<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth_enhanced.php';

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

// Check authentication
if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

try {
    $database = new Database();
    $pdo = $database->getConnection();

    $stmt = $pdo->query("
        SELECT m.id, m.kso_id, m.first_name, m.last_name, m.nickname, m.email, m.phone, 
               m.gender, m.blood_group, m.college, m.course, m.year_of_study,
               m.membership_type, m.status, m.approved_at, m.membership_expiry_date,
               m.session_from_year, m.session_to_year, m.created_at,
               COALESCE(m.photo_url, 'No photo') as photo_url,
               CASE 
                   WHEN m.membership_type = 'Family' THEN 
                       (SELECT COUNT(*) FROM dependents d WHERE d.member_id = m.id)
                   ELSE 0 
               END as dependent_count
        FROM members m
        ORDER BY m.created_at DESC
    ");
    $members = $stmt->fetchAll();

    echo json_encode(['success' => true, 'data' => $members]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
