<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';
$tripEditUi = ['title' => t('edit.trip_title'), 'back' => t('common.back_to_trip'), 'image' => t('edit.image'), 'imageSaved' => t('edit.image_saved'), 'imageDeleted' => t('edit.image_deleted'), 'manage' => t('trip.manage'), 'reactivate' => t('trip.reactivate'), 'archive' => t('edit.archive'), 'delete' => t('trip.delete'), 'formTitle' => t('form.title'), 'subtitle' => t('form.subtitle_optional'), 'description' => t('form.description'), 'start' => t('form.start_date'), 'end' => t('form.end_date'), 'group' => t('edit.group_link_optional'), 'status' => t('edit.status'), 'save' => t('edit.save_changes'), 'hint' => t('edit.shift_hint'), 'draft' => t('edit.status_draft'), 'active' => t('edit.status_active'), 'completed' => t('edit.status_completed'), 'archived' => t('edit.status_archived'), 'confirmArchive' => t('edit.confirm_archive'), 'confirmDelete' => t('trip.confirm_delete'), 'editor' => ['bold' => t('editor.bold'), 'italic' => t('editor.italic'), 'list' => t('editor.list'), 'numbered_list' => t('editor.numbered_list'), 'link' => t('editor.link'), 'style' => t('editor.style'), 'normal' => t('editor.normal'), 'heading' => t('editor.heading'), 'small_heading' => t('editor.small_heading')]];
ob_start(static function (string $html) use ($tripEditUi): string {
    if (language() === 'de') { return $html; }
    $ui = json_encode($tripEditUi, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $script = '<script>(function(){const x=' . $ui . ';document.documentElement.lang="en";document.title=x.title+" · TripTale";const q=s=>document.querySelector(s),a=s=>document.querySelectorAll(s);q("main>a.back").textContent=x.back;q("h1").textContent=x.title;q(".image-button").textContent=x.image;a(".success").forEach(e=>{if(e.textContent.trim()==="Bild gespeichert.")e.textContent=x.imageSaved;if(e.textContent.trim()==="Bild gelöscht.")e.textContent=x.imageDeleted;});q("section strong").textContent=x.manage;a("form[action=\"/trip-manage.php\"] button").forEach(b=>{if(b.textContent.includes("wieder"))b.textContent=x.reactivate;else if(b.textContent.includes("archiv"))b.textContent=x.archive;else b.textContent=x.delete;});const label=n=>q("[name=\""+n+"\"]").closest("label");label("title").childNodes[0].nodeValue=x.formTitle;label("subtitle").childNodes[0].nodeValue=x.subtitle;label("start_date").childNodes[0].nodeValue=x.start;label("end_date").childNodes[0].nodeValue=x.end;label("group_chat_url").childNodes[0].nodeValue=x.group;q("#trip-form > label:nth-of-type(3)").textContent=x.description;q(".hint").textContent=x.hint;label("status").childNodes[0].nodeValue=x.status;const status={draft:x.draft,active:x.active,completed:x.completed,archived:x.archived};a("[name=status] option").forEach(o=>o.textContent=status[o.value]||o.textContent);q(".save[type=submit]").textContent=x.save;a(".toolbar [data-command]").forEach(b=>{const k={bold:"bold",italic:"italic",insertUnorderedList:"list",insertOrderedList:"numbered_list"}[b.dataset.command];if(k)b.childNodes[0].nodeValue=x.editor[k];});q("#link-button").textContent=x.editor.link;const m={"":x.editor.style,p:x.editor.normal,h2:x.editor.heading,h3:x.editor.small_heading};a("#style-select option").forEach(o=>o.textContent=m[o.value]||o.textContent);a("form[action=\"/trip-manage.php\"]").forEach(f=>{if(f.querySelector("[value=archive]"))f.onsubmit=()=>confirm(x.confirmArchive);if(f.querySelector("[value=delete]"))f.onsubmit=()=>confirm(x.confirmDelete);});})();</script>';
    return str_replace('</body>', $script . '</body>', $html);
});
ob_start(static function (string $html): string {
    return language() !== 'de' ? str_replace('>Änderungen speichern<', '>' . t('edit.save_changes') . '<', $html) : $html;
});
$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.'); }
$statement = db()->prepare('SELECT * FROM ' . table('trips') . ' WHERE id = :trip_id LIMIT 1');
$statement->execute([':trip_id' => $tripId]);
$trip = $statement->fetch();
if (!$trip) { http_response_code(404); exit('Reise nicht gefunden.'); }
$canEdit = $user['role'] === 'main_admin' || (int)$trip['created_by'] === (int)$user['id'];
if (!$canEdit) { $check = db()->prepare('SELECT 1 FROM ' . table('trip_admins') . ' WHERE trip_id = :trip_id AND user_id = :user_id'); $check->execute([':trip_id' => $tripId, ':user_id' => $user['id']]); $canEdit = (bool)$check->fetchColumn(); }
if (!$canEdit) { http_response_code(403); exit('Du darfst diese Reise nicht bearbeiten.'); }
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $title = trim((string)($_POST['title'] ?? ''));
    $subtitle = trim((string)($_POST['subtitle'] ?? ''));
    $description = sanitize_rich_text((string)($_POST['description'] ?? ''));
    $groupChatUrl = trim((string)($_POST['group_chat_url'] ?? ''));
    $status = (string)($_POST['status'] ?? 'draft');
    $startDate = (string)($_POST['start_date'] ?? '');
    $endDate = (string)($_POST['end_date'] ?? '');
    $start = DateTimeImmutable::createFromFormat('!Y-m-d', $startDate);
    $end = DateTimeImmutable::createFromFormat('!Y-m-d', $endDate);
    if ($title === '') { $error = t('edit.error_title'); }
    elseif (!in_array($status, ['draft', 'active', 'completed', 'archived'], true)) { $error = t('edit.error_status'); }
    elseif (!$start || !$end || $start->format('Y-m-d') !== $startDate || $end->format('Y-m-d') !== $endDate || $end < $start) { $error = t('edit.error_dates'); }
    elseif ($groupChatUrl !== '' && (!filter_var($groupChatUrl, FILTER_VALIDATE_URL) || parse_url($groupChatUrl, PHP_URL_SCHEME) !== 'https')) { $error = t('edit.error_group_link'); }
    else {
        $currentStart = DateTimeImmutable::createFromFormat('!Y-m-d', (string) $trip['start_date']);
        $currentEnd = DateTimeImmutable::createFromFormat('!Y-m-d', (string) $trip['end_date']);
        $shiftDays = (int) $currentStart->diff($start)->format('%r%a');
        if ($shiftDays > 0) {
            $preservedEnd = $currentEnd->modify('+' . $shiftDays . ' days');
            if ($end < $preservedEnd) { $end = $preservedEnd; $endDate = $end->format('Y-m-d'); }
        }
        $newDayCount = $start->diff($end)->days + 1;
        $days = db()->prepare('SELECT id, day_number FROM ' . table('trip_days') . ' WHERE trip_id = :trip_id ORDER BY day_number');
        $days->execute([':trip_id' => $tripId]);
        $existingDays = $days->fetchAll();
        try {
                $pdo = db(); $pdo->beginTransaction();
                $update = $pdo->prepare('UPDATE ' . table('trips') . ' SET title = :title, subtitle = :subtitle, description = :description, start_date = :start_date, end_date = :end_date, group_chat_url = :group_chat_url, status = :status WHERE id = :id');
                $update->execute([':title' => $title, ':subtitle' => $subtitle ?: null, ':description' => $description ?: null, ':start_date' => $startDate, ':end_date' => $endDate, ':group_chat_url' => $groupChatUrl ?: null, ':status' => $status, ':id' => $tripId]);
                $updateDay = $pdo->prepare('UPDATE ' . table('trip_days') . ' SET date = :date WHERE id = :id');
                foreach ($existingDays as $day) { $updateDay->execute([':date' => $start->modify('+' . ((int)$day['day_number'] - 1) . ' days')->format('Y-m-d'), ':id' => $day['id']]); }
                if ($newDayCount < count($existingDays)) { $deleteDays = $pdo->prepare('DELETE FROM ' . table('trip_days') . ' WHERE trip_id=:trip_id AND day_number>:day_count'); $deleteDays->execute([':trip_id'=>$tripId, ':day_count'=>$newDayCount]); }
                $insertDay = $pdo->prepare('INSERT INTO ' . table('trip_days') . ' (trip_id, day_number, date, title, sort_order) VALUES (:trip_id, :day_number, :date, :title, :sort_order)');
                for ($number = count($existingDays) + 1; $number <= $newDayCount; $number++) { $insertDay->execute([':trip_id' => $tripId, ':day_number' => $number, ':date' => $start->modify('+' . ($number - 1) . ' days')->format('Y-m-d'), ':title' => 'Tag ' . $number, ':sort_order' => $number]); }
                $pdo->commit(); $changeId = triptale_log_trip_change($tripId, (int)$user['id'], 'trip_updated', t('edit.change_logged')); header('Location: /trip.php?id=' . $tripId . '&saved=1'); exit;
        } catch (Throwable $exception) { if (db()->inTransaction()) { db()->rollBack(); } $error = t('edit.error_save'); }
    }
}
$descriptionValue = $_POST['description'] ?? $trip['description'] ?? '';
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Reise bearbeiten · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:680px;margin:auto;background:white;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}label{display:block;margin-top:16px;font-weight:600}input,select{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.editor{min-height:160px;margin-top:6px;padding:11px;border:1px solid #b9c1c8;border-radius:0 0 7px 7px;background:white;font-weight:400}.toolbar{display:flex;gap:5px;flex-wrap:wrap;margin-top:6px;padding:7px;border:1px solid #b9c1c8;border-bottom:0;border-radius:7px 7px 0 0;background:#edf2f3}.toolbar button{margin:0;padding:6px 9px;background:#fff;color:#17202a;border:1px solid #b9c1c8;border-radius:4px}.save{margin-top:22px;padding:12px 16px;border:0;border-radius:7px;background:#126e82;color:white;font-weight:700}.error{background:#ffe6e3;padding:12px;border-radius:7px}a{color:#126e82}.hint{color:#59636d;font-size:.9rem}*{box-sizing:border-box}html,body{max-width:100%;overflow-x:hidden}img,video{max-width:100%;height:auto}input,textarea,select,.editor{max-width:100%}@media(max-width:600px){body{padding:12px!important}header{padding:14px 16px!important;flex-wrap:wrap;gap:10px}main{width:100%!important;margin:18px auto!important;padding:16px!important}.top{flex-wrap:wrap;align-items:flex-start}.top>div{width:100%}.button{margin:4px 4px 4px 0!important}.card,.hero,.day{padding:16px!important}h1{font-size:1.6rem}h2{font-size:1.25rem}}@media(max-width:600px){.top{display:block!important}.top .button{display:block!important;width:100%!important;margin:8px 0!important;text-align:center}input[type="date"],input[type="time"]{min-width:0!important;width:100%!important;max-width:100%!important;font-size:16px!important}}@media(max-width:600px){form,label{min-width:0!important;max-width:100%!important}input[type="date"],input[type="time"]{min-inline-size:0!important;inline-size:100%!important;max-inline-size:100%!important;overflow:hidden!important}input[type="date"]::-webkit-date-and-time-value,input[type="time"]::-webkit-date-and-time-value{min-width:0!important;text-align:left!important}}.image-button{display:inline-block!important;padding:9px 12px!important;background:#126e82!important;color:#fff!important;border-radius:7px!important;text-decoration:none!important;font-weight:700!important}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/trip.php?id=<?= $tripId ?>">← Zurück</a><h1>Reise bearbeiten</h1><a class="button image-button" href="/image-upload.php?type=trip&id=<?= $tripId ?>">Bild bearbeiten</a><?php if(($_GET["image"]??"")==="changed"): ?><p class="success">Bild gespeichert.</p><?php elseif(($_GET["image"]??"")==="deleted"): ?><p class="success">Bild gelöscht.</p><?php endif; ?><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><?php if(($_GET["trip"]??"")==="archive"): ?><p class="success">Reise wurde archiviert.</p><?php elseif(($_GET["trip"]??"")==="restore"): ?><p class="success">Reise wurde wieder aktiviert.</p><?php endif; ?><section style="margin:22px 0;padding:16px;border:1px solid #d6e0e4;border-radius:10px;background:#f8fafb"><strong>Reise verwalten</strong><?php if($trip["status"]==="archived"): ?><form method="post" action="/trip-manage.php" style="margin-top:10px"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,"UTF-8") ?>"><input type="hidden" name="trip_id" value="<?= $tripId ?>"><input type="hidden" name="action" value="restore"><button class="save" style="margin-top:0" type="submit">Reise wieder aktivieren</button></form><?php else: ?><form method="post" action="/trip-manage.php" style="margin-top:10px" onsubmit="return confirm(&quot;Diese Reise nur archivieren? Alle Inhalte bleiben erhalten.&quot;);"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,"UTF-8") ?>"><input type="hidden" name="trip_id" value="<?= $tripId ?>"><input type="hidden" name="action" value="archive"><button class="save" style="margin-top:0" type="submit">Reise archivieren</button></form><?php endif; ?><form method="post" action="/trip-manage.php" style="margin-top:10px" onsubmit="return confirm(&quot;Diese Reise wirklich endgültig löschen? Alle Tage, Programmpunkte, individuellen Hinweise sowie Reise- und Programmbilder werden unwiderruflich entfernt.&quot;);"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,"UTF-8") ?>"><input type="hidden" name="trip_id" value="<?= $tripId ?>"><input type="hidden" name="action" value="delete"><button class="save" style="margin-top:0;background:#9d2d2d" type="submit">Reise endgültig löschen</button></form></section><form method="post" id="trip-form"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="description" id="description-value"><label>Titel<input name="title" required value="<?= htmlspecialchars((string)($_POST['title'] ?? $trip['title']), ENT_QUOTES, 'UTF-8') ?>"></label><label>Untertitel<input name="subtitle" value="<?= htmlspecialchars((string)($_POST['subtitle'] ?? $trip['subtitle'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Beschreibung</label><div class="toolbar"><button type="button" data-command="bold"><b>Fett</b></button><button type="button" data-command="italic"><i>Kursiv</i></button><button type="button" data-command="insertUnorderedList">Liste</button><button type="button" data-command="insertOrderedList">1. Liste</button><button type="button" id="link-button">Link</button><select id="style-select"><option value="">Textstil…</option><option value="p">Normal</option><option value="h2">Überschrift</option><option value="h3">Kleine Überschrift</option></select></div><div class="editor" id="description-editor" contenteditable="true"><?= render_rich_text((string)$descriptionValue) ?></div><label>Startdatum<input name="start_date" type="date" required value="<?= htmlspecialchars((string)($_POST['start_date'] ?? $trip['start_date']), ENT_QUOTES, 'UTF-8') ?>"></label><label>Enddatum<input name="end_date" type="date" required value="<?= htmlspecialchars((string)($_POST['end_date'] ?? $trip['end_date']), ENT_QUOTES, 'UTF-8') ?>"></label><p class="hint">Tage dürfen verschoben oder ergänzt werden. Eine Verkürzung sperrt TripTale derzeit, damit bestehende Inhalte erhalten bleiben.</p><label>Link zur Reisegruppe (optional)<input name="group_chat_url" type="url" placeholder="https://…" value="<?= htmlspecialchars((string)($_POST['group_chat_url'] ?? $trip['group_chat_url'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Status<select name="status"><?php foreach (['draft' => 'Entwurf', 'active' => 'Aktiv', 'completed' => 'Abgeschlossen', 'archived' => 'Archiviert'] as $value => $label): ?><option value="<?= $value ?>"<?= (($_POST['status'] ?? $trip['status']) === $value) ? ' selected' : '' ?>><?= $label ?></option><?php endforeach; ?></select></label><button class="save" type="submit">Änderungen speichern</button></form></main><script>const editor=document.getElementById('description-editor');document.querySelectorAll('[data-command]').forEach(button=>button.addEventListener('click',()=>{editor.focus();document.execCommand(button.dataset.command,false,button.dataset.value||null);}));document.getElementById('style-select').addEventListener('change',function(){if(this.value){editor.focus();document.execCommand('formatBlock',false,'<' + this.value + '>');this.value='';}});document.getElementById('link-button').addEventListener('click',()=>{const url=window.prompt('https://');if(url){editor.focus();document.execCommand('createLink',false,url);}});document.getElementById('trip-form').addEventListener('submit',()=>{document.getElementById('description-value').value=editor.innerHTML;});</script></body></html>
