<?php
// Filename: api_calendar.php
require 'config.php';
requireLogin();

header('Content-Type: application/json; charset=utf-8');

// 1. INPUT VALIDATION
$date = $_GET['date'] ?? '';
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid date format']);
    exit;
}

// 2. CACHE CONFIGURATION
$cache_dir = __DIR__ . '/cache';
$cache_file = $cache_dir . '/calendar_data.json';
$cache_time = 86400; // 24 Hours

// 3. LOAD OR REGENERATE DATA (Concurrency Safe)
$all_holidays = [];
$cache_valid = file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_time);

if ($cache_valid) {
    // Read Cache
    $raw = @file_get_contents($cache_file);
    $all_holidays = $raw ? (json_decode($raw, true) ?: []) : [];
} else {
    // Regenerate Cache (DB Query)
    try {
        // Updated Query: Removed strict date bounds to prevent cutting off overlapping events
        // If your table is huge (10k+ rows), put the date range back. 
        // For school holidays (usually < 500 rows), fetching all is safer and faster.
        $stmt = $pdo->prepare("
            SELECT id, type, description, start_date, end_date 
            FROM school_holidays 
            ORDER BY start_date ASC
        ");
        $stmt->execute();
        $all_holidays = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Atomic Write
        if (!is_dir($cache_dir)) @mkdir($cache_dir, 0755, true);
        $tmp_file = $cache_file . '.tmp';
        if (file_put_contents($tmp_file, json_encode($all_holidays), LOCK_EX)) {
            rename($tmp_file, $cache_file);
        }
    } catch (Exception $e) {
        $all_holidays = [];
    }
}

// 4. FILTER FOR SPECIFIC DATE
// We loop through the cache to find events happening on the requested $date
$dayEvents = [];
foreach ($all_holidays as $h) {
    if ($h['start_date'] <= $date && $h['end_date'] >= $date) {
        $dayEvents[] = [
            'id'       => (int)$h['id'],
            'type'     => $h['type'],
            'desc'     => $h['description'],
            'is_start' => ($date === $h['start_date']),
            'date_end' => $h['end_date']
        ];
    }
}

// 5. SORT PRIORITY (UPDATED)
// National > Term > Cuti Peristiwa > Cuti Ganti > School Event > Others
usort($dayEvents, function($a, $b) {
    // Helper priority function
    $getPriority = function($type) {
        return match($type) {
            'national'       => 1, // Highest
            'term'           => 2,
            'cuti_peristiwa' => 3,
            'cuti_ganti'     => 4,
            'school_event'   => 5,
            'special'        => 6,
            default          => 9
        };
    };

    return $getPriority($a['type']) <=> $getPriority($b['type']);
});

echo json_encode(['ok' => true, 'events' => $dayEvents]);