<?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;
$nom = trim((string)($_POST['nom'] ?? ''));
$description = trim((string)($_POST['description'] ?? ''));
$visibility = strtolower(trim((string)($_POST['visibility'] ?? 'private')));

if (!in_array($visibility, ['private', 'public'], true)) {
    $visibility = 'private';
}

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

if ($nom === '' || $description === '') {
    header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Tous les champs obligatoires doivent etre remplis.'));
    exit;
}

$nomLength = function_exists('mb_strlen') ? mb_strlen($nom) : strlen($nom);
if ($nomLength > 120) {
    header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Le nom du souvenir est trop long.'));
    exit;
}

try {
    $pdo = getPdo();

    $columnStmt = $pdo->query("SHOW COLUMNS FROM souvenirs LIKE 'visibility'");
    $visibilityColumn = $columnStmt ? $columnStmt->fetch(PDO::FETCH_ASSOC) : false;
    if (!$visibilityColumn) {
        $pdo->exec("ALTER TABLE souvenirs ADD COLUMN visibility ENUM('private', 'public') NOT NULL DEFAULT 'private' AFTER image");
    }

    $stmt = $pdo->prepare('SELECT id, image FROM souvenirs WHERE id = :id AND user_id = :user_id LIMIT 1');
    $stmt->execute([
        'id' => $id,
        'user_id' => (int)$_SESSION['user_id'],
    ]);
    $souvenir = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    header('Location: liste-souvenirs.php?error=' . urlencode('Impossible de charger le souvenir.'));
    exit;
}

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

$newImagePath = (string)$souvenir['image'];
$oldImagePath = (string)$souvenir['image'];
$uploadedNewImage = false;

if (isset($_FILES['image']) && is_array($_FILES['image']) && (int)($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
    $image = $_FILES['image'];

    if (($image['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Erreur lors de l\'upload de l\'image.'));
        exit;
    }

    $tmpPath = (string)($image['tmp_name'] ?? '');
    if ($tmpPath === '' || !is_uploaded_file($tmpPath)) {
        header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Fichier image invalide.'));
        exit;
    }

    $allowedMimes = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'image/gif' => 'gif',
    ];

    $mime = '';
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        if ($finfo) {
            $mime = (string)finfo_file($finfo, $tmpPath);
            finfo_close($finfo);
        }
    }

    if ($mime === '' && function_exists('getimagesize')) {
        $imageInfo = @getimagesize($tmpPath);
        if (is_array($imageInfo) && isset($imageInfo['mime']) && is_string($imageInfo['mime'])) {
            $mime = $imageInfo['mime'];
        }
    }

    if (!isset($allowedMimes[$mime])) {
        header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Format image non autorise.'));
        exit;
    }

    $uploadDir = __DIR__ . '/../../image/souvenirs';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
        header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Impossible de creer le dossier d\'upload.'));
        exit;
    }

    $extension = $allowedMimes[$mime];
    $fileName = 'souvenir_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
    $destination = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

    if (!move_uploaded_file($tmpPath, $destination)) {
        header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Impossible d\'enregistrer la nouvelle image.'));
        exit;
    }

    $newImagePath = '../../image/souvenirs/' . $fileName;
    $uploadedNewImage = true;
}

try {
    $updateStmt = $pdo->prepare(
        'UPDATE souvenirs SET nom = :nom, description = :description, image = :image, visibility = :visibility WHERE id = :id AND user_id = :user_id'
    );
    $updateStmt->execute([
        'nom' => $nom,
        'description' => $description,
        'image' => $newImagePath,
        'visibility' => $visibility,
        'id' => $id,
        'user_id' => (int)$_SESSION['user_id'],
    ]);
} catch (Throwable $e) {
    header('Location: modifier-souvenir.php?id=' . $id . '&error=' . urlencode('Erreur serveur pendant la modification.'));
    exit;
}

if ($uploadedNewImage) {
    $oldName = basename($oldImagePath);
    $oldAbsolute = __DIR__ . '/../../image/souvenirs/' . $oldName;
    if (is_file($oldAbsolute)) {
        @unlink($oldAbsolute);
    }
}

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