<?php
/**
 * CFD Today — Parse TeamUp iCal feed for today's events
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$numDaysParam = max(1, min(7, intval($_GET['days'] ?? 1)));
$cacheFile = __DIR__ . "/../uploads/calendar_{$numDaysParam}d_cache.json";
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 900) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

$calKey = TEAMUP_CALENDAR_KEY;
$icsUrl = "https://ics.teamup.com/feed/{$calKey}/0.ics";
$ctx = stream_context_create(['http' => ['timeout' => 10, 'ignore_errors' => true]]);
$ics = @file_get_contents($icsUrl, false, $ctx);

if ($ics === false) {
    if (file_exists($cacheFile)) { header('Content-Type: application/json'); readfile($cacheFile); exit; }
    jsonResponse(['error' => 'Unable to fetch calendar'], 502);
}

$todayStart = strtotime('today');
$todayEnd = strtotime("+{$numDaysParam} days", $todayStart);
$events = [];

// Simple iCal parser
$inEvent = false;
$event = [];
$lines = preg_split('/\r?\n/', $ics);

for ($i = 0; $i < count($lines); $i++) {
    $line = $lines[$i];
    // Handle line continuations (lines starting with space/tab)
    while (isset($lines[$i + 1]) && ($lines[$i + 1][0] ?? '') === ' ') {
        $i++;
        $line .= ltrim($lines[$i]);
    }

    if ($line === 'BEGIN:VEVENT') {
        $inEvent = true;
        $event = [];
    } elseif ($line === 'END:VEVENT') {
        $inEvent = false;
        if (!empty($event)) {
            // Check if event is today
            $dtStart = $event['dtstart'] ?? 0;
            $dtEnd = $event['dtend'] ?? $dtStart;
            $isAllDay = $event['allday'] ?? false;

            if ($isAllDay) {
                if ($dtStart <= $todayStart && $dtEnd > $todayStart) {
                    $events[] = $event;
                }
            } elseif (($dtStart >= $todayStart && $dtStart < $todayEnd) || ($dtStart < $todayStart && $dtEnd > $todayStart)) {
                $events[] = $event;
            }
        }
    } elseif ($inEvent) {
        if (preg_match('/^SUMMARY[;:](.*)/', $line, $m)) {
            $event['summary'] = trim($m[1]);
        } elseif (preg_match('/^DTSTART[;:](.*)/', $line, $m)) {
            $val = trim($m[1]);
            if (preg_match('/VALUE=DATE:(\d{8})/', $val, $dm)) {
                $event['dtstart'] = strtotime($dm[1]);
                $event['allday'] = true;
                $event['time'] = 'All Day';
            } else {
                $ts = preg_replace('/^.*:/', '', $val);
                $event['dtstart'] = strtotime($ts);
                $event['allday'] = false;
                $event['time'] = date('g:i A', $event['dtstart']);
            }
        } elseif (preg_match('/^DTEND[;:](.*)/', $line, $m)) {
            $val = trim($m[1]);
            if (preg_match('/VALUE=DATE:(\d{8})/', $val, $dm)) {
                $event['dtend'] = strtotime($dm[1]);
            } else {
                $ts = preg_replace('/^.*:/', '', $val);
                $event['dtend'] = strtotime($ts);
                $event['end_time'] = date('g:i A', $event['dtend']);
            }
        } elseif (preg_match('/^LOCATION[;:](.*)/', $line, $m)) {
            $event['location'] = trim($m[1]);
        } elseif (preg_match('/^DESCRIPTION[;:](.*)/', $line, $m)) {
            $event['description'] = trim(str_replace('\\n', "\n", $m[1]));
        }
    }
}

// Sort by time
usort($events, fn($a, $b) => ($a['dtstart'] ?? 0) - ($b['dtstart'] ?? 0));

// Clean output — expand multi-day all-day events across each day they span
$output = [];
foreach ($events as $e) {
    $isAllDay = $e['allday'] ?? false;
    $dtStart = $e['dtstart'] ?? time();
    $dtEnd = $e['dtend'] ?? $dtStart + 86400;

    if ($isAllDay && $dtEnd > $dtStart + 86400) {
        // Multi-day all-day event: emit one entry per day within the requested range
        $rangeStart = max($dtStart, $todayStart);
        $rangeEnd = min($dtEnd, $todayEnd);
        for ($day = $rangeStart; $day < $rangeEnd; $day += 86400) {
            $output[] = [
                'summary'     => $e['summary'] ?? '',
                'time'        => 'All Day',
                'end_time'    => '',
                'location'    => $e['location'] ?? '',
                'all_day'     => true,
                'date'        => date('Y-m-d', $day),
            ];
        }
    } else {
        $output[] = [
            'summary'     => $e['summary'] ?? '',
            'time'        => $e['time'] ?? '',
            'end_time'    => $e['end_time'] ?? '',
            'location'    => $e['location'] ?? '',
            'all_day'     => $isAllDay,
            'date'        => date('Y-m-d', $dtStart),
        ];
    }
}

$result = ['events' => $output, 'date' => date('l, F j, Y'), 'cached_at' => date('c')];
@file_put_contents($cacheFile, json_encode($result));
jsonResponse($result);
