<?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';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, [
        '<html lang="de">' => '<html lang="en">', 'Sehenswürdigkeit · TripTale' => t('attraction.title') . ' · TripTale',
        '>← Zurück<' => '>' . t('users.back') . '<', '>Sehenswürdigkeit bearbeiten<' => '>' . t('attraction.edit_title') . '<',
        '>Neue Sehenswürdigkeit<' => '>' . t('attraction.create_title') . '<', '>Bild bearbeiten<' => '>' . t('attraction.image_edit') . '<',
        '>Bild gespeichert.<' => '>' . t('attraction.image_saved') . '<', '>Bild gelöscht.<' => '>' . t('attraction.image_deleted') . '<',
        '>Name<input' => '>' . t('attraction.name') . '<input', '>Kurzbeschreibung<input' => '>' . t('attraction.short_description') . '<input',
        '>Beschreibung<' => '>' . t('attraction.description') . '<', '>Adresse<input' => '>' . t('attraction.address') . '<input',
        '>Ort<input' => '>' . t('attraction.city') . '<input', '>Land<select' => '>' . t('attraction.country') . '<select',
        '>Google-Maps-Link<input' => '>' . t('attraction.maps') . '<input', 'placeholder="https://maps.google.com/…"' => 'placeholder="' . htmlspecialchars(t('attraction.maps_hint'), ENT_QUOTES, 'UTF-8') . '"',
        '>Plus Code<input' => '>' . t('attraction.plus_code') . '<input', 'placeholder="z. B. 9C5M+Q8"' => 'placeholder="' . htmlspecialchars(t('attraction.plus_code_hint'), ENT_QUOTES, 'UTF-8') . '"',
        '>Kategorien <small>' => '>' . t('category.prefix') . ' <small>', '>(mehrere möglich)<' => '>' . t('category.multiple') . '<',
        '>Status<select' => '>' . t('attraction.status') . '<select', '>Aktiv<' => '>' . t('attraction.active') . '<', '>Deaktiviert<' => '>' . t('attraction.inactive') . '<',
        '>Speichern<' => '>' . t('common.save') . '<', '>Fett<' => '>' . t('editor.bold') . '<', '>Kursiv<' => '>' . t('editor.italic') . '<',
        '>Liste<' => '>' . t('editor.list') . '<', '>1. Liste<' => '>' . t('editor.numbered_list') . '<', '>Link<' => '>' . t('editor.link') . '<',
        '>Textstil…<' => '>' . t('editor.style') . '<', '>Normal<' => '>' . t('editor.normal') . '<', '>Überschrift<' => '>' . t('editor.heading') . '<', '>Kleine Überschrift<' => '>' . t('editor.small_heading') . '<',
    ]);
});

$user = require_login();
if (!in_array($user['role'], ['main_admin', 'admin'], true)) { http_response_code(403); exit(t('image.error_access')); }
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$item = ['name'=>'','short_description'=>'','description'=>'','address'=>'','city'=>'','country_code'=>'','google_maps_url'=>'','plus_code'=>'','status'=>'active'];
$error = null;
try {
    if ($id) { $query = db()->prepare('SELECT * FROM ' . table('attractions') . ' WHERE id = :id'); $query->execute([':id' => $id]); $item = $query->fetch(); if (!$item) { http_response_code(404); exit(t('attraction.error_not_found')); } if($user['role']!=='main_admin'&&(int)$item['created_by']!==(int)$user['id']){http_response_code(403);exit(t('image.error_access'));} }
} catch (Throwable $exception) { $error = t('attraction.error_structure'); }
$categories = triptale_categories('attraction');
$selectedCategoryIds = $id ? triptale_selected_category_ids('attraction', (int) $id) : [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {
    verify_csrf();
    $selectedCategoryIds = triptale_category_ids((array) ($_POST['category_ids'] ?? []), 'attraction');
    $countryCode=strtoupper(trim((string)($_POST['country_code']??''))); $name = trim((string)($_POST['name'] ?? '')); $short = trim((string)($_POST['short_description'] ?? '')); $description = sanitize_rich_text((string)($_POST['description'] ?? '')); $address = trim((string)($_POST['address'] ?? '')); $city = trim((string)($_POST['city'] ?? '')); $mapsUrl = trim((string)($_POST['google_maps_url'] ?? '')); $plusCode = trim((string)($_POST['plus_code'] ?? '')); $status = (string)($_POST['status'] ?? 'active');
    if ($name === '') { $error = t('attraction.error_name'); }
    elseif ($countryCode!=='' && !array_key_exists($countryCode,triptale_countries())) { $error=t('attraction.error_country'); }
    elseif (!in_array($status, ['active', 'inactive'], true)) { $error = t('attraction.error_status'); }
    elseif ($mapsUrl !== '' && (!filter_var($mapsUrl, FILTER_VALIDATE_URL) || !in_array(parse_url($mapsUrl, PHP_URL_SCHEME), ['http', 'https'], true))) { $error = t('attraction.error_maps'); }
    else {
        try {
            if ($id) {
                $save = db()->prepare('UPDATE ' . table('attractions') . ' SET name=:name, short_description=:short, description=:description, address=:address, city=:city, country_code=:country_code, google_maps_url=:maps_url, plus_code=:plus_code, status=:status, updated_by=:updated_by WHERE id=:id');
                $save->execute([':name'=>$name,':short'=>$short?:null,':description'=>$description?:null,':address'=>$address?:null,':city'=>$city?:null,':country_code'=>$countryCode?:null,':maps_url'=>$mapsUrl?:null,':plus_code'=>$plusCode?:null,':status'=>$status,':updated_by'=>$user['id'],':id'=>$id]);
            } else {
                $save = db()->prepare('INSERT INTO ' . table('attractions') . ' (name, short_description, description, address, city, country_code, google_maps_url, plus_code, status, created_by, updated_by) VALUES (:name,:short,:description,:address,:city,:country_code,:maps_url,:plus_code,:status,:created_by,:updated_by)');
                $save->execute([':name'=>$name,':short'=>$short?:null,':description'=>$description?:null,':address'=>$address?:null,':city'=>$city?:null,':country_code'=>$countryCode?:null,':maps_url'=>$mapsUrl?:null,':plus_code'=>$plusCode?:null,':status'=>$status,':created_by'=>$user['id'],':updated_by'=>$user['id']]);
            }
            $savedId = $id ? (int) $id : (int) db()->lastInsertId();
            triptale_sync_categories('attraction', $savedId, $selectedCategoryIds);
            header('Location: /attractions.php?saved=1'); exit;
        } catch (Throwable $exception) { $error = t('attraction.error_save'); }
    }
}
$descriptionValue = $_POST['description'] ?? $item['description'] ?? '';
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sehenswürdigkeit · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:720px;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:150px;margin-top:6px;padding:11px;border:1px solid #b9c1c8;border-radius:0 0 7px 7px;font-weight:400}.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:8px 11px;background:#e3ebee;color:#126e82;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}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}}.image-button{background:#126e82!important;color:#fff!important}.success{background:#e6f5e9;padding:12px;border-radius:7px;color:#1d6831}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/attractions.php">← Zurück</a><h1><?= $id ? 'Sehenswürdigkeit bearbeiten' : 'Neue Sehenswürdigkeit' ?></h1><?php if ($id): ?><a class="button image-button" href="/image-upload.php?type=attraction&id=<?= (int)$id ?>">Bild bearbeiten</a><?php endif; ?><?php if(($_GET['image']??'')==='changed'): ?><p class="success">Bild gespeichert.</p><?php elseif(($_GET['image']??'')==='deleted'): ?><p class="success">Bild gelöscht.</p><?php endif; ?><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><form method="post" id="attraction-form"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="description" id="description-value"><label>Name<input name="name" required value="<?= htmlspecialchars((string)($_POST['name'] ?? $item['name']), ENT_QUOTES, 'UTF-8') ?>"></label><label>Kurzbeschreibung<input name="short_description" value="<?= htmlspecialchars((string)($_POST['short_description'] ?? $item['short_description'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Beschreibung</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="description-editor" contenteditable="true"><?= render_rich_text((string)$descriptionValue) ?></div><label>Adresse<input name="address" value="<?= htmlspecialchars((string)($_POST['address'] ?? $item['address'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Ort<input name="city" value="<?= htmlspecialchars((string)($_POST['city'] ?? $item['city'] ?? ''), 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>Google-Maps-Link<input name="google_maps_url" type="url" placeholder="https://maps.google.com/…" value="<?= htmlspecialchars((string)($_POST['google_maps_url'] ?? $item['google_maps_url'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></label><label>Plus Code<input name="plus_code" placeholder="z. B. 9C5M+Q8" value="<?= htmlspecialchars((string)($_POST['plus_code'] ?? $item['plus_code'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"></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>Status<select name="status"><option value="active"<?= (($_POST['status'] ?? $item['status']) === 'active') ? ' selected' : '' ?>>Aktiv</option><option value="inactive"<?= (($_POST['status'] ?? $item['status']) === 'inactive') ? ' selected' : '' ?>>Deaktiviert</option></select></label><button class="save" type="submit">Speichern</button></form></main><script>const editor=document.getElementById('description-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('attraction-form').addEventListener('submit',()=>{document.getElementById('description-value').value=editor.innerHTML;});</script></body></html>
