<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/countries.php';
ob_start(static function (string $html): string {
    return strtr($html, [
        '<html lang="de">' => '<html lang="en">', 'Eigene Programmpunkte · TripTale' => t('custom_points.title') . ' · TripTale',
        '>← Zurück<' => '>' . t('users.back') . '<', '>Eigene Programmpunkte<' => '>' . t('custom_points.title') . '<',
        '>Wiederverwendbare Programmpunkte. Reisespezifische freie Punkte erscheinen hier nicht.<' => '>' . t('custom_points.intro') . '<',
        '>+ Neuer Programmpunkt<' => '>' . t('custom_points.new') . '<', '>Suche<input' => '>' . t('attraction.search') . '<input',
        'placeholder="Name oder Ort eingeben …"' => 'placeholder="' . htmlspecialchars(t('attraction.search_hint'), ENT_QUOTES, 'UTF-8') . '"',
        '>Kategorie<select' => '>' . t('category.filter') . '<select', '>Alle Kategorien<' => '>' . t('category.all') . '<',
        '>Land<select' => '>' . t('attraction.country') . '<select', '>Alle Länder<' => '>' . t('attraction.all_countries') . '<',
        '>Noch keine eigenen Programmpunkte vorhanden.<' => '>' . t('custom_points.none') . '<', '>Kategorien: ' => '>' . t('attraction.categories') . ' ',
        '>Bearbeiten<' => '>' . t('common.edit') . '<', '>Löschen<' => '>' . t('common.delete') . '<',
        "confirm('Diesen Programmpunkt wirklich löschen?')" => 'confirm(' . tjs('custom_points.confirm_delete') . ')',
        '>Der Programmpunkt wurde gespeichert.<' => '>' . t('custom_points.saved') . '<', '>Der Programmpunkt wurde gelöscht.<' => '>' . t('custom_points.deleted') . '<',
    ]);
});
ob_start(static function (string $html): string {
    $notice = isset($_GET['saved']) ? t('custom_points.saved') : (isset($_GET['deleted']) ? t('custom_points.deleted') : '');
    return $notice === '' ? $html : str_replace('<div class="filters">', '<p class="success">' . htmlspecialchars($notice, ENT_QUOTES, 'UTF-8') . '</p><div class="filters">', $html);
});
$user=require_login();if(!in_array($user['role'],['main_admin','admin'],true)){http_response_code(403);exit(t('image.error_access'));}
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();$deleteId=filter_input(INPUT_POST,'id',FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);if($deleteId){$entryQuery=db()->prepare('SELECT id,image_path,created_by FROM '.table('custom_points').' WHERE id=:id');$entryQuery->execute([':id'=>$deleteId]);$entry=$entryQuery->fetch();if(!$entry){header('Location: /custom-points.php');exit;}if($user['role']!=='main_admin'&&(int)$entry['created_by']!==(int)$user['id']){http_response_code(403);exit(t('image.error_access'));}$pdo=db();try{$pdo->beginTransaction();$removePlanItems=$pdo->prepare('DELETE FROM '.table('trip_day_items')." WHERE item_type='catalog_custom' AND reference_id=:id");$removePlanItems->execute([':id'=>$deleteId]);$removeEntry=$pdo->prepare('DELETE FROM '.table('custom_points').' WHERE id=:id');$removeEntry->execute([':id'=>$deleteId]);$pdo->commit();$image=(string)($entry['image_path']??'');if($image!==''&&(str_starts_with($image,'uploads/')||str_starts_with($image,'storage/uploads/'))){@unlink(__DIR__.'/'.$image);}}catch(Throwable $exception){if($pdo->inTransaction()){$pdo->rollBack();}http_response_code(500);exit(t('custom_points.error_save'));}}header('Location: /custom-points.php?deleted=1');exit;}
$items=db()->query('SELECT id,name,short_description,city,country_code,image_path,status FROM '.table('custom_points').' ORDER BY name')->fetchAll();
foreach($items as &$item){$q=db()->prepare('SELECT c.name FROM '.table('custom_point_categories').' m JOIN '.table('categories').' c ON c.id=m.category_id WHERE m.custom_point_id=:id ORDER BY c.name');$q->execute([':id'=>$item['id']]);$item['category_names']=implode(' · ',array_column($q->fetchAll(),'name'));}unset($item);
?><!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Eigene Programmpunkte · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:900px;margin:auto}.button{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}.card{background:#fff;padding:18px;margin:10px 0;border-radius:12px;border:1px solid #d6e0e4;border-left:4px solid #75aeb9;box-shadow:0 3px 12px #0001}.muted{color:#59636d}.thumb{width:96px;height:70px;object-fit:contain;background:#e8eef0;border-radius:8px;float:right;margin-left:12px}.card form{margin-left:8px}.filters{display:flex;gap:12px;flex-wrap:wrap;margin:14px 0}.filters label{font-weight:700;flex:1;min-width:180px}.filters input,.filters select{box-sizing:border-box;width:100%;margin-top:5px;padding:10px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}@media(max-width:600px){body{padding:12px}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/dashboard.php">← Zurück</a><h1>Eigene Programmpunkte</h1><p class="muted">Wiederverwendbare Programmpunkte. Reisespezifische freie Punkte erscheinen hier nicht.</p><a class="button" href="/custom-point-edit.php">+ Neuer Programmpunkt</a><div class="filters"><label>Suche<input id="search" type="search" placeholder="Name oder Ort eingeben …"></label><label>Kategorie<select id="category"><option value="">Alle Kategorien</option><?php $categoryOptions=[];foreach($items as $row){foreach(explode(' · ',$row['category_names']) as $categoryName){if($categoryName!==''){$categoryOptions[$categoryName]=true;}}}foreach(array_keys($categoryOptions) as $categoryName): ?><option value="<?= htmlspecialchars($categoryName,ENT_QUOTES,'UTF-8') ?>"><?= htmlspecialchars($categoryName,ENT_QUOTES,'UTF-8') ?></option><?php endforeach; ?></select></label><label>Land<select id="country"><option value="">Alle Länder</option><?php foreach(triptale_countries() as $code=>$label):if($code!==''): ?><option value="<?= $code ?>"><?= htmlspecialchars($label,ENT_QUOTES,'UTF-8') ?></option><?php endif;endforeach; ?></select></label></div><?php if(!$items):?><section class="card"><p>Noch keine eigenen Programmpunkte vorhanden.</p></section><?php endif;?><?php foreach($items as$item):?><section class="card" data-search="<?= htmlspecialchars(strtolower($item['name'].' '.$item['city'].' '.$item['category_names']),ENT_QUOTES,'UTF-8') ?>" data-country="<?= htmlspecialchars($item['country_code']??'',ENT_QUOTES,'UTF-8') ?>" data-category="<?= htmlspecialchars($item['category_names'],ENT_QUOTES,'UTF-8') ?>"><strong><?= htmlspecialchars($item['name'],ENT_QUOTES,'UTF-8') ?></strong><?php if($item['image_path']): ?><img class="thumb" src="/<?= htmlspecialchars($item['image_path'],ENT_QUOTES,'UTF-8') ?>" alt=""><?php endif; ?><?php if($item['city']||($item['country_code']??'')!==''):?><p class="muted"><?= htmlspecialchars($item['city']??'',ENT_QUOTES,'UTF-8') ?><?= $item['city']&&$item['country_code']?' · ':'' ?><?= ($item['country_code']??'')!==''?htmlspecialchars(triptale_countries()[$item['country_code']]??$item['country_code'],ENT_QUOTES,'UTF-8'):'' ?></p><?php endif;?><?php if($item['category_names']):?><p class="muted">Kategorien: <?= htmlspecialchars($item['category_names'],ENT_QUOTES,'UTF-8') ?></p><?php endif;?><?php if($item['short_description']):?><p><?= htmlspecialchars($item['short_description'],ENT_QUOTES,'UTF-8') ?></p><?php endif;?><a class="button" href="/custom-point-edit.php?id=<?= (int)$item['id'] ?>">Bearbeiten</a><form method="post" style="display:inline" onsubmit="return confirm('Diesen Programmpunkt wirklich löschen?');"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8') ?>"><input type="hidden" name="id" value="<?= (int)$item['id'] ?>"><button class="button" style="background:#9d2d2d">Löschen</button></form></section><?php endforeach;?></main><script>const search=document.getElementById('search'),country=document.getElementById('country'),category=document.getElementById('category');function applyFilter(){document.querySelectorAll('.card[data-search]').forEach(card=>{card.hidden=!(card.dataset.search.includes(search.value.toLowerCase())&&(!country.value||card.dataset.country===country.value)&&(!category.value||card.dataset.category.split(' · ').includes(category.value)));});}search.addEventListener('input',applyFilter);country.addEventListener('change',applyFilter);category.addEventListener('change',applyFilter);</script></body></html>
