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

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

$message = '';

// ACTION : SUPPRESSION D'UN PARC
if (isset($_GET['delete_parc_id'])) {
    $id_to_delete = intval($_GET['delete_parc_id']);
    try {
        $stmt = $pdo->prepare("DELETE FROM parcs WHERE id = ?");
        $stmt->execute([$id_to_delete]);
        header("Location: addparks.php?success=2");
        exit;
    } catch (PDOException $e) {
        $message = "<div class='ap-alert ap-alert-danger'>Erreur : " . $e->getMessage() . "</div>";
    }
}

// ACTION : CRÉATION DU PARC
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_type']) && $_POST['action_type'] === 'create') {
    $nom_parc = trim($_POST['nom_parc'] ?? '');
    $pays = trim($_POST['pays'] ?? '');
    $gps = trim($_POST['gps'] ?? '');
    $site_web = trim($_POST['site_web'] ?? '');

    $latitude = null;
    $longitude = null;
    if (!empty($gps)) {
        $coords = explode(',', $gps);
        if (count($coords) === 2) {
            $latitude = trim($coords[0]);
            $longitude = trim($coords[1]);
        }
    }

    if (!empty($nom_parc) && !empty($pays) && $latitude !== null && $longitude !== null) {
        try {
            $pdo->beginTransaction();

            $stmtParc = $pdo->prepare("INSERT INTO parcs (nom, pays, latitude, longitude, site_web, cover_image, api_slug) VALUES (?, ?, ?, ?, ?, ?, '')");
            $stmtParc->execute([$nom_parc, $pays, $latitude, $longitude, $site_web, '']);
            $parc_id = $pdo->lastInsertId();

            if (isset($_POST['coasters']) && is_array($_POST['coasters'])) {
                foreach ($_POST['coasters'] as $coaster) {
                    $nom_attraction = trim($coaster['nom'] ?? '');
                    $annee = !empty($coaster['annee']) ? intval($coaster['annee']) : null;
                    $constructeur = trim($coaster['constructeur'] ?? '');
                    $hauteur = trim($coaster['hauteur'] ?? '');
                    $longueur = trim($coaster['longueur'] ?? '');
                    $vitesse = trim($coaster['vitesse'] ?? '');
                    $statut = trim($coaster['statut'] ?? 'Ouvert');

                    if (!empty($nom_attraction)) {
                        $stmtCoaster = $pdo->prepare("INSERT INTO coasters (parc_id, nom, annee_ouverture, constructeur, hauteur, longueur, vitesse, statut) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmtCoaster->execute([$parc_id, $nom_attraction, $annee, $constructeur, $hauteur, $longueur, $vitesse, $statut]);
                    }
                }
            }

            $pdo->commit();
            header("Location: addparks.php?success=1");
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = "<div class='ap-alert ap-alert-danger'>Erreur : " . $e->getMessage() . "</div>";
        }
    }
}

// SÉLECTION FILTRÉE : Uniquement les parcs créés ici, et décompte EXCLUSIF des coasters OUVERTS ou EN MAINTENANCE (Fermés exclus)
$query = "SELECT p.*, 
          (SELECT COUNT(*) FROM coasters WHERE parc_id = p.id AND statut != 'Fermé') as nb_coasters 
          FROM parcs p 
          WHERE p.pays IS NOT NULL AND p.pays != '' 
          ORDER BY p.nom ASC";
$parcs = $pdo->query($query)->fetchAll();

if (isset($_GET['success'])) {
    if ($_GET['success'] == 1) $message = "<div class='ap-alert ap-alert-success'>Le complexe touristique a été déployé avec succès !</div>";
    if ($_GET['success'] == 2) $message = "<div class='ap-alert ap-alert-success'>Le complexe a été supprimé de la base.</div>";
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Parcs | ParcoTrip 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/addparks.css">
</head>
<body>

    <!-- NAVBAR ADMIN CENTRALISÉE ET AUTONOME -->
    <?php include_once 'sidebaradmin.php'; ?>

    <main class="ap-container">
        
        <div class="ap-top-action-bar">
            <?php echo $message; ?>
            <button id="btnOpenForm" class="ap-btn-trigger-form"><i class="fa-solid fa-plus"></i> Créer un nouveau complexe</button>
        </div>

        <!-- MODAL MULTI-ETAPES -->
        <div id="formModal" class="ap-modal-overlay">
            <div class="ap-modal-content">
                <div class="ap-modal-header">
                    <h3>Nouvelle fiche de parc touristique</h3>
                    <button id="btnCloseForm" class="ap-btn-close-modal" type="button">&times;</button>
                </div>
                <form action="addparks.php" method="POST" id="multiStepForm">
                    <input type="hidden" name="action_type" value="create">
                    
                    <div class="ap-step-pane active-pane" id="step1">
                        <div class="ap-form-grid">
                            <div class="ap-field-group"><label>Nom du Parc *</label><input type="text" name="nom_parc" class="ap-input" required></div>
                            <div class="ap-field-group"><label>Pays *</label><input type="text" name="pays" class="ap-input" required></div>
                            <div class="ap-field-group"><label>GPS (Lat, Lng) *</label><input type="text" name="gps" class="ap-input" required placeholder="48.2661, 7.7219"></div>
                            <div class="ap-field-group"><label>Site Internet</label><input type="url" name="site_web" class="ap-input"></div>
                        </div>
                        <div class="ap-step-footer">
                            <button type="button" id="btnGoStep2" class="ap-btn-next">Suivant (Coasters) <i class="fa-solid fa-arrow-right"></i></button>
                        </div>
                    </div>

                    <div class="ap-step-pane" id="step2">
                        <div class="ap-step-header-flex">
                            <h5>Catalogue initial des attractions</h5>
                            <button type="button" id="btnAddCoasterField" class="ap-btn-add-item-sub"><i class="fa-solid fa-plus"></i> Un autre ride</button>
                        </div>
                        <div id="coastersDynamicContainer">
                            <div class="ap-coaster-block-card">
                                <div class="ap-form-grid-three">
                                    <div class="ap-field-group"><label>Nom *</label><input type="text" name="coasters[0][nom]" class="ap-input coaster-name-input"></div>
                                    <div class="ap-field-group"><label>Année</label><input type="number" name="coasters[0][annee]" class="ap-input"></div>
                                    <div class="ap-field-group"><label>Constructeur</label><input type="text" name="coasters[0][constructeur]" class="ap-input"></div>
                                    <div class="ap-field-group"><label>Hauteur</label><input type="text" name="coasters[0][hauteur]" class="ap-input"></div>
                                    <div class="ap-field-group"><label>Longueur</label><input type="text" name="coasters[0][longueur]" class="ap-input"></div>
                                    <div class="ap-field-group"><label>Vitesse</label><input type="text" name="coasters[0][vitesse]" class="ap-input"></div>
                                    <div class="ap-field-group">
                                        <label>Statut</label>
                                        <select name="coasters[0][statut]" class="ap-input">
                                            <option value="Ouvert">Ouvert</option>
                                            <option value="Fermé">Fermé (Exclu de la carte)</option>
                                            <option value="En Maintenance">En Maintenance</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="ap-step-footer">
                            <button type="button" id="btnBackStep1" class="ap-btn-back">Retour</button>
                            <button type="submit" class="ap-btn-submit-all">Enregistrer le complexe</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- LISTING DU DASHBOARD MODERNE -->
        <div class="ap-dashboard-list-container">
            <div class="ap-list-header">
                <h3>Parcs touristiques configurés</h3>
                <span class="ap-count-badge"><?= count($parcs) ?> parcs géolocalisés</span>
            </div>

            <div class="ap-grid-cards">
                <?php foreach ($parcs as $p): ?>
                    <div class="ap-park-card">
                        <div class="ap-card-main-info">
                            <h4><?= htmlspecialchars($p['nom']) ?></h4>
                            <div class="ap-card-meta">
                                <span><i class="fa-solid fa-earth-europe"></i> <?= htmlspecialchars($p['pays']) ?></span>
                                <span><i class="fa-solid fa-location-dot"></i> <code><?= htmlspecialchars($p['latitude'] . ',' . $p['longitude']) ?></code></span>
                                <span><i class="fa-solid fa-ticket"></i> <b><?= $p['nb_coasters'] ?></b> actif(s)</span>
                            </div>
                        </div>
                        
                        <div class="ap-card-actions-wrapper">
                            <a href="modifycoaster.php?parc_id=<?= $p['id'] ?>" class="ap-btn-card btn-manage-rides">
                                <i class="fa-solid fa-sliders"></i> Attractions
                            </a>
                            <a href="modifyparcs.php?edit_id=<?= $p['id'] ?>" class="ap-btn-card btn-edit-park">
                                <i class="fa-solid fa-pen"></i> Modifier
                            </a>
                            <a href="addparks.php?delete_parc_id=<?= $p['id'] ?>" class="ap-btn-card btn-delete-park" onclick="return confirm('Confirmer la suppression totale de ce parc ?');">
                                <i class="fa-solid fa-trash"></i>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

    </main>

    <footer class="main-footer" style="text-align: center; padding: 20px; color: #64748b; margin-top: 60px;">
        <p>&copy; 2026 ParcoTrip Administration.</p>
    </footer>

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