<?php
require_once '../session.php';
require_once '../db.php';

// Sécurité : Seul l'admin peut exécuter ce script
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'Administrateur') {
    echo json_encode(['success' => false, 'message' => 'Accès refusé.']);
    exit;
}

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $parkId = intval($_POST['park_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    if ($parkId <= 0) {
        echo json_encode(['success' => false, 'message' => 'ID du parc invalide.']);
        exit;
    }

    $targetDir = "../img/covers/";

    // --- ACTION 1 : TELEVERSEMENT DE L'IMAGE ---
    if ($action === 'upload' && isset($_FILES['cover_image'])) {
        $file = $_FILES['cover_image'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];

        if (!in_array($ext, $allowed)) {
            echo json_encode(['success' => false, 'message' => 'Format d\'image non valide (JPG, PNG, WEBP uniquement).']);
            exit;
        }

        // On renomme le fichier proprement avec son ID unique (ex: cover_parc_3.jpg)
        $newFilename = "cover_parc_" . $parkId . "." . $ext;
        
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }

        $targetPath = $targetDir . $newFilename;

        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            try {
                $stmt = $pdo->prepare("UPDATE parcs SET cover_image = ? WHERE id = ?");
                $stmt->execute([$newFilename, $parkId]);

                echo json_encode(['success' => true, 'filename' => $newFilename]);
                exit;
            } catch (PDOException $e) {
                echo json_encode(['success' => false, 'message' => 'Erreur BDD : ' . $e->getMessage()]);
                exit;
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Impossible de sauvegarder l\'image sur le serveur.']);
            exit;
        }
    }

    // --- ACTION 2 : SUPPRESSION DE L'IMAGE ---
    if ($action === 'delete') {
        try {
            // Récupérer le nom de l'ancien fichier pour le nettoyer du stockage XAMPP
            $stmt = $pdo->prepare("SELECT cover_image FROM parcs WHERE id = ?");
            $stmt->execute([$parkId]);
            $park = $stmt->fetch();

            if ($park && !empty($park['cover_image'])) {
                $filePath = $targetDir . $park['cover_image'];
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }

            $stmt = $pdo->prepare("UPDATE parcs SET cover_image = NULL WHERE id = ?");
            $stmt->execute([$parkId]);

            echo json_encode(['success' => true]);
            exit;
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => 'Erreur BDD : ' . $e->getMessage()]);
            exit;
        }
    }
}

echo json_encode(['success' => false, 'message' => 'Requête invalide.']);