<?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();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get start and end parameters from the request (if provided by FullCalendar)
    $start = isset($_GET['start']) ? $_GET['start'] : date('Y-m-01');
    $end = isset($_GET['end']) ? $_GET['end'] : date('Y-m-t');
    
    // Query to get all events
    $stmt = $conn->prepare("
        SELECT 
            id,
            title,
            description,
            location,
            start_date,
            end_date,
            start_time,
            end_time,
            all_day,
            recurring,
            recurrence_pattern,
            color,
            status,
            organizer_id,
            max_participants,
            registration_required,
            created_at,
            updated_at
        FROM events
        WHERE (start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?)
        ORDER BY start_date ASC
    ");
    $stmt->execute([$start, $end, $start, $end]);
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the events for FullCalendar
    $formattedEvents = [];
    foreach ($events as $event) {
        $startDateTime = $event['start_date'];
        $endDateTime = $event['end_date'];
        
        // If not all-day event, include time
        if (!$event['all_day']) {
            $startDateTime .= 'T' . $event['start_time'];
            $endDateTime .= 'T' . $event['end_time'];
        }
        
        // Default color based on status
        $color = '';
        switch ($event['status']) {
            case 'draft':
                $color = '#6c757d'; // Grey
                break;
            case 'scheduled':
                $color = '#007bff'; // Blue
                break;
            case 'cancelled':
                $color = '#dc3545'; // Red
                break;
            case 'completed':
                $color = '#28a745'; // Green
                break;
            default:
                $color = '#fd7e14'; // Orange
        }
        
        // Use custom color if specified
        if (!empty($event['color'])) {
            $color = $event['color'];
        }
        
        $formattedEvents[] = [
            'id' => $event['id'],
            'title' => $event['title'],
            'start' => $startDateTime,
            'end' => $endDateTime,
            'allDay' => (bool)$event['all_day'],
            'backgroundColor' => $color,
            'borderColor' => $color,
            'extendedProps' => [
                'description' => $event['description'],
                'location' => $event['location'],
                'status' => $event['status'],
                'registration_required' => (bool)$event['registration_required'],
                'max_participants' => $event['max_participants']
            ]
        ];
    }
    
    echo json_encode([
        'success' => true,
        'events' => $formattedEvents
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
