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

try {
    // Check if user is authenticated
    if (!isAuthenticated()) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }

    $pdo = getDBConnection();

    // Check if members table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'members'");
    if ($stmt->rowCount() == 0) {
        echo json_encode(['success' => true, 'data' => []]);
        exit;
    }

    // Fetch all active members for dropdown
    $stmt = $pdo->query("SELECT id, name, kso_id FROM members WHERE status = 'approved' ORDER BY name");
    $members = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

} 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()]);
}
?>
