<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/categories.php';
$user=require_login(); if(!in_array($user['role'],['main_admin','admin'],true)){http_response_code(403);exit(t('image.error_access'));}
$types=['attraction'=>t('dashboard.attractions'),'accommodation'=>t('dashboard.accommodations'),'restaurant'=>t('dashboard.food_drink'),'custom'=>t('dashboard.custom_points')];
$type=(string)($_GET['type']??'attraction');if(!isset($types[$type])){$type='attraction';}$error='';$notice='';
function category_slug(string $name):string{return strtolower(trim((string)preg_replace('/[^a-z0-9]+/i','-',$name),'-'))?:'category';}
function category_back(string $type,string $flag):void{header('Location: /categories.php?type='.urlencode($type).'&'.$flag.'=1');exit;}
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();$postType=(string)($_POST['type']??'');$action=(string)($_POST['action']??'');$id=(int)($_POST['id']??0);if(!isset($types[$postType])){$error=t('category.error_invalid');}elseif($action==='save'){$name=trim((string)($_POST['name']??''));if($name===''){$error=t('category.error_name');}else{try{$language=language();$existing=db()->prepare('SELECT c.id FROM '.table('categories').' c INNER JOIN '.table('category_translations').' ct ON ct.category_id=c.id WHERE c.type=:type AND ct.language_code=:language AND ct.name=:name'.($id?' AND c.id<>:id':'').' LIMIT 1');$params=[':type'=>$postType,':language'=>$language,':name'=>$name];if($id){$params[':id']=$id;}$existing->execute($params);if($existing->fetchColumn()){throw new RuntimeException('duplicate');}if($id){$q=db()->prepare('UPDATE '.table('categories').' SET name=:name,slug=:slug WHERE id=:id AND type=:type');$q->execute([':name'=>$name,':slug'=>category_slug($name),':id'=>$id,':type'=>$postType]);}else{$q=db()->prepare('INSERT INTO '.table('categories').' (name,slug,type) VALUES (:name,:slug,:type)');$q->execute([':name'=>$name,':slug'=>category_slug($name),':type'=>$postType]);$id=(int)db()->lastInsertId();$_POST['translation_'.$language]=$name;}triptale_save_category_translations($id,$_POST);category_back($postType,'saved');}catch(Throwable $e){$error=t('category.error_duplicate');}}}elseif($action==='delete'&&$id){try{db()->beginTransaction();foreach(['attraction_categories','accommodation_categories','restaurant_categories','trip_day_item_categories','custom_point_categories']as$map){try{db()->prepare('DELETE FROM '.table($map).' WHERE category_id=:id')->execute([':id'=>$id]);}catch(Throwable $ignored){}}db()->prepare('DELETE FROM '.table('categories').' WHERE id=:id AND type=:type')->execute([':id'=>$id,':type'=>$postType]);db()->commit();category_back($postType,'deleted');}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();$error=t('category.error_delete');}}}
if(isset($_GET['saved']))$notice=t('category.saved');if(isset($_GET['deleted']))$notice=t('category.deleted');$q=db()->prepare('SELECT id,name FROM '.table('categories').' WHERE type=:type ORDER BY sort_order,name');$q->execute([':type'=>$type]);$items=$q->fetchAll();
?><!doctype html><html lang="<?=htmlspecialchars(language(),ENT_QUOTES,'UTF-8')?>"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?=htmlspecialchars(t('category.title'),ENT_QUOTES,'UTF-8')?> · TripTale</title><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:800px;margin:auto;background:#fff;padding:28px;border-radius:14px}.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}.delete{background:#9d2d2d}.tabs,.actions{display:flex;gap:8px;flex-wrap:wrap;margin:18px 0}.tabs a{padding:8px 10px;border-radius:7px;background:#edf2f3;color:#126e82;text-decoration:none;font-weight:700}.tabs a.active{background:#126e82;color:#fff}label{display:block;font-weight:600;margin-top:12px}input{box-sizing:border-box;width:100%;padding:10px;margin-top:5px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.row{padding:18px 0;border-top:1px solid #dbe1e5}.notice{background:#e6f5e9;padding:12px;border-radius:7px}.error{background:#ffe6e3;padding:12px;border-radius:7px}@media(max-width:600px){body{padding:12px}main{padding:16px}}</style></head><body><main><a class="button back" href="/dashboard.php"><?=htmlspecialchars(t('users.back'),ENT_QUOTES,'UTF-8')?></a><h1><?=htmlspecialchars(t('category.title'),ENT_QUOTES,'UTF-8')?></h1><p><?=htmlspecialchars(t('category.intro'),ENT_QUOTES,'UTF-8')?></p><nav class="tabs"><?php foreach($types as$key=>$label):?><a class="<?=$key===$type?'active':''?>" href="/categories.php?type=<?=$key?>"><?=htmlspecialchars($label,ENT_QUOTES,'UTF-8')?></a><?php endforeach;?></nav><?php if($error):?><p class="error"><?=htmlspecialchars($error,ENT_QUOTES,'UTF-8')?></p><?php endif;?><?php if($notice):?><p class="notice"><?=htmlspecialchars($notice,ENT_QUOTES,'UTF-8')?></p><?php endif;?><h2><?=htmlspecialchars(t('category.new'),ENT_QUOTES,'UTF-8')?></h2><form method="post"><input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8')?>"><input type="hidden" name="action" value="save"><input type="hidden" name="type" value="<?=$type?>"><label><?=htmlspecialchars(t('category.name'),ENT_QUOTES,'UTF-8')?><input required name="name" placeholder="<?=htmlspecialchars(t('category.placeholder'),ENT_QUOTES,'UTF-8')?>"></label><button class="save" type="submit"><?=htmlspecialchars(t('category.add'),ENT_QUOTES,'UTF-8')?></button></form><h2><?=htmlspecialchars($types[$type],ENT_QUOTES,'UTF-8')?></h2><?php if(!$items):?><p><?=htmlspecialchars(t('category.none'),ENT_QUOTES,'UTF-8')?></p><?php endif;?><?php foreach($items as$item):?><section class="row"><form method="post"><input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8')?>"><input type="hidden" name="action" value="save"><input type="hidden" name="type" value="<?=$type?>"><input type="hidden" name="id" value="<?=(int)$item['id']?>"><label><?=htmlspecialchars(t('category.name'),ENT_QUOTES,'UTF-8')?><input required name="name" value="<?=htmlspecialchars($item['name'],ENT_QUOTES,'UTF-8')?>"></label><div class="actions"><button class="save" type="submit"><?=htmlspecialchars(t('common.save'),ENT_QUOTES,'UTF-8')?></button><a class="button" href="/category-translations.php?type=<?=$type?>&id=<?=(int)$item['id']?>"><?=htmlspecialchars(t('category.translate'),ENT_QUOTES,'UTF-8')?></a></div></form><form method="post" onsubmit="return confirm(<?=json_encode(t('category.confirm_delete'),JSON_UNESCAPED_UNICODE)?>)"><input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8')?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="type" value="<?=$type?>"><input type="hidden" name="id" value="<?=(int)$item['id']?>"><button class="button delete" type="submit"><?=htmlspecialchars(t('common.delete'),ENT_QUOTES,'UTF-8')?></button></form></section><?php endforeach;?></main></body></html>
