<?php
session_start();
require_once 'includes/auth_check.php';

$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $beneficiary_id = filter_input(INPUT_POST, 'beneficiary_id', FILTER_VALIDATE_INT);
    $name = trim($_POST['name'] ?? '');
    $account_number = trim($_POST['account_number'] ?? '');
    $bank_name = trim($_POST['bank_name'] ?? '');
    $account_type = trim($_POST['account_type'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $is_favorite = isset($_POST['is_favorite']) ? 1 : 0;
    
    // Validate inputs
    $errors = [];
    
    if (!$beneficiary_id) {
        $errors[] = "Invalid beneficiary ID.";
    }
    
    if (empty($name)) {
        $errors[] = "Beneficiary name is required.";
    }
    
    if (empty($account_number)) {
        $errors[] = "Account number is required.";
    }
    
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }
    
    // If no errors, update the database
    if (empty($errors)) {
        try {
            // Security check: ensure the beneficiary belongs to the logged-in user
            $stmt = $db->prepare("
                UPDATE beneficiaries 
                SET name = ?, account_number = ?, bank_name = ?, account_type = ?, 
                    email = ?, phone = ?, is_favorite = ?, updated_at = NOW() 
                WHERE id = ? AND user_id = ?
            ");
            
            $stmt->execute([
                $name,
                $account_number,
                $bank_name,
                $account_type,
                $email,
                $phone,
                $is_favorite,
                $beneficiary_id,
                $_SESSION['user_id']
            ]);
            
            if ($stmt->rowCount() > 0) {
                $_SESSION['success_message'] = "Beneficiary has been updated successfully.";
            } else {
                $_SESSION['error_message'] = "Beneficiary not found or you don't have permission to edit it.";
            }
            
            header("Location: beneficiaries.php");
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "An error occurred while updating the beneficiary.";
            error_log("Edit Beneficiary Error: " . $e->getMessage());
            header("Location: beneficiaries.php");
            exit();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
        header("Location: beneficiaries.php");
        exit();
    }
} else {
    // If not a POST request, redirect to beneficiaries page
    header("Location: beneficiaries.php");
    exit();
}
?>
