<?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">', 'Unterkünfte · TripTale' => t('accommodation.title') . ' · TripTale', 'Essen & Trinken · TripTale' => t('restaurant.title') . ' · TripTale',
        '>← Zurück<' => '>' . t('users.back') . '<', '>Unterkünfte bearbeiten<' => '>' . t('accommodation.edit_title') . '<', '>Accommodation bearbeiten<' => '>' . t('accommodation.edit_title') . '<',
        '>Neue Unterkünfte<' => '>' . t('accommodation.create_title') . '<', '>Unterkunft bearbeiten<' => '>' . t('accommodation.edit_title') . '<',
        '>Neue Unterkunft<' => '>' . t('accommodation.create_title') . '<', '>Neue Accommodation<' => '>' . t('accommodation.create_title') . '<',
        '>Essen & Trinken bearbeiten<' => '>' . t('restaurant.edit_title') . '<', '>Food & drink bearbeiten<' => '>' . t('restaurant.edit_title') . '<', '>Neue Essen & Trinken<' => '>' . t('restaurant.create_title') . '<', '>Neue Food & drink<' => '>' . t('restaurant.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', '>Beschreibung<textarea' => '>' . t('accommodation.description') . '<textarea',
        '>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') . '"',
        '>Website<input' => '>' . t('accommodation.website') . '<input', '>Telefon<input' => '>' . t('accommodation.phone') . '<input',
        '>Interne Notiz<textarea' => '>' . t('accommodation.internal_note') . '<textarea', '>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') . '<',
    ]);
});

$user = require_login();
if (!in_array($user['role'], ['main_admin', 'admin'], true)) { http_response_code(403); exit(t('image.error_access')); }
$type = (string) ($_GET['type'] ?? '');
$types = [
    'accommodation' => ['table' => 'accommodations', 'label' => t('accommodation.singular')],
    'restaurant' => ['table' => 'restaurants', 'label' => t('restaurant.singular')],
];
if (!isset($types[$type])) { http_response_code(404); exit(t('accommodation.error_area')); }
$meta = $types[$type];
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$item = ['name'=>'','description'=>'','address'=>'','city'=>'','country_code'=>'','website'=>'','phone'=>'','google_maps_url'=>'','plus_code'=>'','note'=>'','status'=>'active'];
$error = null;

try {
    if ($id) { $q = db()->prepare('SELECT * FROM ' . table($meta['table']) . ' WHERE id=:id'); $q->execute([':id'=>$id]); $item=$q->fetch(); if (!$item) { http_response_code(404); exit(t('image.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 = $type === 'restaurant' ? t('restaurant.error_structure') : t('accommodation.error_structure'); }

$categories = triptale_categories($type);
$selectedCategoryIds = $id ? triptale_selected_category_ids($type, (int) $id) : [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {
    verify_csrf();
    $selectedCategoryIds = triptale_category_ids((array) ($_POST['category_ids'] ?? []), $type);
    $countryCode=strtoupper(trim((string)($_POST['country_code']??''))); $name=trim((string)($_POST['name']??'')); $description=sanitize_rich_text((string)($_POST['description']??'')); $address=trim((string)($_POST['address']??'')); $city=trim((string)($_POST['city']??'')); $website=trim((string)($_POST['website']??'')); $phone=trim((string)($_POST['phone']??'')); $mapsUrl=trim((string)($_POST['google_maps_url']??'')); $plusCode=trim((string)($_POST['plus_code']??'')); $note=trim((string)($_POST['note']??'')); $status=(string)($_POST['status']??'active');
    if ($name === '') { $error=t($type === 'restaurant' ? 'restaurant.error_name' : 'accommodation.error_name'); }
    elseif ($countryCode!=='' && !array_key_exists($countryCode,triptale_countries())) { $error=t($type === 'restaurant' ? 'restaurant.error_country' : 'accommodation.error_country'); }
    elseif ($website !== '' && !filter_var($website, FILTER_VALIDATE_URL)) { $error=t($type === 'restaurant' ? 'restaurant.error_website' : 'accommodation.error_website'); }
    elseif ($mapsUrl !== '' && (!filter_var($mapsUrl, FILTER_VALIDATE_URL) || !in_array(parse_url($mapsUrl, PHP_URL_SCHEME), ['http','https'], true))) { $error=t($type === 'restaurant' ? 'restaurant.error_maps' : 'accommodation.error_maps'); }
    else {
        try {
            if ($id) {
                $save=db()->prepare('UPDATE '.table($meta['table']).' SET name=:name,description=:description,address=:address,city=:city,country_code=:country_code,website=:website,phone=:phone,google_maps_url=:maps_url,plus_code=:plus_code,note=:note,status=:status,updated_by=:updated_by WHERE id=:id');
                $save->execute([':name'=>$name,':description'=>$description?:null,':address'=>$address?:null,':city'=>$city?:null,':country_code'=>$countryCode?:null,':website'=>$website?:null,':phone'=>$phone?:null,':maps_url'=>$mapsUrl?:null,':plus_code'=>$plusCode?:null,':note'=>$note?:null,':status'=>$status,':updated_by'=>$user['id'],':id'=>$id]);
            } else {
                $save=db()->prepare('INSERT INTO '.table($meta['table']).' (name,description,address,city,country_code,website,phone,google_maps_url,plus_code,note,status,created_by,updated_by) VALUES (:name,:description,:address,:city,:country_code,:website,:phone,:maps_url,:plus_code,:note,:status,:created_by,:updated_by)');
                $save->execute([':name'=>$name,':description'=>$description?:null,':address'=>$address?:null,':city'=>$city?:null,':country_code'=>$countryCode?:null,':website'=>$website?:null,':phone'=>$phone?:null,':maps_url'=>$mapsUrl?:null,':plus_code'=>$plusCode?:null,':note'=>$note?:null,':status'=>$status,':created_by'=>$user['id'],':updated_by'=>$user['id']]);
            }
            $savedId = $id ? (int) $id : (int) db()->lastInsertId();
            triptale_sync_categories($type, $savedId, $selectedCategoryIds);
            header('Location: /catalog.php?type='.$type.'&saved=1'); exit;
        } catch (Throwable $exception) { $error=$type === 'restaurant' ? t('restaurant.error_save') : t('accommodation.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><?= $meta['label'] ?> · 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:14px;font-weight:600}input,textarea,select{box-sizing:border-box;width:100%;padding:10px;margin-top:5px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}textarea{min-height:130px}.button{display:inline-block;padding:8px 11px;background:#e3ebee;color:#126e82;border-radius:7px;text-decoration:none;font-weight:700}.save{margin-top:20px;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="/catalog.php?type=<?= $type ?>">← Zurück</a><h1><?= $id ? $meta['label'].' bearbeiten' : 'Neue '.$meta['label'] ?></h1><?php if($id): ?><a class="button image-button" href="/image-upload.php?type=<?= $type ?>&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"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8') ?>"><label>Name<input name="name" required value="<?= htmlspecialchars((string)($_POST['name']??$item['name']),ENT_QUOTES,'UTF-8') ?>"></label><label>Beschreibung<textarea name="description"><?= htmlspecialchars((string)$descriptionValue,ENT_QUOTES,'UTF-8') ?></textarea></label><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>Website<input name="website" type="url" value="<?= htmlspecialchars((string)($_POST['website']??$item['website']??''),ENT_QUOTES,'UTF-8') ?>"></label><label>Telefon<input name="phone" value="<?= htmlspecialchars((string)($_POST['phone']??$item['phone']??''),ENT_QUOTES,'UTF-8') ?>"></label><label>Interne Notiz<textarea name="note"><?= htmlspecialchars((string)($_POST['note']??$item['note']??''),ENT_QUOTES,'UTF-8') ?></textarea></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">Aktiv</option><option value="inactive"<?= (($_POST['status']??$item['status'])==='inactive')?' selected':'' ?>>Deaktiviert</option></select></label><button class="save">Speichern</button></form></main></body></html>
