<?php
// /evento.ics  (y /agenda.ics redirige aquí)
declare(strict_types=1);

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/inc/eventos_helpers.php';

$pdo->exec("SET NAMES utf8mb4");

$id = (int)($_GET['id'] ?? 0);

header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="agenda-costa-tropical.ics"');

$esc = fn($s) => str_replace(["\r\n", "\n", ',', ';'], ['\\n', '\\n', '\\,', '\\;'], (string)$s);

$out = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//Diario Costa Tropical//Agenda//ES',
    'CALSCALE:GREGORIAN',
    'METHOD:PUBLISH',
    'X-WR-CALNAME:Agenda Costa Tropical',
    'X-WR-TIMEZONE:Europe/Madrid',
];

if ($id > 0) {
    $st = $pdo->prepare("SELECT e.*, ci.nombre AS ciudad_nombre FROM eventos e LEFT JOIN ciudades ci ON ci.id = e.ciudad_id WHERE e.id = ?");
    $st->execute([$id]);
    $eventos = $st->fetchAll(PDO::FETCH_ASSOC);
} else {
    $eventos = $pdo->query("
        SELECT e.*, ci.nombre AS ciudad_nombre
        FROM eventos e
        LEFT JOIN ciudades ci ON ci.id = e.ciudad_id
        WHERE e.estado = 'programado' AND e.fecha_inicio >= CURDATE()
        ORDER BY e.fecha_inicio ASC
        LIMIT 500
    ")->fetchAll(PDO::FETCH_ASSOC);
}

foreach ($eventos as $ev) {
    $hora = $ev['hora_inicio'] ?: '09:00';
    $dtstart = date('Ymd\THis', strtotime($ev['fecha_inicio'] . ' ' . $hora));
    $dtend   = !empty($ev['fecha_fin'])
        ? date('Ymd\THis', strtotime($ev['fecha_fin'] . ' 23:59'))
        : date('Ymd\THis', strtotime($ev['fecha_inicio'] . ' ' . $hora . ' +2 hours'));

    $out[] = 'BEGIN:VEVENT';
    $out[] = 'UID:evento-' . $ev['id'] . '@diariocostatropical.es';
    $out[] = 'DTSTAMP:' . gmdate('Ymd\THis\Z');
    $out[] = 'DTSTART:' . $dtstart;
    $out[] = 'DTEND:' . $dtend;
    $out[] = 'SUMMARY:' . $esc($ev['titulo']);
    if ($ev['descripcion']) $out[] = 'DESCRIPTION:' . $esc($ev['descripcion']);
    $loc = trim(($ev['lugar'] ?? '') . ($ev['ciudad_nombre'] ? ', ' . $ev['ciudad_nombre'] : ''));
    if ($loc) $out[] = 'LOCATION:' . $esc($loc);
    $out[] = 'URL:' . urlAbsoluta('evento/' . $ev['id']);
    $out[] = 'END:VEVENT';
}

$out[] = 'END:VCALENDAR';

echo implode("\r\n", $out);