<?php
session_start();
require_once '../config/config.php';

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get event ID from query string
$event_id = $_GET['id'] ?? '';

// Validate required field
if (empty($event_id)) {
    echo json_encode(['success' => false, 'message' => 'Event ID is required']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get event details
    $stmt = $conn->prepare("
        SELECT 
            e.*,
            a.name as organizer_name
        FROM events e
        LEFT JOIN admins a ON e.organizer_id = a.id
        WHERE e.id = ?
    ");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        echo json_encode(['success' => false, 'message' => 'Event not found']);
        exit();
    }
    
    // Get registration count
    $stmt = $conn->prepare("
        SELECT COUNT(*) as registration_count
        FROM event_registrations
        WHERE event_id = ?
    ");
    $stmt->execute([$event_id]);
    $registrationCount = $stmt->fetchColumn();
    
    // Add registration count to event data
    $event['registration_count'] = (int)$registrationCount;
    
    // Get available spots
    if ($event['max_participants'] > 0) {
        $event['available_spots'] = $event['max_participants'] - $registrationCount;
    } else {
        $event['available_spots'] = null; // Unlimited
    }
    
    echo json_encode([
        'success' => true,
        'event' => $event
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
