<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/categories.php';
require_once __DIR__ . '/app/Helpers/countries.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">', 'Freier Programmpunkt · TripTale' => t('program.add_custom') . ' · TripTale', '>← Zurück<' => '>' . t('users.back') . '<', '>Freien Programmpunkt hinzufügen<' => '>' . t('program.add_custom') . '<', '>Titel<input' => '>' . t('form.title') . '<input', '>Uhrzeit<input' => '>' . t('custom_points.time') . '<input', '>Land<select' => '>' . t('attraction.country') . '<select', '>Hinweis für diese Reise<' => '>' . t('trip.note_for_trip') . '<', '>Programmpunkt hinzufügen<' => '>' . t('custom_points.add_to_trip') . '<', '>Bitte einen Titel eingeben.<' => '>Please enter a title.<', '>Bitte ein gültiges Land auswählen.<' => '>Please select a valid country.<', '>Bitte eine gültige Uhrzeit eingeben.<' => '>Please enter a valid time.<']);
});
$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.');}
$q=db()->prepare('SELECT d.id,d.trip_id,d.day_number,d.date,d.title,t.created_by FROM '.table('trip_days').' d JOIN '.table('trips').' t ON t.id=d.trip_id WHERE d.id=:id');$q->execute([':id'=>$dayId]);$day=$q->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.');}
$error=null;$categories=triptale_categories('custom');$selectedCategoryIds=triptale_category_ids((array)($_POST['category_ids']??[]),'custom');if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();$title=trim((string)($_POST['title']??''));$countryCode=strtoupper(trim((string)($_POST['country_code']??'')));$time=trim((string)($_POST['time']??''));$info=sanitize_rich_text((string)($_POST['trip_additional_info']??''));if($title===''){$error='Bitte einen Titel eingeben.';}elseif($countryCode!==''&&!array_key_exists($countryCode,triptale_countries())){$error='Bitte ein gültiges Land auswählen.';}elseif($time!==''&&!preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$time)){$error='Bitte eine gültige Uhrzeit eingeben.';}else{$order=(int)db()->query('SELECT COALESCE(MAX(sort_order),0)+1 FROM '.table('trip_day_items').' WHERE trip_day_id='.(int)$dayId)->fetchColumn();$insert=db()->prepare('INSERT INTO '.table('trip_day_items')." (trip_day_id,item_type,title,time,country_code,trip_additional_info,sort_order) VALUES (:day_id,'custom',:title,:time,:country_code,:info,:sort_order)");$insert->execute([':day_id'=>$dayId,':title'=>$title,':time'=>$time?:null,':country_code'=>$countryCode?:null,':info'=>$info?:null,':sort_order'=>$order]);$itemId=(int)db()->lastInsertId();try{triptale_sync_categories('custom',$itemId,$selectedCategoryIds);}catch(Throwable $exception){}try{triptale_log_trip_change((int)$day['trip_id'],(int)$user['id'],'item_added','Freier Programmpunkt „'.$title.'“ wurde zu Tag '.(int)$day['day_number'].' hinzugefügt.');}catch(Throwable $exception){}header('Location: /day-program.php?id='.(int)$dayId.'&saved=1');exit;}}
$infoValue=$_POST['trip_additional_info']??'';
?><!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Freier Programmpunkt · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:760px;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,select{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.editor{min-height:120px;margin-top:6px;padding:11px;border:1px solid #b9c1c8;border-radius:0 0 7px 7px;background:#fff}.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)$dayId ?>">← Zurück</a><h1>Freien Programmpunkt hinzufügen</h1><p>Tag <?= (int)$day['day_number'] ?> · <?= htmlspecialchars($day['title'],ENT_QUOTES,'UTF-8') ?></p><?php if($error): ?><p class="error"><?= htmlspecialchars($error,ENT_QUOTES,'UTF-8') ?></p><?php endif; ?><form method="post" id="item-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>Titel<input name="title" required value="<?= htmlspecialchars((string)($_POST['title']??''),ENT_QUOTES,'UTF-8') ?>"></label><label>Uhrzeit<input name="time" type="time" value="<?= htmlspecialchars((string)($_POST['time']??''),ENT_QUOTES,'UTF-8') ?>"></label><label>Land<select name="country_code"><?php foreach(triptale_countries() as $code=>$country): ?><option value="<?= $code ?>"<?= (($_POST['country_code']??$item['country_code']??'')===$code)?' selected':'' ?>><?= htmlspecialchars($country,ENT_QUOTES,'UTF-8') ?></option><?php endforeach; ?></select></label><label>Kategorien <small>(mehrere möglich)</small><select name="category_ids[]" multiple size="5"><?php foreach($categories as $category): ?><option value="<?= (int)$category['id'] ?>"<?= in_array((int)$category['id'],$selectedCategoryIds,true)?' selected':'' ?>><?= htmlspecialchars($category['name'],ENT_QUOTES,'UTF-8') ?></option><?php endforeach; ?></select></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">Programmpunkt hinzufügen</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('item-form').addEventListener('submit',()=>{document.getElementById('info-value').value=editor.innerHTML;});</script></body></html>
