<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
$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') { http_response_code(405); exit(t('attraction.error_status')); }
verify_csrf();
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, ['options'=>['min_range'=>1]]);
$type = (string)($_POST['type'] ?? '');
$types = ['attraction'=>['table'=>'attractions','back'=>'/attractions.php'],'accommodation'=>['table'=>'accommodations','back'=>'/catalog.php?type=accommodation'],'restaurant'=>['table'=>'restaurants','back'=>'/catalog.php?type=restaurant']];
if (!$id || !isset($types[$type])) { http_response_code(400); exit(t('attraction.error_status')); }
$meta = $types[$type];
$entryQuery = db()->prepare('SELECT id, image_path, created_by FROM '.table($meta['table']).' WHERE id=:id');
$entryQuery->execute([':id'=>$id]); $entry=$entryQuery->fetch();
if (!$entry) { header('Location: '.$meta['back']); 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=:type AND reference_id=:id');
    $removePlanItems->execute([':type'=>$type,':id'=>$id]);
    $removeEntry=$pdo->prepare('DELETE FROM '.table($meta['table']).' WHERE id=:id');
    $removeEntry->execute([':id'=>$id]);
    $pdo->commit();
} catch (Throwable $exception) { if ($pdo->inTransaction()) { $pdo->rollBack(); } http_response_code(500); exit(t('attraction.error_save')); }
$image=(string)($entry['image_path'] ?? '');
if ($image !== '' && (str_starts_with($image,'uploads/') || str_starts_with($image,'storage/uploads/'))) { @unlink(__DIR__.'/'.$image); }
header('Location: ' . $meta['back'] . (str_contains($meta['back'], '?') ? '&' : '?') . 'deleted=1'); exit;
