<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';

$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,t.created_by FROM ' . table('trip_days') . ' d JOIN ' . table('trips') . ' t ON t.id=d.trip_id WHERE d.id=:id');
$statement->execute([':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.'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = (string) ($_POST['action'] ?? '');
    $changeId = 0;
    if ($action === 'delete') {
        $itemId = filter_input(INPUT_POST, 'item_id', FILTER_VALIDATE_INT, ['options'=>['min_range'=>1]]);
        if ($itemId) { $nameQuery = db()->prepare('SELECT COALESCE(i.title,a.name,ac.name,r.name,cp.name,\'Programmpunkt\') 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.id=:id AND i.trip_day_id=:day_id"); $nameQuery->execute([':id'=>$itemId, ':day_id'=>$dayId]); $name=(string)$nameQuery->fetchColumn(); $delete = db()->prepare('DELETE FROM ' . table('trip_day_items') . ' WHERE id=:id AND trip_day_id=:day_id'); $delete->execute([':id'=>$itemId, ':day_id'=>$dayId]); if ($delete->rowCount()) { $changeId=triptale_log_trip_change((int)$day['trip_id'],(int)$user['id'],'item_deleted','Programmpunkt „'.$name.'“ wurde aus Tag '.(int)$day['day_number'].' entfernt.'); } }
    }
    if ($action === 'reorder') {
        $order = array_filter(array_map('intval', explode(',', (string) ($_POST['order'] ?? ''))));
        $valid = db()->prepare('SELECT id FROM ' . table('trip_day_items') . ' WHERE trip_day_id=:day_id'); $valid->execute([':day_id'=>$dayId]);
        $validIds = array_map('intval', array_column($valid->fetchAll(), 'id'));
        sort($order); $sortedValid = $validIds; sort($sortedValid);
        if ($order === $sortedValid) { $update = db()->prepare('UPDATE ' . table('trip_day_items') . ' SET sort_order=:sort_order WHERE id=:id AND trip_day_id=:day_id'); foreach (array_values(array_filter(array_map('intval', explode(',', (string) $_POST['order'])))) as $position => $itemId) { $update->execute([':sort_order'=>$position+1, ':id'=>$itemId, ':day_id'=>$dayId]); } $changeId=triptale_log_trip_change((int)$day['trip_id'],(int)$user['id'],'program_reordered','Die Reihenfolge der Programmpunkte an Tag '.(int)$day['day_number'].' wurde geändert.'); }
    }
    header('Location: /day-program.php?id=' . $dayId . '&saved=1'); exit;
}

$itemsQuery = db()->prepare('SELECT i.id,i.item_type,i.title,i.time,i.trip_additional_info,i.image_path AS custom_image,a.name AS attraction_name,a.image_path AS attraction_image,ac.name AS accommodation_name,ac.image_path AS accommodation_image,r.name AS restaurant_name,r.image_path AS restaurant_image,cp.name AS custom_point_name,cp.image_path AS custom_point_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=:day_id ORDER BY i.sort_order,i.id");
$itemsQuery->execute([':day_id'=>$dayId]); $items = $itemsQuery->fetchAll();
$labels = ['custom'=>t('type.custom'),'attraction'=>t('type.attraction'),'accommodation'=>t('type.accommodation'),'restaurant'=>t('type.restaurant'),'catalog_custom'=>t('type.custom')];
ob_start(static function (string $html): string {
    $style = '<style>.item[data-type="attraction"],.choice[data-type="attraction"]{border-left:5px solid #e4a06f!important}.item[data-type="accommodation"],.choice[data-type="accommodation"]{border-left:5px solid #91c2d8!important}.item[data-type="restaurant"],.choice[data-type="restaurant"]{border-left:5px solid #b9a2cd!important}.item[data-type="custom"],.item[data-type="catalog_custom"],.choice[data-type="custom"],.choice[data-type="catalog_custom"]{border-left:5px solid #91bf98!important}.type{display:table!important;padding:3px 7px!important;margin-bottom:10px!important;border-radius:999px!important;font-size:.74rem!important;line-height:1.2!important;font-weight:400!important}.item[data-type="attraction"] .type{background:#f5ddce;color:#8b421a;border:1px solid #8b421a}.item[data-type="accommodation"] .type{background:#d7eaf2;color:#25637e;border:1px solid #25637e}.item[data-type="restaurant"] .type{background:#e8dfee;color:#5d3d72;border:1px solid #5d3d72}.item[data-type="custom"] .type,.item[data-type="catalog_custom"] .type{background:#deede0;color:#35673e;border:1px solid #35673e}</style>';
    $script = '<script>(function(){var types=window.triptaleProgramTypes||{"Sehenswürdigkeit":"attraction","Unterkunft":"accommodation","Essen & Trinken":"restaurant","Freier Programmpunkt":"custom","Eigener Programmpunkt":"catalog_custom"};document.querySelectorAll("#program-list .item").forEach(function(item){var label=item.querySelector(".type");if(!label)return;var type=types[label.textContent.trim()]||"custom";item.dataset.type=type;if(type==="custom"||type==="catalog_custom")label.textContent=window.triptaleProgramItem||"Programmpunkt";});document.querySelectorAll(".choice").forEach(function(choice){var href=choice.getAttribute("href")||"";if(href.indexOf("day-attraction-add")!==-1)choice.dataset.type="attraction";else if(href.indexOf("type=accommodation")!==-1)choice.dataset.type="accommodation";else if(href.indexOf("type=restaurant")!==-1)choice.dataset.type="restaurant";else if(href.indexOf("day-custom-catalog-add")!==-1)choice.dataset.type="catalog_custom";else if(href.indexOf("day-items")!==-1)choice.dataset.type="custom";});})();</script>';
    return str_replace('</head>', $style . '</head>', str_replace('</body>', $script . '</body>', $html));
});
$programUi = ['back' => t('common.back_to_trip'), 'title' => t('program.edit_title'), 'day' => t('trip.day'), 'catalog' => t('program.add_catalog_custom'), 'catalogHint' => t('program.add_catalog_custom_hint'), 'custom' => t('program.add_custom'), 'customHint' => t('program.add_custom_hint'), 'attraction' => t('program.add_attraction'), 'attractionHint' => t('program.add_attraction_hint'), 'accommodation' => t('program.add_accommodation'), 'accommodationHint' => t('program.add_accommodation_hint'), 'restaurant' => t('program.add_restaurant'), 'restaurantHint' => t('program.add_restaurant_hint'), 'existing' => t('program.existing'), 'desktop' => t('program.sort_desktop'), 'mobile' => t('program.sort_mobile'), 'empty' => t('program.empty'), 'edit' => t('common.edit'), 'editNote' => t('program.edit_note'), 'delete' => t('common.delete'), 'confirmDelete' => t('program.confirm_delete'), 'move' => t('program.move'), 'up' => t('checklist.up'), 'down' => t('checklist.down'), 'types' => [t('type.attraction') => 'attraction', t('type.accommodation') => 'accommodation', t('type.restaurant') => 'restaurant', t('type.custom') => 'custom']];
ob_start(static function (string $html) use ($programUi): string {
    if (language() === 'de') { return $html; }
    $ui = json_encode($programUi, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $script = '<script>(function(){const x=' . $ui . ';window.triptaleProgramTypes=x.types;window.triptaleProgramItem=' . json_encode(t('type.custom'), JSON_UNESCAPED_UNICODE) . ';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;const p=q("main>p.muted"),num=(p.textContent.match(/\\d+/)||[""])[0];p.childNodes[0].nodeValue=x.day+" "+num+" · ";const choices=[[["day-custom-catalog-add"],x.catalog,x.catalogHint],[["day-items.php"],x.custom,x.customHint],[["day-attraction-add"],x.attraction,x.attractionHint],[["type=accommodation"],x.accommodation,x.accommodationHint],[["type=restaurant"],x.restaurant,x.restaurantHint]];a(".choice").forEach(c=>{const h=c.href||"";const d=choices.find(v=>h.includes(v[0][0]));if(d){c.querySelector("strong").textContent=d[1];c.childNodes[c.childNodes.length-1].nodeValue=d[2];}});q(".items h2").textContent=x.existing;q(".sort-desktop").textContent=x.desktop;q(".sort-mobile").textContent=x.mobile;const empty=q("#program-list > p.muted");if(empty)empty.textContent=x.empty;a(".handle").forEach(h=>h.title=x.move);a("#program-list .item a.button").forEach(b=>b.textContent=b.textContent.trim()==="Bearbeiten"?x.edit:x.editNote);a("#program-list .delete").forEach(b=>b.textContent=x.delete);a("#program-list form").forEach(f=>f.onsubmit=()=>confirm(x.confirmDelete));setTimeout(()=>a(".mobile-sort button").forEach(b=>b.textContent=b.textContent.includes("Hoch")?"↑ "+x.up:"↓ "+x.down),0);})();</script>';
    return str_replace('</body>', $script . '</body>', $html);
});
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Programm 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}.button{display:inline-block;padding:9px 12px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;margin:8px 8px 0 0;cursor:pointer}.back{background:#e3ebee;color:#126e82}.choice{display:block;background:#f4f6f8;color:#17202a;text-decoration:none;padding:16px;margin-top:10px;border-radius:10px;border:1px solid #dbe1e5}.choice strong{display:block;color:#126e82;font-size:1.05rem}.muted{color:#59636d}.items{margin-top:30px;border-top:1px solid #dbe1e5;padding-top:12px}.item{padding:14px 0;border-top:1px solid #edf0f2}.item:first-of-type{border-top:0}.type{font-size:.9rem;color:#59636d}.time{font-weight:700;color:#126e82}.delete{background:#9d2d2d}.small{padding:7px 10px;font-size:.9rem}*{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}}.handle{float:right;font-size:1.5rem;color:#59636d;padding:0 8px;cursor:grab;touch-action:none}.dragging{opacity:.45}.card,.hero,.day,.choice{border:1px solid #d6e0e4!important;box-shadow:0 3px 12px rgba(23,32,42,.08)!important}.card{border-left:4px solid #75aeb9!important}.card:hover{transform:translateY(-1px);box-shadow:0 7px 20px rgba(23,32,42,.13)!important}.day{border-left:4px solid #75aeb9!important}.choice{border-left:4px solid #75aeb9!important}.item{background:#f8fafb;border:1px solid #dfe7ea!important;border-radius:9px;padding:14px!important;margin-top:10px}.item:first-of-type{border-top:1px solid #dfe7ea!important}.thumb{width:64px;height:52px;object-fit:contain;background:#e8eef0;border-radius:6px;float:right;margin-left:10px}@media(max-width:600px){.mobile-sort{display:inline-flex;gap:6px;margin:8px 0}.mobile-sort button{padding:6px 10px;border:1px solid #b9c1c8;border-radius:6px;background:#fff;color:#126e82;font-weight:700}.handle{display:none}.sort-desktop{display:none}.sort-mobile{display:inline}}@media(min-width:601px){.mobile-sort{display:none}.sort-mobile{display:none}}</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ück zur Reise</a><h1>Programm bearbeiten</h1><p class="muted">Tag <?= (int) $day['day_number'] ?> · <?= htmlspecialchars($day['title'], ENT_QUOTES, 'UTF-8') ?></p><a class="choice" href="/day-custom-catalog-add.php?id=<?= (int) $day['id'] ?>"><strong>Eigenen Programmpunkt aus dem Katalog hinzufügen</strong>Aus den gespeicherten eigenen Programmpunkten auswählen.</a><a class="choice" href="/day-items.php?id=<?= (int) $day['id'] ?>"><strong>Freien Programmpunkt nur für diese Reise hinzufügen</strong>Eigene Aktivität oder individuellen Hinweis eintragen.</a><a class="choice" href="/day-attraction-add.php?id=<?= (int) $day['id'] ?>"><strong>Sehenswürdigkeit hinzufügen</strong>Aus den angelegten Sehenswürdigkeiten auswählen.</a><a class="choice" href="/day-catalog-add.php?id=<?= (int) $day['id'] ?>&type=accommodation"><strong>Unterkunft hinzufügen</strong>Aus den angelegten Unterkünften auswählen.</a><a class="choice" href="/day-catalog-add.php?id=<?= (int) $day['id'] ?>&type=restaurant"><strong>Essen &amp; Trinken hinzufügen</strong>Aus den angelegten Einträgen auswählen.</a><section class="items"><h2>Bestehendes Programm</h2><p class="muted"><span class="sort-desktop">Mit den drei Strichen kannst du die Reihenfolge ändern.</span><span class="sort-mobile">Mit „Hoch“ und „Runter“ kannst du die Reihenfolge ändern.</span></p><div id="program-list"><?php if (!$items): ?><p class="muted">Noch keine Programmpunkte für diesen Tag.</p><?php endif; ?><?php foreach ($items as $item): ?><?php $name=$item['title'] ?: $item['attraction_name'] ?: $item['accommodation_name'] ?: $item['restaurant_name'] ?: $item['custom_point_name'] ?: 'Programmpunkt'; $image=$item['custom_image']?:$item['attraction_image']?:$item['accommodation_image']?:$item['restaurant_image']?:$item['custom_point_image']?:null; ?><div class="item" draggable="true" data-id="<?= (int) $item["id"] ?>"><span class="handle" title="Verschieben">☰</span><?php if($image): ?><img class="thumb" src="/<?= htmlspecialchars($image,ENT_QUOTES,'UTF-8') ?>" alt=""><?php endif; ?><div class="type"><?= $labels[$item['item_type']] ?? 'Programmpunkt' ?></div><strong><?php if ($item['time']): ?><span class="time"><?= htmlspecialchars(substr($item['time'],0,5),ENT_QUOTES,'UTF-8') ?> – </span><?php endif; ?><?= htmlspecialchars($name,ENT_QUOTES,'UTF-8') ?></strong><?php if ($item['trip_additional_info']): ?><div class="muted"><?= render_rich_text($item['trip_additional_info']) ?></div><?php endif; ?><div><?php if ($item['item_type'] === 'custom'): ?><a class="button small" href="/item-edit.php?id=<?= (int) $item['id'] ?>">Bearbeiten</a><?php else: ?><a class="button small" href="/planned-item-edit.php?id=<?= (int) $item['id'] ?>">Hinweis bearbeiten</a><?php endif; ?><form method="post" style="display:inline" onsubmit='return confirm("Diesen Programmpunkt wirklich löschen?");'><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8') ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="item_id" value="<?= (int) $item['id'] ?>"><button class="button small delete" type="submit">Löschen</button></form></div></div><?php endforeach; ?></div></section></main><script>const list=document.getElementById("program-list");let dragged=null;function saveOrder(){const data=new FormData();data.append("csrf_token",document.querySelector("input[name=csrf_token]").value);data.append("action","reorder");data.append("order",[...list.children].map(el=>el.dataset.id).join(","));fetch(location.href,{method:"POST",body:data});}list.querySelectorAll(".item").forEach(item=>{item.addEventListener("dragstart",()=>{dragged=item;item.classList.add("dragging");});item.addEventListener("dragend",()=>{item.classList.remove("dragging");saveOrder();});item.addEventListener("dragover",event=>{event.preventDefault();if(dragged&&dragged!==item){const before=event.clientY<item.getBoundingClientRect().top+item.offsetHeight/2;list.insertBefore(dragged,before?item:item.nextSibling);}});});</script><script>document.querySelectorAll("#program-list > .item").forEach(item=>{const controls=document.createElement("div");controls.className="mobile-sort";const up=document.createElement("button");up.type="button";up.textContent="↑ Hoch";const down=document.createElement("button");down.type="button";down.textContent="↓ Runter";controls.append(up,down);item.append(controls);up.addEventListener("click",()=>{const previous=item.previousElementSibling;if(previous){list.insertBefore(item,previous);saveOrder();}});down.addEventListener("click",()=>{const next=item.nextElementSibling;if(next){list.insertBefore(next,item);saveOrder();}});});</script></body></html>
