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

try {
    $pdo = getDBConnection();

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

    // Get events in calendar format
    $stmt = $pdo->query("
        SELECT id, title, description, event_date, event_time, location, status,
               CONCAT(event_date, ' ', IFNULL(event_time, '00:00:00')) as start
        FROM events 
        ORDER BY event_date ASC
    ");
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format for calendar
    $calendarEvents = [];
    foreach ($events as $event) {
        $calendarEvents[] = [
            'id' => $event['id'],
            'title' => $event['title'],
            'start' => $event['start'],
            'description' => $event['description'],
            'location' => $event['location'],
            'status' => $event['status'],
            'className' => 'event-' . $event['status']
        ];
    }

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

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
