<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/countries.php';

$user = require_login();
$type = (string)($_GET['type'] ?? '');
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if (!$id || !in_array($type, ['day', 'item'], true)) { http_response_code(404); exit('Kalendereintrag nicht gefunden.'); }
if ($type === 'day') {
    $query = db()->prepare('SELECT d.id,d.trip_id,d.date,d.title,d.description,t.title AS trip_title,t.created_by FROM ' . table('trip_days') . ' d JOIN ' . table('trips') . ' t ON t.id=d.trip_id WHERE d.id=:id');
} else {
    $query = db()->prepare('SELECT i.id,i.time,i.title,i.trip_additional_info,d.trip_id,d.date,d.title AS day_title,t.title AS trip_title,t.created_by,COALESCE(a.name,ac.name,r.name,cp.name) AS catalog_title,COALESCE(a.description,ac.description,r.description,cp.description) AS description,COALESCE(a.address,ac.address,r.address,cp.address) AS address,COALESCE(a.city,ac.city,r.city,cp.city) AS city,COALESCE(a.country_code,ac.country_code,r.country_code,cp.country_code) AS country_code,COALESCE(a.google_maps_url,ac.google_maps_url,r.google_maps_url,cp.google_maps_url) AS maps_url FROM ' . table('trip_day_items') . ' i JOIN ' . table('trip_days') . ' d ON d.id=i.trip_day_id JOIN ' . table('trips') . ' t ON t.id=d.trip_id LEFT JOIN ' . table('attractions') . " a ON i.item_type='attraction' AND a.id=i.reference_id LEFT JOIN " . table('accommodations') . " ac ON i.item_type='accommodation' AND ac.id=i.reference_id LEFT JOIN " . table('restaurants') . " r ON i.item_type='restaurant' AND r.id=i.reference_id LEFT JOIN " . table('custom_points') . " cp ON i.item_type='catalog_custom' AND cp.id=i.reference_id WHERE i.id=:id");
}
$query->execute([':id' => $id]); $entry = $query->fetch();
if (!$entry) { http_response_code(404); exit('Kalendereintrag nicht gefunden.'); }
if ($user['role'] !== 'main_admin' && (int)$entry['created_by'] !== (int)$user['id']) {
    $access = db()->prepare('SELECT 1 FROM ' . table('trip_admins') . ' WHERE trip_id=:trip AND user_id=:user UNION SELECT 1 FROM ' . table('trip_participants') . ' WHERE trip_id=:trip AND user_id=:user LIMIT 1');
    $access->execute([':trip' => $entry['trip_id'], ':user' => $user['id']]);
    if (!$access->fetchColumn()) { http_response_code(403); exit('Kein Zugriff auf diesen Kalendereintrag.'); }
}
function ical_escape(string $value): string { return str_replace(["\\", ";", ",", "\r\n", "\r", "\n"], ["\\\\", "\\;", "\\,", "\\n", "\\n", "\\n"], trim(html_entity_decode(strip_tags($value), ENT_QUOTES, 'UTF-8'))); }
function ical_line(string $name, string $value): string { return $name . ':' . ical_escape($value) . "\r\n"; }
$stamp = gmdate('Ymd\\THis\\Z');
if ($type === 'day') {
    $start = str_replace('-', '', (string)$entry['date']); $end = date('Ymd', strtotime((string)$entry['date'] . ' +1 day'));
    $summary = t('calendar.day_prefix') . ': ' . $entry['title'] . ' · ' . $entry['trip_title']; $description = (string)$entry['description'];
    $dateLines = "DTSTART;VALUE=DATE:$start\r\nDTEND;VALUE=DATE:$end\r\n"; $fileName = 'TripTale-Tag-' . $entry['id'] . '.ics';
} else {
    $summary = trim((string)($entry['title'] ?: $entry['catalog_title'] ?: t('type.custom'))) . ' · ' . $entry['trip_title'];
    $description = trim((string)$entry['description'] . "\n\n" . t('calendar.trip_note') . ":\n" . (string)$entry['trip_additional_info']);
    $location = implode(', ', array_filter([(string)($entry['address'] ?? ''), (string)($entry['city'] ?? ''), triptale_countries()[(string)($entry['country_code'] ?? '')] ?? '']));
    $date = str_replace('-', '', (string)$entry['date']);
    if (!empty($entry['time'])) { $startTime = strtotime((string)$entry['date'] . ' ' . (string)$entry['time']); $dateLines = 'DTSTART:' . date('Ymd\\THis', $startTime) . "\r\nDTEND:" . date('Ymd\\THis', $startTime + 3600) . "\r\n"; }
    else { $dateLines = "DTSTART;VALUE=DATE:$date\r\nDTEND;VALUE=DATE:" . date('Ymd', strtotime((string)$entry['date'] . ' +1 day')) . "\r\n"; }
    $fileName = 'TripTale-Programmpunkt-' . $entry['id'] . '.ics';
}
$calendar = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//TripTale//DE\r\nCALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\nBEGIN:VEVENT\r\n";
$calendar .= 'UID:triptale-' . $type . '-' . (int)$entry['id'] . '@triptale.willhoff.de' . "\r\nDTSTAMP:$stamp\r\n" . $dateLines . ical_line('SUMMARY', $summary) . ical_line('DESCRIPTION', $description);
if (!empty($location)) { $calendar .= ical_line('LOCATION', $location); }
if ($type === 'item' && !empty($entry['maps_url'])) { $calendar .= ical_line('URL', (string)$entry['maps_url']); }
$calendar .= "END:VEVENT\r\nEND:VCALENDAR\r\n";
header('Content-Type: text/calendar; charset=utf-8'); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Cache-Control: no-store'); echo $calendar;
