<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';
require_once __DIR__ . '/app/Helpers/note-images.php';
require_once __DIR__ . '/app/Helpers/comment-images.php';
$user=require_login();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit('Ungültige Anfrage.'); }
verify_csrf();
$tripId=filter_input(INPUT_POST,'trip_id',FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);
$action=(string)($_POST['action']??'');
if(!$tripId || !in_array($action,['archive','restore','delete'],true)){http_response_code(400);exit('Ungültige Anfrage.');}
$query=db()->prepare('SELECT id,created_by,image_path FROM '.table('trips').' WHERE id=:id');$query->execute([':id'=>$tripId]);$trip=$query->fetch();
if(!$trip){header('Location: /dashboard.php');exit;}
if($user['role']!=='main_admin' && (int)$trip['created_by']!==(int)$user['id']){http_response_code(403);exit('Kein Zugriff.');}
if($action==='archive'||$action==='restore'){
    $status=$action==='archive'?'archived':'active';
    $save=db()->prepare('UPDATE '.table('trips').' SET status=:status WHERE id=:id');$save->execute([':status'=>$status,':id'=>$tripId]);
    triptale_log_trip_change($tripId, (int)$user['id'], $action === 'archive' ? 'trip_archived' : 'trip_restored', $action === 'archive' ? 'Die Reise wurde archiviert.' : 'Die Reise wurde wieder aktiviert.');
    header('Location: /trip-edit.php?id='.$tripId.'&trip='.$action);exit;
}
$pdo=db();
$images=[(string)($trip['image_path']??'')];
try{
    foreach(note_images_for_trip($tripId) as $noteImage){$images[]=(string)$noteImage;}
    foreach(comment_images_for_trip($tripId) as $commentImage){$images[]=(string)$commentImage;}
    $imagesQuery=$pdo->prepare('SELECT i.image_path FROM '.table('trip_day_items').' i JOIN '.table('trip_days').' d ON d.id=i.trip_day_id WHERE d.trip_id=:id AND i.image_path IS NOT NULL');
    $imagesQuery->execute([':id'=>$tripId]); foreach($imagesQuery->fetchAll() as $row){$images[]=(string)$row['image_path'];}
    $pdo->beginTransaction();
    $remove=$pdo->prepare('DELETE FROM '.table('trips').' WHERE id=:id');$remove->execute([':id'=>$tripId]);
    $pdo->commit();
}catch(Throwable $exception){if($pdo->inTransaction()){$pdo->rollBack();}http_response_code(500);exit('Die Reise konnte nicht gelöscht werden.');}
foreach(array_unique($images) as $image){if($image!==''&&(str_starts_with($image,'uploads/')||str_starts_with($image,'storage/uploads/'))){@unlink(__DIR__.'/'.$image);}}
header('Location: /dashboard.php?trip=deleted');exit;
