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

$user = require_login();
$tripId = (int)($_GET['id'] ?? 0);
$query = db()->prepare('SELECT id,title,created_by FROM ' . table('trips') . ' WHERE id=?');
$query->execute([$tripId]);
$trip = $query->fetch();
if (!$trip) { exit('Reise nicht gefunden.'); }
$query = db()->prepare('SELECT 1 FROM ' . table('trip_admins') . ' WHERE trip_id=? AND user_id=? UNION SELECT 1 FROM ' . table('trip_participants') . ' WHERE trip_id=? AND user_id=?');
$query->execute([$tripId, $user['id'], $tripId, $user['id']]);
if ($user['role'] !== 'main_admin' && (int)$trip['created_by'] !== (int)$user['id'] && !$query->fetchColumn()) { exit('Kein Zugriff.'); }

$editId = (int)($_GET['edit'] ?? 0);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    $itemId = (int)($_POST['item_id'] ?? 0);
    if ($action === 'reorder') {
        $ids = array_filter(array_map('intval', explode(',', $_POST['order'] ?? '')));
        $query = db()->prepare('UPDATE ' . table('trip_checklist_items') . ' SET sort_order=? WHERE id=? AND trip_id=? AND user_id=?');
        foreach ($ids as $number => $id) { $query->execute([$number + 1, $id, $tripId, $user['id']]); }
        exit;
    }
    if ($action === 'add' && trim($_POST['title'] ?? '') !== '') {
        $query = db()->prepare('INSERT INTO ' . table('trip_checklist_items') . ' (trip_id,user_id,title) VALUES (?,?,?)');
        $query->execute([$tripId, $user['id'], trim($_POST['title'])]);
    } elseif ($action === 'toggle') {
        $query = db()->prepare('UPDATE ' . table('trip_checklist_items') . ' SET is_done=1-is_done WHERE id=? AND trip_id=? AND user_id=?');
        $query->execute([$itemId, $tripId, $user['id']]);
    } elseif ($action === 'delete') {
        $query = db()->prepare('DELETE FROM ' . table('trip_checklist_items') . ' WHERE id=? AND trip_id=? AND user_id=?');
        $query->execute([$itemId, $tripId, $user['id']]);
    } elseif ($action === 'save' && trim($_POST['title'] ?? '') !== '') {
        $query = db()->prepare('UPDATE ' . table('trip_checklist_items') . ' SET title=? WHERE id=? AND trip_id=? AND user_id=?');
        $query->execute([trim($_POST['title']), $itemId, $tripId, $user['id']]);
    }
    header('Location: /trip-checklist.php?id=' . $tripId);
    exit;
}
$query = db()->prepare('SELECT * FROM ' . table('trip_checklist_items') . ' WHERE trip_id=? AND user_id=? ORDER BY is_done,sort_order,id');
$query->execute([$tripId, $user['id']]);
$items = $query->fetchAll();
?>
<!doctype html>
<html lang="<?= htmlspecialchars(language(), ENT_QUOTES, 'UTF-8') ?>">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/assets/triptale-ui.css?v=19">
<style>body{font-family:system-ui;background:#f4f6f8;margin:0;color:#17202a}main{max-width:720px;margin:30px auto;padding:0 18px}.card{background:#fff;border:1px solid #d6e0e4;border-left:4px solid #75aeb9;border-radius:12px;padding:14px;margin:10px 0}.button{background:#126e82;color:#fff;border:0;border-radius:7px;padding:9px 12px;text-decoration:none;font-weight:700;cursor:pointer;margin:4px 6px 0 0}.back,.edit{background:#e3ebee;color:#126e82}.delete{background:#9d2d2d}.add,.row{display:flex;align-items:center;gap:9px}.add input{flex:1;min-width:0;padding:10px;border:1px solid #b9c1c8;border-radius:7px}.title{flex:1;font-weight:700}.done .title{text-decoration:line-through;color:#59636d;font-weight:400}.check{width:22px;height:22px;accent-color:#126e82}.handle{font-size:1.4rem;color:#59636d;cursor:grab}.hint{color:#59636d;font-size:.92rem}.mobile-hint,.move{display:none}.drag{opacity:.4}@media(max-width:600px){main{margin:18px auto;padding:0 12px}.add{display:block}.add input{box-sizing:border-box;width:100%;margin-bottom:8px}.row{flex-wrap:wrap}.title{min-width:45%}.handle,.desktop-hint{display:none}.mobile-hint,.move{display:block}.move button{padding:6px 9px;border:1px solid #b9c1c8;border-radius:6px;background:#fff;color:#126e82;font-weight:700}}</style>
</head>
<body>
<main>
<a class="button back" href="/trip.php?id=<?= $tripId ?>"><?= htmlspecialchars(t('common.back_to_trip'), ENT_QUOTES, 'UTF-8') ?></a>
<h1><?= htmlspecialchars(t('trip.checklist'), ENT_QUOTES, 'UTF-8') ?></h1>
<p class="hint"><?= htmlspecialchars(t('checklist.private_hint'), ENT_QUOTES, 'UTF-8') ?></p>
<section class="card"><form method="post" class="add"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input name="title" placeholder="<?= htmlspecialchars(t('checklist.placeholder'), ENT_QUOTES, 'UTF-8') ?>" required><button class="button" name="action" value="add"><?= htmlspecialchars(t('checklist.add'), ENT_QUOTES, 'UTF-8') ?></button></form></section>
<p class="hint desktop-hint"><?= htmlspecialchars(t('checklist.desktop_hint'), ENT_QUOTES, 'UTF-8') ?></p><p class="hint mobile-hint"><?= htmlspecialchars(t('checklist.mobile_hint'), ENT_QUOTES, 'UTF-8') ?></p>
<div id="list"><?php foreach ($items as $item): ?><section class="card<?= $item['is_done'] ? ' done' : '' ?>" data-id="<?= (int)$item['id'] ?>" draggable="<?= $item['is_done'] ? 'false' : 'true' ?>"><?php if ($editId === (int)$item['id']): ?><form method="post" class="add"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="item_id" value="<?= (int)$item['id'] ?>"><input name="title" value="<?= htmlspecialchars($item['title'], ENT_QUOTES, 'UTF-8') ?>" required><button class="button" name="action" value="save"><?= htmlspecialchars(t('common.save'), ENT_QUOTES, 'UTF-8') ?></button><a class="button edit" href="/trip-checklist.php?id=<?= $tripId ?>"><?= htmlspecialchars(t('common.cancel'), ENT_QUOTES, 'UTF-8') ?></a></form><?php else: ?><div class="row"><form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="item_id" value="<?= (int)$item['id'] ?>"><input type="hidden" name="action" value="toggle"><input class="check" type="checkbox"<?= $item['is_done'] ? ' checked' : '' ?> onchange="this.form.submit()"></form><?php if (!$item['is_done']): ?><span class="handle">☰</span><?php endif; ?><span class="title"><?= htmlspecialchars($item['title'], ENT_QUOTES, 'UTF-8') ?></span><?php if (!$item['is_done']): ?><span class="move"><button type="button" data-up>↑ <?= htmlspecialchars(t('checklist.up'), ENT_QUOTES, 'UTF-8') ?></button><button type="button" data-down>↓ <?= htmlspecialchars(t('checklist.down'), ENT_QUOTES, 'UTF-8') ?></button></span><?php endif; ?><a class="button edit" href="/trip-checklist.php?id=<?= $tripId ?>&edit=<?= (int)$item['id'] ?>"><?= htmlspecialchars(t('common.edit'), ENT_QUOTES, 'UTF-8') ?></a><form method="post" onsubmit="return confirm(<?= htmlspecialchars(tjs('checklist.confirm_delete'), ENT_QUOTES, 'UTF-8') ?>)"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="item_id" value="<?= (int)$item['id'] ?>"><button class="button delete" name="action" value="delete"><?= htmlspecialchars(t('common.delete'), ENT_QUOTES, 'UTF-8') ?></button></form></div><?php endif; ?></section><?php endforeach; ?></div>
</main>
<script>let l=document.querySelector('#list'),d;function s(){let f=new FormData;f.append('csrf_token',document.querySelector('[name=csrf_token]').value);f.append('action','reorder');f.append('order',[...l.querySelectorAll('.card:not(.done)')].map(x=>x.dataset.id).join(','));fetch(location.href,{method:'POST',body:f})}l.querySelectorAll('[draggable=true]').forEach(x=>{x.ondragstart=()=>{d=x;x.classList.add('drag')};x.ondragend=()=>{x.classList.remove('drag');s()};x.ondragover=e=>{e.preventDefault();if(d&&d!==x)l.insertBefore(d,e.clientY<x.getBoundingClientRect().top+x.offsetHeight/2?x:x.nextSibling)}});l.querySelectorAll('[data-up],[data-down]').forEach(b=>b.onclick=()=>{let c=b.closest('.card'),n=b.hasAttribute('data-up')?c.previousElementSibling:c.nextElementSibling;if(n&&!n.classList.contains('done'))l.insertBefore(b.hasAttribute('data-up')?c:n,b.hasAttribute('data-up')?n:c);s()})</script>
</body>
</html>
