<?php
// Public endpoint — authenticated via secret token, NOT via session/login,
// so that Google Calendar / Outlook / Apple Calendar can poll it directly.
require_once 'includes/config.php';

$token = $_GET['token'] ?? '';
if (!$token) { http_response_code(403); header('Content-Type: text/plain'); die('Missing token.'); }

$stmt = $pdo->prepare("SELECT id, name FROM users WHERE calendar_token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch();
if (!$user) { http_response_code(403); header('Content-Type: text/plain'); die('Invalid or revoked token.'); }
$uid = $user['id'];

function icsEscape($s) {
    return str_replace(["\\", ",", ";", "\n"], ["\\\\", "\\,", "\\;", "\\n"], (string)$s);
}
function toUtcStamp(DateTime $dt) {
    $u = clone $dt;
    $u->setTimezone(new DateTimeZone('UTC'));
    return $u->format('Ymd\THis\Z');
}

$tz = new DateTimeZone('Asia/Colombo');
$now = new DateTime('now', $tz);

$lines = [];
$lines[] = 'BEGIN:VCALENDAR';
$lines[] = 'VERSION:2.0';
$lines[] = 'PRODID:-//StudyTrack//Calendar Sync//EN';
$lines[] = 'CALSCALE:GREGORIAN';
$lines[] = 'METHOD:PUBLISH';
$lines[] = 'X-WR-CALNAME:StudyTrack — ' . icsEscape($user['name']);
$lines[] = 'X-WR-TIMEZONE:Asia/Colombo';
$lines[] = 'REFRESH-INTERVAL;VALUE=DURATION:PT6H';
$lines[] = 'X-PUBLISHED-TTL:PT6H';

$dayMap = ['Monday'=>'MO','Tuesday'=>'TU','Wednesday'=>'WE','Thursday'=>'TH','Friday'=>'FR','Saturday'=>'SA','Sunday'=>'SU'];
$dayNum = ['Monday'=>1,'Tuesday'=>2,'Wednesday'=>3,'Thursday'=>4,'Friday'=>5,'Saturday'=>6,'Sunday'=>7];

// ── 1. Weekly recurring timetable slots ─────────────────────────
$tt = $pdo->prepare("SELECT t.*, s.name AS subject_name FROM timetable t LEFT JOIN subjects s ON s.id=t.subject_id WHERE t.user_id=? AND t.is_active=1");
$tt->execute([$uid]);
foreach ($tt->fetchAll() as $row) {
    $todayNum = (int)$now->format('N');
    $targetNum = $dayNum[$row['day_of_week']] ?? 1;
    $diff = ($targetNum - $todayNum + 7) % 7;
    $start = clone $now;
    $start->modify("+{$diff} days");
    [$h,$m,$sec] = explode(':', $row['start_time']);
    $start->setTime((int)$h, (int)$m, (int)$sec);
    $end = clone $now;
    $end->modify("+{$diff} days");
    [$eh,$em,$es] = explode(':', $row['end_time']);
    $end->setTime((int)$eh, (int)$em, (int)$es);

    $label = $row['label'] ?: ($row['subject_name'] ?: 'Study Session');
    $lines[] = 'BEGIN:VEVENT';
    $lines[] = 'UID:st-timetable-' . $row['id'] . '@studytrack.edurx.icu';
    $lines[] = 'DTSTAMP:' . toUtcStamp($now);
    $lines[] = 'DTSTART:' . toUtcStamp($start);
    $lines[] = 'DTEND:' . toUtcStamp($end);
    $lines[] = 'RRULE:FREQ=WEEKLY;BYDAY=' . ($dayMap[$row['day_of_week']] ?? 'MO');
    $lines[] = 'SUMMARY:' . icsEscape('📘 ' . $label);
    $lines[] = 'DESCRIPTION:' . icsEscape('StudyTrack timetable — ' . ($row['subject_name'] ?: 'General'));
    $lines[] = 'END:VEVENT';
}

// ── 2. A/L exam dates (global, active) ───────────────────────────
$ex = $pdo->query("SELECT * FROM al_exam_dates WHERE is_active=1");
foreach ($ex->fetchAll() as $row) {
    $d = new DateTime($row['exam_date'], $tz);
    $lines[] = 'BEGIN:VEVENT';
    $lines[] = 'UID:st-exam-' . $row['id'] . '@studytrack.edurx.icu';
    $lines[] = 'DTSTAMP:' . toUtcStamp($now);
    $lines[] = 'DTSTART;VALUE=DATE:' . $d->format('Ymd');
    $lines[] = 'SUMMARY:' . icsEscape('📝 ' . $row['exam_name']);
    if ($row['description']) $lines[] = 'DESCRIPTION:' . icsEscape($row['description']);
    $lines[] = 'END:VEVENT';
}

// ── 3. Task due dates (pending/in_progress only) ─────────────────
$tk = $pdo->prepare("SELECT * FROM tasks WHERE user_id=? AND due_date IS NOT NULL AND status != 'completed'");
$tk->execute([$uid]);
foreach ($tk->fetchAll() as $row) {
    $d = new DateTime($row['due_date'], $tz);
    $lines[] = 'BEGIN:VEVENT';
    $lines[] = 'UID:st-task-' . $row['id'] . '@studytrack.edurx.icu';
    $lines[] = 'DTSTAMP:' . toUtcStamp($now);
    $lines[] = 'DTSTART;VALUE=DATE:' . $d->format('Ymd');
    $lines[] = 'SUMMARY:' . icsEscape('✅ ' . $row['title']);
    if ($row['description']) $lines[] = 'DESCRIPTION:' . icsEscape($row['description']);
    $lines[] = 'END:VEVENT';
}

// ── 4. Goal deadlines (active only) ───────────────────────────────
$gl = $pdo->prepare("SELECT * FROM goals WHERE user_id=? AND deadline IS NOT NULL AND status='active'");
$gl->execute([$uid]);
foreach ($gl->fetchAll() as $row) {
    $d = new DateTime($row['deadline'], $tz);
    $lines[] = 'BEGIN:VEVENT';
    $lines[] = 'UID:st-goal-' . $row['id'] . '@studytrack.edurx.icu';
    $lines[] = 'DTSTAMP:' . toUtcStamp($now);
    $lines[] = 'DTSTART;VALUE=DATE:' . $d->format('Ymd');
    $lines[] = 'SUMMARY:' . icsEscape('🎯 Goal due: ' . $row['title']);
    $lines[] = 'END:VEVENT';
}

$lines[] = 'END:VCALENDAR';

header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename="studytrack.ics"');
echo implode("\r\n", $lines) . "\r\n";
