<?php

declare(strict_types=1);

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

startSecureSession();

if (!isUserLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

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

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

$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 ($nom === '' || $description === '') {
    header('Location: ajout-souvenir.php?error=' . urlencode('Tous les champs sont obligatoires.'));
    exit;
}

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

if (!isset($_FILES['image']) || !is_array($_FILES['image'])) {
    header('Location: ajout-souvenir.php?error=' . urlencode('Aucune image envoyee.'));
    exit;
}

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

$tmpPath = (string)($image['tmp_name'] ?? '');
if ($tmpPath === '' || !is_uploaded_file($tmpPath)) {
    header('Location: ajout-souvenir.php?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);
    }
}

// 🎀 Fallback si l'extension fileinfo n'est pas active 🎀
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: ajout-souvenir.php?error=' . urlencode('Format image non autorise.'));
    exit;
}

$uploadDir = __DIR__ . '/../../image/souvenirs';
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
    header('Location: ajout-souvenir.php?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;
$relativeImagePath = '../../image/souvenirs/' . $fileName;

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

try {
    $pdo = getPdo();

    // 🎀 Creation de la table souvenirs si elle n'existe pas encore 🎀
    $pdo->exec(
        "CREATE TABLE IF NOT EXISTS souvenirs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            nom VARCHAR(120) NOT NULL,
            description TEXT NOT NULL,
            image VARCHAR(255) NOT NULL,
            visibility ENUM('private', 'public') NOT NULL DEFAULT 'private',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_souvenirs_user (user_id),
            CONSTRAINT fk_souvenirs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );

    $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(
        'INSERT INTO souvenirs (user_id, nom, description, image, visibility) VALUES (:user_id, :nom, :description, :image, :visibility)'
    );

    $stmt->execute([
        'user_id' => (int)$_SESSION['user_id'],
        'nom' => $nom,
        'description' => $description,
        'image' => $relativeImagePath,
        'visibility' => $visibility,
    ]);

    header('Location: liste-souvenirs.php?added=1');
    exit;
} catch (Throwable $e) {
    header('Location: ajout-souvenir.php?error=' . urlencode('Erreur serveur pendant l\'enregistrement du souvenir.'));
    exit;
}
