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

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

// Ensure only authenticated admin users can access
if (!isAuthenticated() || !isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if event ID is provided
if (!isset($_GET['event_id']) || empty($_GET['event_id'])) {
    echo json_encode(['success' => false, 'message' => 'Event ID is required']);
    exit;
}

$eventId = (int)$_GET['event_id'];

try {
    $pdo = getDBConnection();
    
    // Check if event exists
    $stmt = $pdo->prepare("SELECT id, event_title FROM events WHERE id = :id");
    $stmt->execute([':id' => $eventId]);
    $event = $stmt->fetch();
    
    if (!$event) {
        echo json_encode(['success' => false, 'message' => 'Event not found']);
        exit;
    }
    
    // Check if registrations table exists
    try {
        $stmt = $pdo->query("SHOW TABLES LIKE 'event_registrations'");
        if ($stmt->rowCount() == 0) {
            // If table doesn't exist, return empty data
            echo json_encode([
                'success' => true,
                'data' => [],
                'message' => 'No registrations found'
            ]);
            exit;
        }
    } catch (Exception $e) {
        // If error checking table, return empty data
        echo json_encode([
            'success' => true,
            'data' => [],
            'message' => 'Error checking registrations table: ' . $e->getMessage()
        ]);
        exit;
    }
    
    // Fetch registrations with member information
    $query = "
        SELECT 
            er.id,
            er.event_id,
            er.member_id,
            er.registration_date,
            er.payment_status,
            er.amount_paid,
            er.status,
            er.notes,
            m.first_name,
            m.last_name,
            m.kso_id,
            m.email,
            m.phone
        FROM 
            event_registrations er
            LEFT JOIN members m ON er.member_id = m.id
        WHERE 
            er.event_id = :event_id
        ORDER BY 
            er.registration_date DESC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([':event_id' => $eventId]);
    $registrations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $registrations,
        'count' => count($registrations),
        'event_id' => $eventId,
        'event_title' => $event['event_title']
    ]);
    
} catch (Exception $e) {
    error_log('Error fetching event registrations: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
