<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';
$dayEditUi = ['back' => t('common.back_to_trip'), 'heading' => t('edit.day_heading'), 'title' => t('form.title'), 'description' => t('edit.day_description'), 'save' => t('common.save'), '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 ($dayEditUi): string {
    if (language() === 'de') { return $html; }
    $ui = json_encode($dayEditUi, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $script = '<script>(function(){const x=' . $ui . ';const q=s=>document.querySelector(s),a=s=>document.querySelectorAll(s);document.documentElement.lang="en";q("main>a.back").textContent=x.back;const h=q("h1"),n=(h.textContent.match(/\\d+/)||[""])[0];h.textContent=x.heading.replace("{day}",n);document.title=h.textContent+" · TripTale";const l=q("[name=title]").closest("label");l.childNodes[0].nodeValue=x.title;q("#day-form > label:nth-of-type(2)").textContent=x.description;q(".save").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);})();</script>';
    return str_replace('</body>', $script . '</body>', $html);
});
$user = require_login();
$dayId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if (!$dayId) { http_response_code(404); exit('Reisetag nicht gefunden.'); }
$statement = db()->prepare('SELECT d.id, d.trip_id, d.day_number, d.date, d.title, d.description, t.created_by FROM ' . table('trip_days') . ' d JOIN ' . table('trips') . ' t ON t.id = d.trip_id WHERE d.id = :day_id LIMIT 1');
$statement->execute([':day_id' => $dayId]);
$day = $statement->fetch();
if (!$day) { http_response_code(404); exit('Reisetag nicht gefunden.'); }
$canEdit = $user['role'] === 'main_admin' || (int)$day['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' => $day['trip_id'], ':user_id' => $user['id']]); $canEdit = (bool)$check->fetchColumn(); }
if (!$canEdit) { http_response_code(403); exit('Du darfst diesen Reisetag 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'] ?? '')); $description = sanitize_rich_text((string)($_POST['description'] ?? ''));
    if ($title === '') { $error = t('day.error_title'); }
    else { $update = db()->prepare('UPDATE ' . table('trip_days') . ' SET title = :title, description = :description WHERE id = :id'); $update->execute([':title' => $title, ':description' => $description ?: null, ':id' => $dayId]); $changeText = str_replace(['{day}', '{title}'], [(string)(int)$day['day_number'], $title], t('day.change_logged')); $changeId = triptale_log_trip_change((int)$day['trip_id'], (int)$user['id'], 'day_updated', $changeText); header('Location: /trip.php?id=' . (int)$day['trip_id'] . '&saved=1'); exit; }
}
$descriptionValue = $_POST['description'] ?? $day['description'] ?? '';
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Reisetag 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{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.editor{min-height:180px;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}*{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}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/trip.php?id=<?= (int)$day['trip_id'] ?>">← Zur Reise</a><h1>Tag <?= (int)$day['day_number'] ?> bearbeiten</h1><p><?= htmlspecialchars(localized_date($day['date']), ENT_QUOTES, 'UTF-8') ?></p><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><form method="post" id="day-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'] ?? $day['title']), ENT_QUOTES, 'UTF-8') ?>"></label><label>Tagesbeschreibung</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><button class="save" type="submit">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('day-form').addEventListener('submit',()=>{document.getElementById('description-value').value=editor.innerHTML;});</script></body></html>
