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

$parc_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$user_id = $_SESSION['user_id'] ?? null;

// 1. TRAITEMENT DE L'AJOUT D'UN AVIS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_comment') {
    if (!$user_id) {
        header("Location: login.php");
        exit;
    }
    $comm = trim($_POST['commentaire'] ?? '');
    $nom_user = $_SESSION['nom'] ?? 'Anonyme';
    
    if (!empty($comm)) {
        $stmt = $pdo->prepare("INSERT INTO parc_avis (parc_id, user_id, nom_utilisateur, commentaire) VALUES (?, ?, ?, ?)");
        $stmt->execute([$parc_id, $user_id, $nom_user, $comm]);
        header("Location: parcview.php?id=$parc_id#community-section");
        exit;
    }
}

// 2. TRAITEMENT DU LIKE VIA PARAMÈTRE URL
if (isset($_GET['like_avis_id'])) {
    if (!$user_id) { header("Location: login.php"); exit; }
    $avis_id = intval($_GET['like_avis_id']);
    
    $chk = $pdo->prepare("SELECT id FROM avis_likes WHERE avis_id = ? AND user_id = ?");
    $chk->execute([$avis_id, $user_id]);
    if ($chk->fetch()) {
        $del = $pdo->prepare("DELETE FROM avis_likes WHERE avis_id = ? AND user_id = ?");
        $del->execute([$avis_id, $user_id]);
    } else {
        $ins = $pdo->prepare("INSERT INTO avis_likes (avis_id, user_id) VALUES (?, ?)");
        $ins->execute([$avis_id, $user_id]);
    }
    header("Location: parcview.php?id=$parc_id#community-section");
    exit;
}

// 3. RÉCUPÉRATION DU PARC ET DE SA MOYENNE D'ÉTOILES
$stmt = $pdo->prepare("SELECT p.*, COALESCE(AVG(n.note), 0) as moyenne_note, COUNT(n.id) as total_votes 
                       FROM parcs p 
                       LEFT JOIN parc_notes n ON p.id = n.parc_id 
                       WHERE p.id = ?");
$stmt->execute([$parc_id]);
$parc = $stmt->fetch();

if (!$parc || empty($parc['nom'])) {
    die("Erreur : Ce complexe n'existe pas.");
}

// Note attribuée par l'utilisateur connecté actuel (si existante)
$user_current_note = 0;
if ($user_id) {
    $stmtN = $pdo->prepare("SELECT note FROM parc_notes WHERE parc_id = ? AND user_id = ?");
    $stmtN->execute([$parc_id, $user_id]);
    $resN = $stmtN->fetch();
    if ($resN) $user_current_note = $resN['note'];
}

// 4. EXTRACTION DES ATTRACTIONS EN DEUX GROUPES (OUVERTS / FERMÉS)
$stmtC = $pdo->prepare("SELECT * FROM coasters WHERE parc_id = ? ORDER BY nom ASC");
$stmtC->execute([$parc_id]);
$all_coasters = $stmtC->fetchAll();

$coasters_ouverts = [];
$coasters_fermes = [];
foreach ($all_coasters as $c) {
    if ($c['statut'] === 'Fermé') {
        $coasters_fermes[] = $c;
    } else {
        $coasters_ouverts[] = $c;
    }
}

// 5. CHARGEMENT DES AVIS AVEC COMPTEUR DE LIKES
$stmtA = $pdo->prepare("SELECT a.*, 
                       (SELECT COUNT(*) FROM avis_likes WHERE avis_id = a.id) as likes_count,
                       (SELECT COUNT(*) FROM avis_likes WHERE avis_id = a.id AND user_id = ?) as user_has_liked
                       FROM parc_avis a WHERE a.parc_id = ? ORDER BY a.date_publication DESC");
$stmtA->execute([$user_id, $parc_id]);
$avis_liste = $stmtA->fetchAll();

$cover_path = !empty($parc['cover_image']) ? "img/covers/" . $parc['cover_image'] : "img/covers/default.jpg";
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($parc['nom']) ?> | ParcoTrip</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/parcview.css">
</head>
<body>

    <header class="navbar">
        <div class="logo"><a href="index.php">PARCO<span>TRIP</span></a></div>
        <nav>
            <ul class="nav-links">
                <li><a href="index.php">Accueil</a></li>
                <li><a href="waittimes.php">Temps d'attentes</a></li>
                <li><a href="map.php">Carte des parcs</a></li>
                <?php echo renderMemberButton(); ?>
            </ul>
        </nav>
    </header>

    <!-- BANDEAU HERO PREMIUM EN FULL BLUR DEGRADÉ -->
    <section class="pv-premium-hero" style="--bg-cover: url('../<?= $cover_path ?>');">
        <div class="pv-hero-overlay"></div>
        <div class="pv-hero-container">
            <div class="pv-hero-breadcrumbs">
                <a href="map.php">Carte</a> <i class="fa-solid fa-chevron-right"></i> <span>Détails complexe</span>
            </div>
            
            <div class="pv-hero-main-content">
                <div class="pv-hero-info-side">
                    <span class="pv-country-tag"><i class="fa-solid fa-earth-europe"></i> <?= htmlspecialchars($parc['pays']) ?></span>
                    <h1><?= htmlspecialchars($parc['nom']) ?></h1>
                    
                    <div class="pv-hero-meta-pills">
                        <span><i class="fa-solid fa-rocket text-primary"></i> <b><?= count($coasters_ouverts) ?></b> Attractions actives</span>
                        <?php if ($parc['site_web']): ?>
                            <a href="<?= htmlspecialchars($parc['site_web']) ?>" target="_blank" class="pv-btn-pill-web"><i class="fa-solid fa-link"></i> Site officiel</a>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- CARTE DE SCORING INTERACTIVE -->
                <div class="pv-hero-score-card">
                    <div class="pv-score-big-flex">
                        <div class="pv-score-number">
                            <span><?= number_format($parc['moyenne_note'], 1) ?></span>
                            <small>/ 5</small>
                        </div>
                        <div class="pv-score-stars-col">
                            <div class="pv-stars-interactive-line" data-parc-id="<?= $parc_id ?>" data-logged="<?= $user_id ? 'true' : 'false' ?>">
                                <?php for($i = 1; $i <= 5; $i++): ?>
                                    <i class="fa-star <?= $i <= round($parc['moyenne_note']) ? 'fa-solid is-active' : 'fa-regular' ?> pv-star-item" data-value="<?= $i ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <span class="pv-total-votes-label"><i class="fa-regular fa-comment-dots"></i> Base de <b><?= $parc['total_votes'] ?></b> avis</span>
                        </div>
                    </div>
                    <?php if($user_id && $user_current_note > 0): ?>
                        <div class="pv-user-vote-status-bar">
                            <i class="fa-solid fa-circle-check"></i> Votre évaluation : <strong><?= $user_current_note ?>/5</strong>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </section>

    <!-- CORPS DE PAGE EN DEUX COLONNES ASYMÉTRIQUES -->
    <main class="pv-main-layout">
        
        <!-- COLONNE GAUCHE : LES ATTRACTIONS (70% Largeur) -->
        <div class="pv-content-primary-column">
            
            <!-- CODE BLOC : ATTRACTIONS OPÉRATIONNELLES -->
            <div class="pv-dashboard-section-card">
                <div class="pv-section-header">
                    <div class="pv-header-title-wrapper">
                        <div class="pv-icon-container bg-success-light"><i class="fa-solid fa-bolt"></i></div>
                        <div>
                            <h3>Attractions opérationnelles</h3>
                            <p> Rollercoasters disponibles, ouverts ou en cours d'optimisation d'affluence.</p>
                        </div>
                    </div>
                    <span class="pv-counter-badge bg-success-p"><?= count($coasters_ouverts) ?></span>
                </div>

                <div class="pv-rides-grid-system">
                    <?php if(count($coasters_ouverts) > 0): ?>
                        <?php foreach($coasters_ouverts as $c): 
                            $stmtImg = $pdo->prepare("SELECT fichier_chemin FROM coaster_photos WHERE coaster_id = ? LIMIT 1");
                            $stmtImg->execute([$c['id']]);
                            $img = $stmtImg->fetch();
                            $src_img = $img ? "img/coasters/" . $img['fichier_chemin'] : "img/covers/default.jpg";
                        ?>
                            <div class="pv-ride-premium-card">
                                <div class="pv-ride-card-img-container">
                                    <img src="<?= $src_img ?>" alt="Photo Coaster" loading="lazy">
                                    <span class="pv-status-card-pill status-<?= strtolower(str_replace(' ', '-', $c['statut'])) ?>"><?= $c['statut'] ?></span>
                                </div>
                                <div class="pv-ride-card-details">
                                    <h4><?= htmlspecialchars($c['nom']) ?></h4>
                                    <div class="pv-ride-specs-row-pills">
                                        <?php if($c['constructeur']): ?><span><?= htmlspecialchars($c['constructeur']) ?></span><?php endif; ?>
                                        <?php if($c['annee_ouverture']): ?><span><i class="fa-regular fa-calendar"></i> <?= $c['annee_ouverture'] ?></span><?php endif; ?>
                                        <?php if($c['vitesse']): ?><span><i class="fa-solid fa-gauge-high"></i> <?= htmlspecialchars($c['vitesse']) ?> km/h</span><?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="pv-empty-state-box">
                            <i class="fa-regular fa-folder-open"></i>
                            <p>Aucun coaster opérationnel n'est répertorié sur ce complexe.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- CODE BLOC : ATTRACTIONS FERMÉES -->
            <?php if(count($coasters_fermes) > 0): ?>
                <div class="pv-dashboard-section-card margin-top-card">
                    <div class="pv-section-header">
                        <div class="pv-header-title-wrapper">
                            <div class="pv-icon-container bg-danger-light"><i class="fa-solid fa-triangle-exclamation"></i></div>
                            <div>
                                <h3>Attractions hors service / Fermées</h3>
                                <p>Rides actuellement indisponibles (maintenance saisonnière ou pannes techniques).</p>
                            </div>
                        </div>
                        <span class="pv-counter-badge bg-danger-p"><?= count($coasters_fermes) ?></span>
                    </div>

                    <div class="pv-rides-list-strip">
                        <?php foreach($coasters_fermes as $c): ?>
                            <div class="pv-ride-strip-item">
                                <div class="pv-strip-info">
                                    <h5><?= htmlspecialchars($c['nom']) ?></h5>
                                    <span><?= htmlspecialchars($c['constructeur'] ?: 'Constructeur non spécifié') ?></span>
                                </div>
                                <span class="pv-status-strip-pill"><i class="fa-solid fa-ban"></i> Indisponible</span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- COLONNE DROITE : ESPACE DISCUSSIONS & COMMUNITY (30% Largeur) -->
        <div class="pv-content-secondary-column" id="community-section">
            <div class="pv-community-sticky-card">
                <div class="pv-comm-card-header">
                    <h4><i class="fa-solid fa-comments text-primary"></i> Espace Communautaire</h4>
                    <p>Lisez et partagez les retours d'expériences en temps réel sur ce parc.</p>
                </div>

                <!-- Zone d'écriture d'avis -->
                <div class="pv-comm-writing-box">
                    <?php if ($user_id): ?>
                        <form action="parcview.php?id=<?= $parc_id ?>" method="POST" class="pv-modern-form">
                            <input type="hidden" name="action" value="add_comment">
                            <textarea name="commentaire" required placeholder="Affluence, astuces sur les files d'attentes... Laissez votre avis ici !" rows="3"></textarea>
                            <button type="submit" class="pv-btn-send-comment">Envoyer le retour <i class="fa-solid fa-paper-plane"></i></button>
                        </form>
                    <?php else: ?>
                        <div class="pv-card-locked-notice">
                            <p>Connectez-vous pour évaluer le parc et publier un avis.</p>
                            <a href="login.php" class="pv-btn-form-login">Se connecter</a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Liste des publications -->
                <div class="pv-comm-feed-wrapper">
                    <?php if(count($avis_liste) > 0): ?>
                        <?php foreach($avis_liste as $av): ?>
                            <div class="pv-feed-item-bubble">
                                <div class="pv-bubble-top">
                                    <div class="pv-bubble-user-info">
                                        <div class="pv-avatar-placeholder"><?= strtoupper(substr($av['nom_utilisateur'], 0, 1)) ?></div>
                                        <strong><?= htmlspecialchars($av['nom_utilisateur']) ?></strong>
                                    </div>
                                    <small><?= date('d/m/Y', strtotime($av['date_publication'])) ?></small>
                                </div>
                                <p class="pv-bubble-text"><?= nl2br(htmlspecialchars($av['commentaire'])) ?></p>
                                
                                <div class="pv-bubble-footer-actions">
                                    <a href="parcview.php?id=<?= $parc_id ?>&like_avis_id=<?= $av['id'] ?>" class="pv-action-like-pill <?= $av['user_has_liked'] ? 'liked-active' : '' ?>">
                                        <i class="fa-solid fa-thumbs-up"></i> <span><?= $av['likes_count'] ?></span> Utile
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="pv-empty-feed-state">
                            <i class="fa-regular fa-comments"></i>
                            <p>Aucun avis publié pour le moment. Soyez le premier à lancer la discussion !</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    </main>

    <script>
        const CURRENT_PARC_ID = <?= $parc_id ?>;
    </script>
    <script src="js/parcview.js"></script>
</body>
</html>