<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return str_replace(['← Meine Reisen','Neue Reise','Für jeden Kalendertag wird automatisch ein Reisetag angelegt.','<label>Titel<input','Untertitel (optional)','Beschreibung (optional)','Startdatum','Enddatum','Reise anlegen'], [t('trip.back'),t('create.title'),t('create.intro'),'<label>' . t('form.title') . '<input',t('form.subtitle_optional'),t('form.description_optional'),t('form.start_date'),t('form.end_date'),t('create.submit')], $html);
});
$user = require_login();
if (!in_array($user['role'], ['main_admin', 'admin'], true)) { http_response_code(403); exit('Du darfst keine Reisen anlegen.'); }
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'] ?? ''));
    $subtitle = trim((string)($_POST['subtitle'] ?? ''));
    $description = sanitize_rich_text((string)($_POST['description'] ?? ''));
    $startDate = (string)($_POST['start_date'] ?? '');
    $endDate = (string)($_POST['end_date'] ?? '');
    $start = DateTimeImmutable::createFromFormat('!Y-m-d', $startDate);
    $end = DateTimeImmutable::createFromFormat('!Y-m-d', $endDate);
    if ($title === '' || !$start || !$end || $start->format('Y-m-d') !== $startDate || $end->format('Y-m-d') !== $endDate) {
        $error = t('create.error_dates');
    } elseif ($end < $start) {
        $error = t('create.error_order');
    } elseif ($start->diff($end)->days > 366) {
        $error = t('create.error_length');
    } else {
        try {
            $pdo = db();
            $pdo->beginTransaction();
            $insertTrip = $pdo->prepare('INSERT INTO ' . table('trips') . ' (title, subtitle, description, start_date, end_date, created_by) VALUES (:title, :subtitle, :description, :start_date, :end_date, :created_by)');
            $insertTrip->execute([':title' => $title, ':subtitle' => $subtitle ?: null, ':description' => $description ?: null, ':start_date' => $startDate, ':end_date' => $endDate, ':created_by' => $user['id']]);
            $tripId = (int)$pdo->lastInsertId();
            $pdo->prepare('INSERT INTO ' . table('trip_admins') . ' (trip_id, user_id) VALUES (:trip_id, :user_id)')->execute([':trip_id' => $tripId, ':user_id' => $user['id']]);
            $insertDay = $pdo->prepare('INSERT INTO ' . table('trip_days') . ' (trip_id, day_number, date, title, sort_order) VALUES (:trip_id, :day_number, :date, :title, :sort_order)');
            $dayNumber = 1;
            for ($day = $start; $day <= $end; $day = $day->modify('+1 day')) {
                $insertDay->execute([':trip_id' => $tripId, ':day_number' => $dayNumber, ':date' => $day->format('Y-m-d'), ':title' => t('trip.day') . ' ' . $dayNumber, ':sort_order' => $dayNumber]);
                $dayNumber++;
            }
            $pdo->commit();
            header('Location: /trip.php?id=' . $tripId);
            exit;
        } catch (Throwable $exception) {
            if (db()->inTransaction()) { db()->rollBack(); }
            $error = t('create.error_save');
        }
    }
}
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Neue Reise · 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,textarea{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}textarea{min-height:130px}button{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}}@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="/dashboard.php">← Meine Reisen</a><h1>Neue Reise</h1><p>Für jeden Kalendertag wird automatisch ein Reisetag angelegt.</p><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><label>Titel<input name="title" required value="<?= htmlspecialchars((string)($_POST['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Untertitel (optional)<input name="subtitle" value="<?= htmlspecialchars((string)($_POST['subtitle'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Beschreibung (optional)<textarea name="description"><?= htmlspecialchars((string)($_POST['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?></textarea></label><label>Startdatum<input name="start_date" type="date" required value="<?= htmlspecialchars((string)($_POST['start_date'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Enddatum<input name="end_date" type="date" required value="<?= htmlspecialchars((string)($_POST['end_date'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><button type="submit">Reise anlegen</button></form></main></body></html>
