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

$user = require_login();
$tripId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if (!$tripId) { http_response_code(404); exit('Reise nicht gefunden.'); }

if ($user['role'] === 'main_admin') {
    $query = db()->prepare('SELECT * FROM ' . table('trips') . ' WHERE id=:id');
    $query->execute([':id' => $tripId]);
} else {
    $query = db()->prepare('SELECT t.* FROM ' . table('trips') . ' t WHERE t.id=:id AND (t.created_by=:user OR EXISTS (SELECT 1 FROM ' . table('trip_admins') . ' a WHERE a.trip_id=t.id AND a.user_id=:user) OR EXISTS (SELECT 1 FROM ' . table('trip_participants') . ' p WHERE p.trip_id=t.id AND p.user_id=:user))');
    $query->execute([':id' => $tripId, ':user' => $user['id']]);
}
$trip = $query->fetch();
if (!$trip) { http_response_code(403); exit('Du hast keinen Zugriff auf diese Reise.'); }

$theme = ['site_primary_color' => '#126e82', 'site_accent_color' => '#e3ebee'];
try {
    $theme = db()->query("SELECT setting_key, setting_value FROM " . table('settings') . " WHERE setting_key IN ('site_primary_color','site_accent_color')")->fetchAll(PDO::FETCH_KEY_PAIR) + $theme;
} catch (Throwable $exception) {}
$pdfColor = static function (string $hex, string $fallback): array {
    $hex = triptale_theme_color($hex, $fallback);
    return [hexdec(substr($hex, 1, 2)) / 255, hexdec(substr($hex, 3, 2)) / 255, hexdec(substr($hex, 5, 2)) / 255];
};
$pdfPrimary = $pdfColor((string)($theme['site_primary_color'] ?? ''), '#126e82');
$pdfAccent = $pdfColor((string)($theme['site_accent_color'] ?? ''), '#e3ebee');

$defaults = ['plan' => true, 'trip_image' => true, 'item_images' => true, 'comment_images' => true, 'note_images' => true, 'maps' => true, 'notes' => false, 'comments' => false];
$selected = $defaults;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    foreach (array_keys($selected) as $key) { $selected[$key] = isset($_POST[$key]); }
}
$selected['images'] = $selected['trip_image'];

$daysQuery = db()->prepare('SELECT id,day_number,date,title,description FROM ' . table('trip_days') . ' WHERE trip_id=:trip ORDER BY day_number');
$daysQuery->execute([':trip' => $tripId]);
$days = $daysQuery->fetchAll();
$itemsByDay = [];
if ($days) {
    $ids = array_map(static fn(array $day): int => (int)$day['id'], $days);
    $marks = implode(',', array_fill(0, count($ids), '?'));
    $itemsQuery = db()->prepare('SELECT i.id,i.trip_day_id,i.item_type,i.title,i.time,i.trip_additional_info,i.image_path AS own_image,a.name AS attraction_name,a.description AS attraction_description,a.address AS attraction_address,a.city AS attraction_city,a.google_maps_url AS attraction_maps,a.image_path AS attraction_image,ac.name AS accommodation_name,ac.description AS accommodation_description,ac.address AS accommodation_address,ac.city AS accommodation_city,ac.google_maps_url AS accommodation_maps,ac.image_path AS accommodation_image,r.name AS restaurant_name,r.description AS restaurant_description,r.address AS restaurant_address,r.city AS restaurant_city,r.google_maps_url AS restaurant_maps,r.image_path AS restaurant_image,cp.name AS custom_name,cp.description AS custom_description,cp.address AS custom_address,cp.city AS custom_city,cp.google_maps_url AS custom_maps,cp.image_path AS custom_image FROM ' . table('trip_day_items') . ' i 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.trip_day_id IN ($marks) ORDER BY i.trip_day_id,i.sort_order,i.id");
    $itemsQuery->execute($ids);
    foreach ($itemsQuery->fetchAll() as $item) { $itemsByDay[(int)$item['trip_day_id']][] = $item; }
}

$commentsAtTrip = $commentsAtDay = $commentsAtItem = [];
if ($selected['comments']) {
    $comments = db()->prepare('SELECT c.id,c.trip_day_id,c.trip_day_item_id,c.body,c.created_at,u.first_name,u.last_name FROM ' . table('trip_comments') . ' c JOIN ' . table('users') . ' u ON u.id=c.user_id WHERE c.trip_id=:trip ORDER BY c.created_at');
    $comments->execute([':trip' => $tripId]);
    $commentImages = [];
    $images = db()->prepare('SELECT ci.comment_id,ci.file_path FROM ' . table('trip_comment_images') . ' ci JOIN ' . table('trip_comments') . ' c ON c.id=ci.comment_id WHERE c.trip_id=:trip ORDER BY ci.sort_order,ci.id');
    $images->execute([':trip' => $tripId]);
    foreach ($images->fetchAll() as $image) { $commentImages[(int)$image['comment_id']][] = $image['file_path']; }
    foreach ($comments->fetchAll() as $comment) {
        $comment['images'] = $commentImages[(int)$comment['id']] ?? [];
        if ($comment['trip_day_item_id']) { $commentsAtItem[(int)$comment['trip_day_item_id']][] = $comment; }
        elseif ($comment['trip_day_id']) { $commentsAtDay[(int)$comment['trip_day_id']][] = $comment; }
        else { $commentsAtTrip[] = $comment; }
    }
}
$notesAtTrip = $notesAtDay = $notesAtItem = [];
if ($selected['notes']) {
    $notes = db()->prepare('SELECT id,trip_day_id,trip_day_item_id,title,body,updated_at FROM ' . table('trip_private_notes') . ' WHERE trip_id=:trip AND user_id=:user ORDER BY updated_at');
    $notes->execute([':trip' => $tripId, ':user' => $user['id']]);
    $noteImages = [];
    $images = db()->prepare('SELECT ni.note_id,ni.file_path FROM ' . table('trip_private_note_images') . ' ni JOIN ' . table('trip_private_notes') . ' n ON n.id=ni.note_id WHERE n.trip_id=:trip AND n.user_id=:user ORDER BY ni.sort_order,ni.id');
    $images->execute([':trip' => $tripId, ':user' => $user['id']]);
    foreach ($images->fetchAll() as $image) { $noteImages[(int)$image['note_id']][] = $image['file_path']; }
    foreach ($notes->fetchAll() as $note) {
        $note['images'] = $noteImages[(int)$note['id']] ?? [];
        if ($note['trip_day_item_id']) { $notesAtItem[(int)$note['trip_day_item_id']][] = $note; }
        elseif ($note['trip_day_id']) { $notesAtDay[(int)$note['trip_day_id']][] = $note; }
        else { $notesAtTrip[] = $note; }
    }
}
$writeComments = static function (TripTalePdf $pdf, array $comments) use ($selected, $pdfAccent, $pdfPrimary): void {
    if (!$comments) { return; }
    $pdf->section(t('pdf.comments'), $pdfAccent);
    foreach ($comments as $comment) {
        $card = $pdf->beginCard($pdfPrimary);
        $pdf->heading($comment['first_name'] . ' ' . $comment['last_name'] . ' - ' . date('d.m.Y H:i', strtotime((string)$comment['created_at'])), 10);
        $pdf->richText((string)$comment['body']);
        if ($selected['comment_images'] && !empty($comment['images'])) { $pdf->imageRow(array_map(static fn(string $image): string => __DIR__ . '/' . ltrim($image, '/'), $comment['images'])); }
        $pdf->endCard($card);
    }
};
$writeNotes = static function (TripTalePdf $pdf, array $notes) use ($selected, $pdfAccent, $pdfPrimary): void {
    if (!$notes) { return; }
    $pdf->section(t('pdf.private_notes'), $pdfAccent);
    foreach ($notes as $note) {
        $card = $pdf->beginCard($pdfPrimary);
        if ($note['title']) { $pdf->heading((string)$note['title'], 10); }
        $pdf->paragraph(t('pdf.updated') . ' ' . date('d.m.Y H:i', strtotime((string)$note['updated_at'])), 8);
        $pdf->richText((string)$note['body']);
        if ($selected['note_images'] && !empty($note['images'])) { $pdf->imageRow(array_map(static fn(string $image): string => __DIR__ . '/' . ltrim($image, '/'), $note['images'])); }
        $pdf->endCard($card);
    }
};

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['download'])) {
    $pdf = new TripTalePdf();
    $pdf->heading($trip['title'], 22);
    if ($selected['trip_image'] && !empty($trip['image_path'])) { $pdf->image(__DIR__ . '/' . ltrim((string)$trip['image_path'], '/'), 210); }
    if ($trip['subtitle']) { $pdf->paragraph($trip['subtitle'], 12); }
    $pdf->paragraph(localized_date($trip['start_date']) . ' - ' . localized_date($trip['end_date']), 11);
    if ($trip['description']) { $pdf->richText($trip['description']); }
    $writeComments($pdf, $commentsAtTrip);
    $writeNotes($pdf, $notesAtTrip);
    if ($selected['plan']) {
        foreach ($days as $day) {
            $dayCard = $pdf->beginCard($pdfPrimary);
            $pdf->section(t('pdf.day') . ' ' . (int)$day['day_number'] . ' - ' . $day['title'], $pdfAccent);
            $pdf->paragraph(localized_date($day['date'], true), 10);
            if ($day['description']) { $pdf->richText($day['description']); }
            $writeComments($pdf, $commentsAtDay[(int)$day['id']] ?? []);
            $writeNotes($pdf, $notesAtDay[(int)$day['id']] ?? []);
            foreach ($itemsByDay[(int)$day['id']] ?? [] as $item) {
                $itemColor = match ($item['item_type']) {
                    'attraction' => [0.89, 0.63, 0.44],
                    'accommodation' => [0.57, 0.76, 0.85],
                    'restaurant' => [0.73, 0.64, 0.80],
                    default => [0.57, 0.75, 0.59],
                };
                // Der Rahmen folgt der gewählten Akzentfarbe; der linke Streifen bleibt je Typ farbig.
                $itemCard = $pdf->beginCard($pdfAccent, $itemColor);
                $name = $item['title'] ?: $item['attraction_name'] ?: $item['accommodation_name'] ?: $item['restaurant_name'] ?: $item['custom_name'] ?: t('pdf.program_item');
                $description = $item['attraction_description'] ?: $item['accommodation_description'] ?: $item['restaurant_description'] ?: $item['custom_description'] ?: '';
                $address = $item['attraction_address'] ?: $item['accommodation_address'] ?: $item['restaurant_address'] ?: $item['custom_address'] ?: '';
                $city = $item['attraction_city'] ?: $item['accommodation_city'] ?: $item['restaurant_city'] ?: $item['custom_city'] ?: '';
                $maps = $item['attraction_maps'] ?: $item['accommodation_maps'] ?: $item['restaurant_maps'] ?: $item['custom_maps'] ?: '';
                $image = $item['own_image'] ?: $item['attraction_image'] ?: $item['accommodation_image'] ?: $item['restaurant_image'] ?: $item['custom_image'] ?: '';
                $pdf->section(($item['time'] ? substr((string)$item['time'], 0, 5) . ' - ' : '') . $name, $pdfAccent);
                if ($selected['item_images'] && $image) { $pdf->image(__DIR__ . '/' . ltrim((string)$image, '/'), 150); }
                if ($description) { $pdf->richText($description); }
                if ($address || $city) { $pdf->paragraph(trim($address . ($address && $city ? ' - ' : '') . $city), 9); }
                if ($selected['maps'] && $maps) { $pdf->paragraph(t('pdf.map_link') . ' ' . $maps, 8); }
                if ($item['trip_additional_info']) {
                    $noteCard = $pdf->beginCard($pdfAccent);
                    $pdf->section(t('pdf.trip_note'), $pdfAccent);
                    $pdf->richText((string)$item['trip_additional_info']);
                    $pdf->endCard($noteCard);
                }
                $writeComments($pdf, $commentsAtItem[(int)$item['id']] ?? []);
                $writeNotes($pdf, $notesAtItem[(int)$item['id']] ?? []);
                $pdf->endCard($itemCard);
            }
            $pdf->endCard($dayCard);
        }
    }
    $pdf->output('TripTale-' . $trip['title'] . '-' . trim($user['first_name'] . '-' . $user['last_name'], '-') . '.pdf');
}
?>
<script>document.addEventListener('DOMContentLoaded',function(){var trip=document.querySelector('input[name="images"]');if(!trip)return;trip.name='trip_image';var first=trip.closest('.option');first.querySelector('span').innerHTML='<strong><?= htmlspecialchars(t('pdf.trip_image'),ENT_QUOTES,'UTF-8') ?></strong><?= htmlspecialchars(t('pdf.trip_image_hint'),ENT_QUOTES,'UTF-8') ?>';var entries=[['item_images',<?= tjs('pdf.item_images') ?>,<?= tjs('pdf.item_images_hint') ?>,<?= $selected['item_images']?'true':'false' ?>],['comment_images',<?= tjs('pdf.comment_images') ?>,<?= tjs('pdf.comment_images_hint') ?>,<?= $selected['comment_images']?'true':'false' ?>],['note_images',<?= tjs('pdf.note_images') ?>,<?= tjs('pdf.note_images_hint') ?>,<?= $selected['note_images']?'true':'false' ?>]];var after=first;entries.forEach(function(entry){var label=document.createElement('label');label.className='option';label.innerHTML='<input type="checkbox" name="'+entry[0]+'"'+(entry[3]?' checked':'')+'><span><strong>'+entry[1]+'</strong>'+entry[2]+'</span>';after.after(label);after=label;});});</script>
<!doctype html><html lang="<?= htmlspecialchars(language(),ENT_QUOTES,'UTF-8') ?>"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= htmlspecialchars(t('pdf.title'),ENT_QUOTES,'UTF-8') ?> · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:720px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}.button{display:inline-block;background:#126e82;color:#fff;padding:10px 14px;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.option{display:flex;gap:12px;align-items:flex-start;padding:14px 0;border-top:1px solid #dbe4e8}.option:first-of-type{border-top:0}.option input{width:19px;height:19px;margin-top:2px}.option strong{display:block}.muted{color:#59636d}fieldset{border:0;padding:0;margin:22px 0}*{box-sizing:border-box}@media(max-width:600px){body{padding:12px}main{margin:18px auto;padding:16px}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/trip.php?id=<?= (int)$tripId ?>"><?= htmlspecialchars(t('common.back_to_trip'),ENT_QUOTES,'UTF-8') ?></a><h1><?= htmlspecialchars(t('pdf.title'),ENT_QUOTES,'UTF-8') ?></h1><p class="muted"><?= htmlspecialchars(t('pdf.intro'),ENT_QUOTES,'UTF-8') ?></p><form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8') ?>"><fieldset><label class="option"><input type="checkbox" name="plan"<?= $selected['plan']?' checked':'' ?>><span><strong><?= htmlspecialchars(t('pdf.plan'),ENT_QUOTES,'UTF-8') ?></strong><?= htmlspecialchars(t('pdf.plan_hint'),ENT_QUOTES,'UTF-8') ?></span></label><label class="option"><input type="checkbox" name="images"<?= $selected['images']?' checked':'' ?>><span><strong><?= htmlspecialchars(t('common.images'),ENT_QUOTES,'UTF-8') ?></strong></span></label><label class="option"><input type="checkbox" name="maps"<?= $selected['maps']?' checked':'' ?>><span><strong><?= htmlspecialchars(t('pdf.maps'),ENT_QUOTES,'UTF-8') ?></strong><?= htmlspecialchars(t('pdf.maps_hint'),ENT_QUOTES,'UTF-8') ?></span></label><label class="option"><input type="checkbox" name="comments"<?= $selected['comments']?' checked':'' ?>><span><strong><?= htmlspecialchars(t('pdf.comments'),ENT_QUOTES,'UTF-8') ?></strong><?= htmlspecialchars(t('pdf.comments_hint'),ENT_QUOTES,'UTF-8') ?></span></label><label class="option"><input type="checkbox" name="notes"<?= $selected['notes']?' checked':'' ?>><span><strong><?= htmlspecialchars(t('pdf.private_notes'),ENT_QUOTES,'UTF-8') ?></strong><?= htmlspecialchars(t('pdf.private_notes_hint'),ENT_QUOTES,'UTF-8') ?></span></label></fieldset><button class="button" name="download" value="1" type="submit"><?= htmlspecialchars(t('pdf.download'),ENT_QUOTES,'UTF-8') ?></button></form></main></body></html>
