<?php

declare(strict_types=1);

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db.php';

startSecureSession();

if (!isUserLoggedIn() || !isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: liste-souvenirs.php');
    exit;
}

if (!verifyCsrfToken($_POST['csrf_token'] ?? null)) {
    header('Location: liste-souvenirs.php?error=' . urlencode('Session invalide. Recharge la page et reessaie.'));
    exit;
}

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
    header('Location: liste-souvenirs.php?error=' . urlencode('Souvenir invalide.'));
    exit;
}

try {
    $pdo = getPdo();

    $selectStmt = $pdo->prepare('SELECT image FROM souvenirs WHERE id = :id AND user_id = :user_id LIMIT 1');
    $selectStmt->execute([
        'id' => $id,
        'user_id' => (int)$_SESSION['user_id'],
    ]);
    $souvenir = $selectStmt->fetch(PDO::FETCH_ASSOC);

    if (!$souvenir) {
        header('Location: liste-souvenirs.php?error=' . urlencode('Souvenir introuvable.'));
        exit;
    }

    $deleteStmt = $pdo->prepare('DELETE FROM souvenirs WHERE id = :id AND user_id = :user_id');
    $deleteStmt->execute([
        'id' => $id,
        'user_id' => (int)$_SESSION['user_id'],
    ]);

    if ($deleteStmt->rowCount() > 0) {
        $imagePath = (string)$souvenir['image'];
        $fileName = basename($imagePath);
        $absolutePath = __DIR__ . '/../../image/souvenirs/' . $fileName;
        if (is_file($absolutePath)) {
            @unlink($absolutePath);
        }

        header('Location: liste-souvenirs.php?success=' . urlencode('Souvenir supprime avec succes.'));
        exit;
    }

    header('Location: liste-souvenirs.php?error=' . urlencode('Impossible de supprimer ce souvenir.'));
    exit;
} catch (Throwable $e) {
    header('Location: liste-souvenirs.php?error=' . urlencode('Erreur serveur pendant la suppression.'));
    exit;
}
