<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/countries.php';
require_once __DIR__ . '/app/Helpers/categories.php';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, [
        '<html lang="de">' => '<html lang="en">', 'Eigener Programmpunkt · TripTale' => t('custom_points.singular') . ' · TripTale',
        '>← Zurück<' => '>' . t('users.back') . '<', '>Programmpunkt bearbeiten<' => '>' . t('custom_points.edit_title') . '<',
        '>Neuer Programmpunkt<' => '>' . t('custom_points.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<textarea' => '>' . t('attraction.description') . '<textarea', '>Adresse<input' => '>' . t('attraction.address') . '<input',
        '>Ort<input' => '>' . t('attraction.city') . '<input', '>Land<select' => '>' . t('attraction.country') . '<select',
        '>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') . '<',
    ]);
});
ob_start(static function (string $html): string {
    $notice = ($_GET['image'] ?? '') === 'changed' ? t('attraction.image_saved') : ((($_GET['image'] ?? '') === 'deleted') ? t('attraction.image_deleted') : '');
    return $notice === '' ? $html : str_replace('<form method="post">', '<p class="success">' . htmlspecialchars($notice, ENT_QUOTES, 'UTF-8') . '</p><form method="post">', $html);
});
set_exception_handler(static function (Throwable $e): void { http_response_code(500); exit('<main style="font-family:system-ui;padding:24px"><h1>' . htmlspecialchars(t('custom_points.error_save'), ENT_QUOTES, 'UTF-8') . '</h1></main>'); });
$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'=>'','status'=>'active'];$error=null;$categories=triptale_categories('custom');$selectedCategoryIds=[];if($id){try{$selectedCategoryIds=triptale_selected_category_ids('custom_point',(int)$id);}catch(Throwable $exception){$selectedCategoryIds=[];}}
if($id){$q=db()->prepare('SELECT * FROM '.table('custom_points').' WHERE id=:id');$q->execute([':id'=>$id]);$item=$q->fetch();if(!$item){http_response_code(404);exit(t('custom_points.error_not_found'));}if($user['role']!=='main_admin'&&(int)$item['created_by']!==(int)$user['id']){http_response_code(403);exit(t('image.error_access'));}}
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();$selectedCategoryIds=triptale_category_ids((array)($_POST['category_ids']??[]),'custom');$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']??''));$country=strtoupper(trim((string)($_POST['country_code']??'')));$status=(string)($_POST['status']??'active');if($name===''){$error=t('custom_points.error_name');}elseif($country!==''&&!array_key_exists($country,triptale_countries())){$error=t('custom_points.error_country');}else{try{if($id){$q=db()->prepare('UPDATE '.table('custom_points').' SET name=:name,short_description=:short,description=:description,address=:address,city=:city,country_code=:country,status=:status,updated_by=:user WHERE id=:id');$q->execute([':name'=>$name,':short'=>$short?:null,':description'=>$description?:null,':address'=>$address?:null,':city'=>$city?:null,':country'=>$country?:null,':status'=>$status,':user'=>$user['id'],':id'=>$id]);}else{$q=db()->prepare('INSERT INTO '.table('custom_points').' (name,short_description,description,address,city,country_code,status,created_by,updated_by) VALUES (:name,:short,:description,:address,:city,:country,:status,:created_by,:updated_by)');$q->execute([':name'=>$name,':short'=>$short?:null,':description'=>$description?:null,':address'=>$address?:null,':city'=>$city?:null,':country'=>$country?:null,':status'=>$status,':created_by'=>$user['id'],':updated_by'=>$user['id']]);}$savedId=$id?(int)$id:(int)db()->lastInsertId();triptale_sync_categories('custom_point',$savedId,$selectedCategoryIds);header('Location: /custom-points.php?saved=1');exit;}catch(Throwable $exception){$error=t('custom_points.error_save');}}}
?><!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Eigener Programmpunkt · 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}label{display:block;margin-top:14px;font-weight:700}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,.save{display:inline-block;padding:9px 12px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700}.back{background:#e3ebee;color:#126e82}.save{margin-top:20px}.error{background:#ffe6e3;padding:12px;border-radius:7px}@media(max-width:600px){body{padding:12px}main{padding:16px}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/custom-points.php">← Zurück</a><h1><?= $id?'Programmpunkt bearbeiten':'Neuer Programmpunkt' ?></h1><?php if($id): ?><a class="button" href="/image-upload.php?type=custom_point&id=<?= (int)$id ?>">Bild bearbeiten</a><?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>Kurzbeschreibung<input name="short_description" value="<?= htmlspecialchars((string)($_POST['short_description']??$item['short_description']),ENT_QUOTES,'UTF-8') ?>"></label><label>Beschreibung<textarea name="description"><?= htmlspecialchars((string)($_POST['description']??$item['description']),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>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>
