<?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 registrations table exists
    try {
        $stmt = $pdo->query("SHOW TABLES LIKE 'event_registrations'");
        if ($stmt->rowCount() == 0) {
            // If table doesn't exist, return empty stats
            echo json_encode([
                'success' => true,
                'data' => [
                    'total' => 0,
                    'confirmed' => 0,
                    'pending' => 0,
                    'cancelled' => 0
                ],
                'message' => 'Registrations table not found'
            ]);
            exit;
        }
    } catch (Exception $e) {
        // If error checking table, return empty stats
        echo json_encode([
            'success' => true,
            'data' => [
                'total' => 0,
                'confirmed' => 0,
                'pending' => 0,
                'cancelled' => 0
            ],
            'message' => 'Error checking registrations table'
        ]);
        exit;
    }
    
    // Get registration stats
    $query = "
        SELECT 
            COUNT(*) as total,
            COUNT(CASE WHEN status = 'confirmed' THEN 1 END) as confirmed,
            COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
            COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled,
            SUM(amount_paid) as total_paid
        FROM 
            event_registrations
        WHERE 
            event_id = :event_id
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([':event_id' => $eventId]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Format numbers
    $stats['total'] = (int)$stats['total'];
    $stats['confirmed'] = (int)$stats['confirmed'];
    $stats['pending'] = (int)$stats['pending'];
    $stats['cancelled'] = (int)$stats['cancelled'];
    $stats['total_paid'] = $stats['total_paid'] ? (float)$stats['total_paid'] : 0;
    
    echo json_encode([
        'success' => true,
        'data' => $stats
    ]);
    
} catch (Exception $e) {
    error_log('Error fetching registration stats: ' . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'Error: ' . $e->getMessage(),
        'data' => [
            'total' => 0,
            'confirmed' => 0,
            'pending' => 0,
            'cancelled' => 0,
            'total_paid' => 0
        ]
    ]);
}
?>
