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

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

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

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

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

try {
    $pdo = getDBConnection();
    
    // Fetch event details
    $stmt = $pdo->prepare("
        SELECT 
            id,
            event_title,
            event_description,
            event_banner_url,
            event_date,
            event_time,
            event_location,
            event_type,
            max_participants,
            registration_fee,
            status,
            created_by,
            created_at,
            updated_at
        FROM events 
        WHERE id = :id
    ");
    
    $stmt->execute([':id' => $eventId]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        echo json_encode(['success' => false, 'message' => 'Event not found']);
        exit;
    }
    
    // Fetch registration count
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as registration_count
        FROM event_registrations
        WHERE event_id = :event_id
    ");
    
    $registrationCount = 0;
    
    try {
        $stmt->execute([':event_id' => $eventId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $registrationCount = $result ? (int)$result['registration_count'] : 0;
    } catch (Exception $e) {
        // Table might not exist yet, continue with count as 0
    }
    
    // Format data for frontend
    $formattedEvent = [
        'id' => $event['id'],
        'event_title' => $event['event_title'],
        'event_description' => $event['event_description'],
        'event_banner_url' => $event['event_banner_url'],
        'event_date' => $event['event_date'],
        'event_time' => $event['event_time'],
        'event_location' => $event['event_location'],
        'event_type' => $event['event_type'],
        'max_participants' => $event['max_participants'],
        'registration_fee' => $event['registration_fee'],
        'status' => $event['status'],
        'created_by' => $event['created_by'],
        'created_at' => $event['created_at'],
        'updated_at' => $event['updated_at'],
        'registration_count' => $registrationCount
    ];
    
    echo json_encode([
        'success' => true, 
        'data' => $formattedEvent
    ]);
    
} catch (Exception $e) {
    error_log('Error fetching event details: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
