<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Hinweis bearbeiten · TripTale' => 'Edit trip note · TripTale', '>← Zurück zum Programm<' => '>← Back to program<', '>Hier ergänzt du Angaben, die nur für diese Reise gelten.<' => '>Add details that apply only to this trip.<', '>Uhrzeit<input' => '>' . t('custom_points.time') . '<input', '>Hinweis für diese Reise<' => '>' . t('trip.note_for_trip') . '<', '>Speichern<' => '>' . t('common.save') . '<', '>Programmpunkt nicht gefunden.<' => '>' . t('custom_points.error_not_found') . '<', '>Bitte eine gültige Uhrzeit eingeben.<' => '>Please enter a valid time.<', '>Sehenswürdigkeit bearbeiten<' => '>Edit attraction<', '>Unterkunft bearbeiten<' => '>Edit accommodation<', '>Essen & Trinken bearbeiten<' => '>Edit food & drink<', '>Eigener Programmpunkt bearbeiten<' => '>Edit custom program item<']);
});

$user = require_login();
$itemId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options'=>['min_range'=>1]]);
if (!$itemId) { http_response_code(404); exit('Programmpunkt nicht gefunden.'); }
$query = db()->prepare('SELECT i.*,d.trip_id,t.created_by,a.name AS attraction_name,ac.name AS accommodation_name,r.name AS restaurant_name,cp.name AS custom_point_name 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 AND i.item_type IN ('attraction','accommodation','restaurant','catalog_custom')");
$query->execute([':id'=>$itemId]); $item=$query->fetch();
if (!$item) { http_response_code(404); exit('Programmpunkt nicht gefunden.'); }
$canEdit=$user['role']==='main_admin'||(int)$item['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'=>$item['trip_id'],':user_id'=>$user['id']]);$canEdit=(bool)$check->fetchColumn();}if(!$canEdit){http_response_code(403);exit('Kein Zugriff.');}
$labels=['attraction'=>'Sehenswürdigkeit','accommodation'=>'Unterkunft','restaurant'=>'Essen & Trinken','catalog_custom'=>'Eigener Programmpunkt'];$name=$item['attraction_name']?:$item['accommodation_name']?:$item['restaurant_name']?:$item['custom_point_name']?:'Programmpunkt';$error=null;
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();$time=trim((string)($_POST['time']??''));$info=sanitize_rich_text((string)($_POST['trip_additional_info']??''));$title=trim((string)($_POST['title']??$item['title']??''));$canChangeTitle=$item['item_type']==='catalog_custom';if($canChangeTitle&&$title===''){$error=t('custom_points.error_name');}elseif($time!==''&&!preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$time)){$error='Bitte eine gültige Uhrzeit eingeben.';}else{$sql='UPDATE '.table('trip_day_items').' SET time=:time,trip_additional_info=:info'.($canChangeTitle?',title=:title':'').' WHERE id=:id';$params=[':time'=>$time?:null,':info'=>$info?:null,':id'=>$itemId];if($canChangeTitle){$params[':title']=$title;}$update=db()->prepare($sql);$update->execute($params);$name=$canChangeTitle?$title:$name;$changeId=triptale_log_trip_change((int)$item['trip_id'],(int)$user['id'],'item_updated',$labels[$item['item_type']].' „'.$name.'“ wurde für diese Reise bearbeitet.');header('Location: /day-program.php?id='.(int)$item['trip_day_id'].'&saved=1');exit;}}
$timeValue=(string)($_POST['time']??($item['time']?substr($item['time'],0,5):''));$infoValue=$_POST['trip_additional_info']??$item['trip_additional_info']??'';
if ($item['item_type'] === 'catalog_custom') {
    $titleValue = (string)($_POST['title'] ?? $item['title'] ?? $name);
    ob_start(static function (string $html) use ($titleValue): string {
        $field = '<label>' . htmlspecialchars(t('form.title'), ENT_QUOTES, 'UTF-8') . '<input name="title" required value="' . htmlspecialchars($titleValue, ENT_QUOTES, 'UTF-8') . '"></label>';
        return str_replace('<label>Uhrzeit<input', $field . '<label>Uhrzeit<input', $html);
    });
}
?><!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Hinweis bearbeiten · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:700px;margin:auto;background:#fff;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:130px;margin-top:6px;padding:11px;border:1px solid #b9c1c8;border-radius:0 0 7px 7px}.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}.button{display:inline-block;padding:9px 12px;background:#e3ebee;color:#126e82;border:0;border-radius:7px;text-decoration:none;font-weight:700}.save{margin-top:22px;padding:12px 16px;border:0;border-radius:7px;background:#126e82;color:#fff;font-weight:700}.error{background:#ffe6e3;padding:12px;border-radius:7px}*{box-sizing:border-box}html,body{max-width:100%;overflow-x:hidden}@media(max-width:600px){body{padding:12px}main{width:100%;margin:18px auto;padding:16px}h1{font-size:1.6rem}}@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}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/day-program.php?id=<?= (int)$item['trip_day_id'] ?>">← Zurück zum Programm</a><h1><?= $labels[$item['item_type']] ?> bearbeiten</h1><p><strong><?= htmlspecialchars($name,ENT_QUOTES,'UTF-8') ?></strong></p><p>Hier ergänzt du Angaben, die nur für diese Reise gelten.</p><?php if($error): ?><p class="error"><?= htmlspecialchars($error,ENT_QUOTES,'UTF-8') ?></p><?php endif; ?><form method="post" id="planned-form"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8') ?>"><input type="hidden" name="trip_additional_info" id="info-value"><label>Uhrzeit<input name="time" type="time" value="<?= htmlspecialchars($timeValue,ENT_QUOTES,'UTF-8') ?>"></label><label>Hinweis für diese Reise</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="info-editor" contenteditable="true"><?= render_rich_text((string)$infoValue) ?></div><button class="save" type="submit">Speichern</button></form></main><script>const editor=document.getElementById('info-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('planned-form').addEventListener('submit',()=>{document.getElementById('info-value').value=editor.innerHTML;});</script></body></html>
