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

// FullCalendar sends 'start' and 'end' param (ISO8601)
$start = $_GET['start'] ?? date('Y-m-d');
$end = $_GET['end'] ?? date('Y-m-d', strtotime('+1 month'));

try {
    $stmt = $pdo->prepare("SELECT * FROM calendar_events WHERE event_date BETWEEN ? AND ?");
    $stmt->execute([$start, $end]);
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted = [];
    foreach ($events as $e) {
        // Convert to FullCalendar Event Object
        // https://fullcalendar.io/docs/event-object
        $formatted[] = [
            'id' => $e['id'],
            'title' => $e['title'],
            'start' => $e['event_date'] . ($e['event_time'] ? 'T' . $e['event_time'] : ''),
            // 'end' => ... if duration logic existed
            'description' => $e['description'],
            'extendedProps' => [
                'prayer_time' => $e['prayer_time'] ? date('h:i A', strtotime($e['prayer_time'])) : null,
                'desc' => $e['description']
            ],
            'allDay' => empty($e['event_time'])
        ];
    }

    echo json_encode($formatted);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
