<?php
// /evento.ics
declare(strict_types=1);

// Limpiar cualquier búfer o espacio previo en blanco
while (ob_get_level()) {
    ob_end_clean();
}
ob_start();

ini_set('display_errors', '0');
error_reporting(0);

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

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

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

// Cabeceras estrictas de calendario
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="agenda-costa-tropical.ics"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

$formatIcalProperty = function(string $key, string $value): string {
    $value = str_replace(["\r\n", "\n", "\r"], "\\n", $value);
    $value = str_replace(['\\', ',', ';'], ['\\\\', '\\,', '\\;'], $value);
    
    $line = $key . ':' . $value;
    
    $result = '';
    while (mb_strlen($line, 'UTF-8') > 75) {
        $chunk = mb_substr($line, 0, 75, 'UTF-8');
        $result .= $chunk . "\r\n ";
        $line = mb_substr($line, 75, null, 'UTF-8');
    }
    $result .= $line;
    
    return $result;
};

$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 = !empty($ev['hora_inicio']) ? substr($ev['hora_inicio'], 0, 5) : '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[] = $formatIcalProperty('SUMMARY', (string)$ev['titulo']);
    
    if (!empty($ev['descripcion'])) {
        $out[] = $formatIcalProperty('DESCRIPTION', strip_tags($ev['descripcion']));
    }
    
    $loc = trim(($ev['lugar'] ?? '') . ($ev['ciudad_nombre'] ? ', ' . $ev['ciudad_nombre'] : ''));
    if (!empty($loc)) {
        $out[] = $formatIcalProperty('LOCATION', $loc);
    }
    
    $out[] = $formatIcalProperty('URL', urlAbsoluta('evento/' . $ev['id']));
    $out[] = "END:VEVENT";
}

$out[] = "END:VCALENDAR";

$finalOutput = implode("\r\n", $out);

// Limpiar búfer por completo y eliminar cualquier BOM residual que haya introducido el editor web
ob_clean();
echo ltrim($finalOutput, "\xEF\xBB\xBF");
exit;