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

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

$beneficiary_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$beneficiary_id) {
    $_SESSION['error_message'] = "Invalid beneficiary ID.";
    header("Location: beneficiaries.php");
    exit();
}

try {
    // Security check: ensure the beneficiary belongs to the logged-in user
    $stmt = $db->prepare("DELETE FROM beneficiaries WHERE id = ? AND user_id = ?");
    $stmt->execute([$beneficiary_id, $_SESSION['user_id']]);
    
    if ($stmt->rowCount() > 0) {
        $_SESSION['success_message'] = "Beneficiary has been deleted successfully.";
    } else {
        $_SESSION['error_message'] = "Beneficiary not found or you don't have permission to delete it.";
    }
} catch (PDOException $e) {
    $_SESSION['error_message'] = "An error occurred while deleting the beneficiary.";
    error_log("Beneficiary Delete Error: " . $e->getMessage());
}

header("Location: beneficiaries.php");
exit();
?>
