<?php
session_start();
require_once '../db.php';

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

$parc_id = isset($_GET['parc_id']) ? intval($_GET['parc_id']) : 0;

$stmt = $pdo->prepare("SELECT * FROM parcs WHERE id = ?");
$stmt->execute([$parc_id]);
$parc = $stmt->fetch();

if (!$parc) {
    die("Erreur : Complexe introuvable.");
}

// 1. DÉFINIR UNE IMAGE COMME PREMIER PLAN (IMAGE PRINCIPALE)
if (isset($_GET['set_main_photo_id']) && isset($_GET['coaster_id'])) {
    $photo_id = intval($_GET['set_main_photo_id']);
    $coaster_id = intval($_GET['coaster_id']);
    
    // Étape A : On remet toutes les photos de ce coaster à 0 (normal)
    $reset = $pdo->prepare("UPDATE coaster_photos SET is_main = 0 WHERE coaster_id = ?");
    $reset->execute([$coaster_id]);
    
    // Étape B : On passe la photo sélectionnée à 1 (premier plan)
    $setMain = $pdo->prepare("UPDATE coaster_photos SET is_main = 1 WHERE id = ?");
    $setMain->execute([$photo_id]);
    
    header("Location: modifycoaster.php?parc_id=$parc_id");
    exit;
}

// 2. SUPPRESSION D'UNE PHOTO INDIVIDUELLE
if (isset($_GET['delete_photo_id'])) {
    $photo_id = intval($_GET['delete_photo_id']);
    
    $stmtPhoto = $pdo->prepare("SELECT * FROM coaster_photos WHERE id = ?");
    $stmtPhoto->execute([$photo_id]);
    $photo = $stmtPhoto->fetch();
    
    if ($photo) {
        $chemin_physique = "../img/coasters/" . $photo['fichier_chemin'];
        if (file_exists($chemin_physique)) {
            @unlink($chemin_physique);
        }
        $stmtDelete = $pdo->prepare("DELETE FROM coaster_photos WHERE id = ?");
        $stmtDelete->execute([$photo_id]);
    }
    header("Location: modifycoaster.php?parc_id=$parc_id");
    exit;
}

// 3. SUPPRESSION GLOBALE D'UN RIDE
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    
    $stmtPhotos = $pdo->prepare("SELECT * FROM coaster_photos WHERE coaster_id = ?");
    $stmtPhotos->execute([$delete_id]);
    foreach ($stmtPhotos->fetchAll() as $p) {
        if (file_exists("../img/coasters/" . $p['fichier_chemin'])) {
            @unlink("../img/coasters/" . $p['fichier_chemin']);
        }
    }
    
    $stmt = $pdo->prepare("DELETE FROM coasters WHERE id = ? AND parc_id = ?");
    $stmt->execute([$delete_id, $parc_id]);
    header("Location: modifycoaster.php?parc_id=$parc_id&success=2");
    exit;
}

// 4. ENREGISTREMENT / CONFIGURATION (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save') {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $nom = trim($_POST['nom'] ?? '');
        $annee = !empty($_POST['annee_ouverture']) ? intval($_POST['annee_ouverture']) : null;
        $constructeur = trim($_POST['constructeur'] ?? '');
        $hauteur = trim($_POST['hauteur'] ?? '');
        $longueur = trim($_POST['longueur'] ?? '');
        $vitesse = trim($_POST['vitesse'] ?? '');
        $statut = trim($_POST['statut'] ?? 'Ouvert');

        if (!empty($nom)) {
            if ($id > 0) {
                $stmt = $pdo->prepare("UPDATE coasters SET nom = ?, annee_ouverture = ?, constructeur = ?, hauteur = ?, longueur = ?, vitesse = ?, statut = ? WHERE id = ? AND parc_id = ?");
                $stmt->execute([$nom, $annee, $constructeur, $hauteur, $longueur, $vitesse, $statut, $id, $parc_id]);
                $coaster_id = $id;
            } else {
                $stmt = $pdo->prepare("INSERT INTO coasters (parc_id, nom, annee_ouverture, constructeur, hauteur, longueur, vitesse, statut) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$parc_id, $nom, $annee, $constructeur, $hauteur, $longueur, $vitesse, $statut]);
                $coaster_id = $pdo->lastInsertId();
            }

            // ENVOI DES PHOTOS DES ATTRACTIONS
            if (isset($_FILES['photos']) && !empty($_FILES['photos']['name'][0])) {
                $dossier_cible = "../img/coasters/";
                if (!is_dir($dossier_cible)) {
                    mkdir($dossier_cible, 0777, true);
                }

                foreach ($_FILES['photos']['tmp_name'] as $index => $tmp_name) {
                    if ($_FILES['photos']['error'][$index] === UPLOAD_ERR_OK) {
                        $nom_original = $_FILES['photos']['name'][$index];
                        $ext = strtolower(pathinfo($nom_original, PATHINFO_EXTENSION));
                        
                        if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
                            $nom_fichier_unique = "coaster_" . $coaster_id . "_" . uniqid() . "." . $ext;
                            
                            if (move_uploaded_file($tmp_name, $dossier_cible . $nom_fichier_unique)) {
                                // On vérifie si le coaster a déjà une image principale, sinon la première chargée le devient
                                $chkMain = $pdo->prepare("SELECT id FROM coaster_photos WHERE coaster_id = ? AND is_main = 1");
                                $chkMain->execute([$coaster_id]);
                                $has_main = $chkMain->fetch() ? 0 : 1;

                                $stmtImg = $pdo->prepare("INSERT INTO coaster_photos (coaster_id, fichier_chemin, is_main) VALUES (?, ?, ?)");
                                $stmtImg->execute([$coaster_id, $nom_fichier_unique, $has_main]);
                            }
                        }
                    }
                }
            }

            header("Location: modifycoaster.php?parc_id=$parc_id&success=1");
            exit;
        }
    }
}

$stmt = $pdo->prepare("SELECT * FROM coasters WHERE parc_id = ? ORDER BY nom ASC");
$stmt->execute([$parc_id]);
$coasters = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Catalogue <?= htmlspecialchars($parc['nom']) ?> | Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="css/modifycoaster.css">
</head>
<body>

    <header class="navbar">
        <div class="logo"><a href="index.php">PARCO<span>TRIP</span> <small>ADMIN</small></a></div>
        <nav>
            <ul class="nav-links">
                <li><a href="addparks.php"><i class="fa-solid fa-arrow-left"></i> Retour aux parcs</a></li>
            </ul>
        </nav>
    </header>

    <main class="mc-container">
        <div class="mc-page-header">
            <div>
                <span class="mc-subtitle">Gestion et Galeries d'attractions</span>
                <h2><?= htmlspecialchars($parc['nom']) ?></h2>
            </div>
            <button class="mc-btn-add" id="btnNewCoaster"><i class="fa-solid fa-plus"></i> Ajouter une attraction</button>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="mc-success-alert">Mise à jour du catalogue effectuée !</div>
        <?php endif; ?>

        <div class="mc-grid-coasters">
            <?php foreach ($coasters as $c): 
                $stmtP = $pdo->prepare("SELECT * FROM coaster_photos WHERE coaster_id = ? ORDER BY is_main DESC, id ASC");
                $stmtP->execute([$c['id']]);
                $photos_coaster = $stmtP->fetchAll();
            ?>
                <div class="mc-coaster-card <?= strtolower(str_replace(' ', '-', $c['statut'])) ?>">
                    <div class="mc-card-head">
                        <h3><?= htmlspecialchars($c['nom']) ?></h3>
                        <span class="mc-status-badge status-<?= strtolower(str_replace(' ', '-', $c['statut'])) ?>"><?= htmlspecialchars($c['statut']) ?></span>
                    </div>

                    <!-- GALERIE DE GESTION DES PHOTOS + PREMIER PLAN -->
                    <div class="mc-extended-gallery">
                        <?php if (count($photos_coaster) > 0): ?>
                            <?php foreach ($photos_coaster as $ph): ?>
                                <div class="mc-gallery-wrapper-box <?= $ph['is_main'] ? 'is-main-featured' : '' ?>">
                                    <div class="mc-gallery-thumb-container">
                                        <img src="../img/coasters/<?= htmlspecialchars($ph['fichier_chemin']) ?>" alt="Ride img">
                                        <a href="modifycoaster.php?parc_id=<?= $parc_id ?>&delete_photo_id=<?= $ph['id'] ?>" class="mc-delete-photo-link" onclick="return confirm('Supprimer cette photo ?');">&times;</a>
                                    </div>
                                    
                                    <!-- Sélecteur de premier plan -->
                                    <div class="mc-gallery-actions-bar">
                                        <?php if ($ph['is_main']): ?>
                                            <span class="mc-badge-main-display"><i class="fa-solid fa-star"></i> Premier Plan</span>
                                        <?php else: ?>
                                            <a href="modifycoaster.php?parc_id=<?= $parc_id ?>&set_main_photo_id=<?= $ph['id'] ?>&coaster_id=<?= $c['id'] ?>" class="mc-link-set-main" title="Mettre en premier plan sur le site">
                                                <i class="fa-regular fa-image"></i> Activer
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span class="mc-no-photo-label"><i class="fa-regular fa-image"></i> Aucune photo</span>
                        <?php endif; ?>
                    </div>

                    <div class="mc-card-specs">
                        <div><span>Constructeur:</span> <strong><?= htmlspecialchars($c['constructeur'] ?: '-') ?></strong></div>
                        <div><span>Année:</span> <strong><?= htmlspecialchars($c['annee_ouverture'] ?: '-') ?></strong></div>
                        <div><span>Spécifications:</span> <strong><?= htmlspecialchars($c['hauteur'] ?: '-') ?>m / <?= htmlspecialchars($c['vitesse'] ?: '-') ?> km/h</strong></div>
                    </div>
                    <div class="mc-card-actions">
                        <button class="mc-btn-edit btnEditClass" data-json='<?= json_encode($c) ?>'><i class="fa-solid fa-pen-to-square"></i> Éditer / Photos</button>
                        <a href="modifycoaster.php?parc_id=<?= $parc_id ?>&delete_id=<?= $c['id'] ?>" class="mc-btn-delete" onclick="return confirm('Supprimer ce ride ?');"><i class="fa-solid fa-trash-can"></i></a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- MODAL AVEC APPORT MULTIPLE -->
        <div class="mc-modal" id="coasterModal">
            <div class="mc-modal-box">
                <div class="mc-modal-header">
                    <h3 id="modalTitle">Ajouter un ride</h3>
                    <button class="mc-close" id="btnCloseModal">&times;</button>
                </div>
                <form action="modifycoaster.php?parc_id=<?= $parc_id ?>" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" id="field_id" value="">
                    
                    <div class="mc-form-grid">
                        <div class="mc-group" style="grid-column: span 2;"><label>Nom de l'attraction *</label><input type="text" name="nom" id="field_nom" required class="mc-input"></div>
                        <div class="mc-group"><label>Année d'ouverture</label><input type="number" name="annee_ouverture" id="field_annee" class="mc-input"></div>
                        <div class="mc-group"><label>Constructeur</label><input type="text" name="constructeur" id="field_constructeur" class="mc-input"></div>
                        <div class="mc-group"><label>Hauteur (m)</label><input type="text" name="hauteur" id="field_hauteur" class="mc-input"></div>
                        <div class="mc-group"><label>Longueur (m)</label><input type="text" name="longueur" id="field_longueur" class="mc-input"></div>
                        <div class="mc-group"><label>Vitesse (km/h)</label><input type="text" name="vitesse" id="field_vitesse" class="mc-input"></div>
                        <div class="mc-group"><label>Statut opérationnel</label>
                            <select name="statut" id="field_statut" class="mc-input">
                                <option value="Ouvert">Ouvert</option>
                                <option value="Fermé">Fermé (Exclu des compteurs)</option>
                                <option value="En Maintenance">En Maintenance</option>
                            </select>
                        </div>
                        
                        <div class="mc-group" style="grid-column: span 2; margin-top: 8px;">
                            <label style="color:#4a51ff;"><i class="fa-solid fa-images"></i> Ajouter des photos</label>
                            <input type="file" name="photos[]" multiple class="mc-input" accept="image/*" style="padding:8px;">
                        </div>
                    </div>
                    <button type="submit" class="mc-btn-submit">Sauvegarder les données</button>
                </form>
            </div>
        </div>

    </main>

    <script src="js/modifycoaster.js"></script>
</body>
</html>