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

header('Content-Type: application/json');

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

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

if (!$beneficiary_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid beneficiary ID.']);
    exit();
}

try {
    // Security check: ensure the beneficiary belongs to the logged-in user
    $stmt = $db->prepare("SELECT * FROM beneficiaries WHERE id = ? AND user_id = ?");
    $stmt->execute([$beneficiary_id, $_SESSION['user_id']]);
    $beneficiary = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($beneficiary) {
        echo json_encode(['success' => true, 'beneficiary' => $beneficiary]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Beneficiary not found or you don\'t have permission to view it.']);
    }
} catch (PDOException $e) {
    error_log("Get Beneficiary Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred while fetching the beneficiary details.']);
}
?>
