<?php
require_once '../config/database.php';
header('Content-Type: application/json');

try {
    // Temporarily bypass authentication for testing
    // TODO: Re-enable authentication once login system is working
    // if (!isAuthenticated()) {
    //     echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    //     exit;
    // }

    $member_id = $_GET['id'] ?? '';
    
    if (empty($member_id)) {
        echo json_encode(['success' => false, 'message' => 'Member ID is required']);
        exit;
    }

    $pdo = getDBConnection();

    // Get member details
    $stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
    $stmt->execute([$member_id]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$member) {
        echo json_encode(['success' => false, 'message' => 'Member not found']);
        exit;
    }

    // Get dependents if family membership
    $dependents = [];
    if ($member['membership_type'] === 'Family') {
        $stmt = $pdo->prepare("SELECT * FROM dependents WHERE member_id = ? ORDER BY created_at");
        $stmt->execute([$member_id]);
        $dependents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    echo json_encode([
        'success' => true,
        'data' => [
            'member' => $member,
            'dependents' => $dependents
        ]
    ]);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
