<?php
if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($pdo)) { require_once __DIR__ . '/config.php'; }
if (!function_exists('isAdmin')) { require_once __DIR__ . '/functions.php'; }

// Vérifier si mineur
$isMinor = false;
if ($isLoggedIn && isset($currentUser['is_minor'])) {
    $isMinor = (bool)$currentUser['is_minor'];
} elseif ($isLoggedIn && !empty($currentUser['birthdate'])) {
    $birth = new DateTime($currentUser['birthdate']);
    $age   = (new DateTime())->diff($birth)->y;
    $isMinor = ($age < 18);
}

// Charger le thème — thème perso Premium+ en priorité
$siteTheme = [];
try {
    // Premium+ avec thème perso ?
    if ($isLoggedIn && in_array($currentUser['tier']??'', ['premium_plus']) && !empty($currentUser['theme_id'])) {
        $ts = $pdo->prepare("SELECT * FROM site_appearance WHERE id=? AND is_active=1");
        $ts->execute([$currentUser['theme_id']]);
        $siteTheme = $ts->fetch() ?: [];
    }
    // Sinon thème par défaut
    if (empty($siteTheme)) {
        $td = $pdo->query("SELECT * FROM site_appearance WHERE is_default=1 LIMIT 1");
        $siteTheme = ($td && $td->rowCount()) ? $td->fetch() : [];
    }
    if (empty($siteTheme)) {
        $tf = $pdo->query("SELECT * FROM site_appearance LIMIT 1");
        $siteTheme = $tf ? ($tf->fetch() ?: []) : [];
    }
} catch (Exception $e) { $siteTheme = []; }
$themeBg      = $siteTheme['bg_color']      ?? '#0a0a0a';
$themeCard    = $siteTheme['card_bg']        ?? '#1a1a2e';
$themePrimary = $siteTheme['primary_color']  ?? '#0d6efd';
$themeAccent  = $siteTheme['accent_color']   ?? '#0dcaf0';
$themeText    = $siteTheme['text_color']     ?? '#e0e0e0';
$themeBorder  = $siteTheme['border_color']   ?? '#333333';
$themeFont    = $siteTheme['font_family']    ?? 'Orbitron';

// Charger wallet_points
$walletPoints = 0;
try {
    if (isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0) {
        $wpStmt = $pdo->prepare("SELECT wallet_points FROM users WHERE id=?");
        $wpStmt->execute([$_SESSION['user_id']]);
        $walletPoints = (int)($wpStmt->fetchColumn() ?? 0);
    }
} catch (Exception $e) {}

// Photo de fond personnelle (Premium+)
$userBgImage = '';
if (isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0) {
    try {
        $bgStmt = $pdo->prepare("SELECT profile_bg_image FROM users WHERE id = ?");
        $bgStmt->execute([$_SESSION['user_id']]);
        $bgRow = $bgStmt->fetchColumn();
        if ($bgRow && is_string($bgRow) && strlen($bgRow) > 0) {
            $fullPath = __DIR__ . DIRECTORY_SEPARATOR . ltrim($bgRow, '/\\');
            if (@file_exists($fullPath)) {
                $userBgImage = htmlspecialchars($bgRow);
            }
        }
    } catch (Exception $e) { $userBgImage = ''; }
}

$isLoggedIn   = (isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0) 
                || (isset($_SESSION['auth_method']) && $_SESSION['auth_method'] === 'code');
$isFullMember = isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0 
                && isset($_SESSION['auth_method']) && $_SESSION['auth_method'] === 'password';

$currentUser  = null;
$isAdminUser  = false;
$isOracleUser = false;
$currentPage  = basename($_SERVER['PHP_SELF']);

if ($isLoggedIn && isset($pdo)) {
    $stmt = $pdo->prepare("SELECT id, username, tier, admin, points, is_admin_store, role_status, is_private_user FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $currentUser = $stmt->fetch();
    if ($currentUser) {
        $isAdminUser = (int)($currentUser['admin'] ?? 0) === 1
                    || strtolower($currentUser['tier'] ?? '') === 'admin';
    }
}
// v1.7 — Utilisateur compte privé (famille/école/entreprise)
$isPrivateUser = $isLoggedIn && !empty($currentUser['is_private_user']);

// v1.7 — Appliquer les termes fixes pour les comptes privés
if ($isPrivateUser && function_exists('applyPrivateTerms')) applyPrivateTerms();

// Cercle actif en session
$activeCircleId   = $_SESSION['circle_id'] ?? 1;
$activeCircleName = '';
if ($isLoggedIn && isset($pdo)) {
    $sc = $pdo->prepare("SELECT name, oracle_id FROM circles WHERE id = ?");
    $sc->execute([$activeCircleId]);
    $circleRow = $sc->fetch();
    if ($circleRow) {
        $activeCircleName = $circleRow['name'];
        $isOracleUser = ((int)$circleRow['oracle_id'] === (int)($_SESSION['user_id'] ?? 0));
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>JeTeGageQue</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=<?= urlencode($themeFont) ?>:wght@400;700&family=Orbitron:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <!-- Theme dynamique -->
    <style>
        :root {
            --bg-main:       <?= $themeBg ?>;
            --bg-card:       <?= $themeCard ?>;
            --color-primary: <?= $themePrimary ?>;
            --color-accent:  <?= $themeAccent ?>;
            --color-text:    <?= $themeText ?>;
            --color-border:  <?= $themeBorder ?>;
            --font-main:     '<?= $themeFont ?>';
        }
        /* Force form controls sur fond sombre */
        .bg-dark .form-control,
        .bg-dark .form-select,
        .form-control.bg-dark,
        .form-select.bg-dark,
        textarea.bg-dark,
        input.bg-dark,
        select.bg-dark {
            background-color: #1a1a2e !important;
            color: #e0e0e0 !important;
            border-color: #444 !important;
        }
        .bg-dark .form-control::placeholder,
        .form-control.bg-dark::placeholder,
        textarea.bg-dark::placeholder,
        input.bg-dark::placeholder { color: #888 !important; }
        .form-control.bg-black, input.bg-black, textarea.bg-black {
            background-color: #000 !important;
            color: #e0e0e0 !important;
        }
        body { background-color: var(--bg-main); color: var(--color-text); font-family: var(--font-main), 'Roboto', sans-serif; }
        html, body { overflow-x: hidden; max-width: 100%; }

        /* ── Fixes mobile scroll et touch ───────────────────────── */
        /* Bloquer scroll horizontal partout */
        html {
            overflow-x: hidden;
            overscroll-behavior-x: none; /* Empêche le "rebond" horizontal */
        }
        body {
            overflow-x: hidden;
            overscroll-behavior-x: none;
            touch-action: pan-y; /* Autorise scroll vertical seulement */
            position: relative;
        }
        /* Empêcher les éléments de déborder et créer un scroll horizontal */
        * {
            max-width: 100%;
            box-sizing: border-box;
        }
        img, video, iframe { max-width: 100%; }

        /* Cartes de gage — pas d'espace flottant, scroll fluide */
        .gage-card {
            -webkit-user-select: none;
            user-select: none;          /* Pas de sélection de texte accidentelle */
            touch-action: pan-y;        /* Scroll vertical uniquement sur les cartes */
            overscroll-behavior: contain;
        }

        /* Colonnes de scroll — contenir le rebond vertical */
        #col2Gages, #col3Chat, .friends-col {
            overscroll-behavior-y: contain;
        }

        /* Menus dropdown — scroll interne autorisé */
        .dropdown-menu {
            overscroll-behavior: contain;
            touch-action: pan-y;
        }

        /* Modales — scroll interne uniquement */
        .modal-body, .modal-content {
            overscroll-behavior: contain;
            touch-action: pan-y;
        }

        /* Fix nav qui peut déborder sur mobile */
        .navbar { overflow-x: hidden; }
        .navbar-collapse { overflow-x: hidden; }

        @media (max-width: 768px) {
            /* Sur mobile, forcer les colonnes à prendre toute la largeur sans débordement */
            .container, .container-fluid {
                overflow-x: hidden;
                padding-left: 8px;
                padding-right: 8px;
            }
            /* Empêcher les cards de déborder */
            .card { overflow: hidden; }
        }
        /* Override text-muted sur fond sombre */
        .text-muted { color: #999 !important; }
        .text-secondary { color: #aaa !important; }
        /* Labels et titres secondaires lisibles */
        label.small, .form-label.small, .small.text-muted { color: #bbb !important; font-size: 0.72rem; }
        .form-text { color: #999 !important; }
        /* Dropdowns sur fond sombre */
        .dropdown-item { color: #ddd !important; }
        .dropdown-item:hover { color: #fff !important; background: rgba(255,255,255,0.08) !important; }
        .dropdown-divider { border-color: #333 !important; }
        /* Overlay si photo de fond */
        <?php if ($userBgImage): ?>
        body::before { content:''; position:fixed; inset:0; background:rgba(0,0,0,0.65); z-index:0; pointer-events:none; }
        body > * { position:relative; z-index:1; }
        <?php endif; ?>
        .oracle-text { font-family: 'Orbitron', sans-serif; }
        .navbar-oracle { background-color: #1a1a1a; border-bottom: 2px solid #333; }
        .navbar-brand { font-family: 'Orbitron', sans-serif; font-weight: bold; color: #00d4ff !important; text-shadow: 0 0 6px rgba(0,212,255,0.4); font-size: 1rem; }
        .nav-link { color: #bbb !important; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 1px; transition: 0.2s; padding: 6px 10px !important; }
        .nav-link:hover { color: #fff !important; background-color: rgba(255,255,255,0.06); border-radius: 4px; }
        .nav-link.active { color: #ffc107 !important; font-weight: bold; }
        .dropdown-menu { background: #1e1e1e; border: 1px solid #333; }
        .dropdown-item { color: #ccc; font-size: 0.8rem; }
        .dropdown-item:hover { background: #2a2a2a; color: #fff; }
        .dropdown-divider { border-color: #333; }
        .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 4px; }
        .status-online  { background: #28a745; box-shadow: 0 0 4px #28a745; }
        .status-offline { background: #ffc107; }
        .status-dnd     { background: #dc3545; }
        .badge-gold   { background: linear-gradient(45deg,#d4af37,#f1d592); color:#000; font-weight:bold; border:1px solid #b8860b; }
        .badge-silver { background: linear-gradient(45deg,#a9a9a9,#e0e0e0); color:#000; font-weight:bold; border:1px solid #808080; }
        .btn-xs { font-size: 0.65rem; padding: 2px 6px; }
        .card { background-color: #1a1a1a; border-color: #333; }
        .form-control, .form-select { background-color: #0d0d0d !important; color: #e0e0e0 !important; border-color: #444 !important; }
        .form-control::placeholder { color: #666; }
        .form-control:focus, .form-select:focus { border-color: #0d6efd !important; box-shadow: 0 0 0 0.15rem rgba(13,110,253,.25); }
        .table-dark { --bs-table-bg: #1a1a1a; }
        .modal-content { background: #1a1a1a; }
        /* Marquise */
        .marquee-bar { background: var(--marquee-bg, #0d0d0d); border-bottom: 1px solid #333; padding: 4px 0; overflow: hidden; white-space: nowrap; position:relative; }
        .marquee-flash { position:fixed;top:0;left:0;width:100%;z-index:9999;display:none;overflow:hidden;white-space:nowrap;align-items:center; }
        .marquee-flash-inner { display:inline-block;font-weight:900;letter-spacing:1px;animation:marquee-scroll 6s linear; }
        @keyframes marquee-flash-blink { 0%,100%{opacity:1} 50%{opacity:0.4} }
        .marquee-inner { display: inline-block; animation: marquee-scroll 30s linear infinite; }
        @keyframes marquee-scroll { from { transform: translateX(100vw); } to { transform: translateX(-100%); } }
    </style>
</head>
<body<?php if ($userBgImage): ?> style="background-image:url('<?= $userBgImage ?>');background-size:cover;background-attachment:fixed;background-position:center;"<?php endif; ?>>

<!-- FLASH ALERT MARQUISE -->
<div id="marqueeFlash" style="display:none;position:fixed;top:0;left:0;width:100%;z-index:9999;overflow:hidden;white-space:nowrap;align-items:center;">
    <div id="marqueeFlashInner" style="display:inline-block;padding:0 2rem;font-family:'Orbitron',sans-serif;font-weight:900;letter-spacing:2px;"></div>
</div>

<script>
const _flashEnabled  = <?= (int)$flashEnabled ?>;
const _flashDuration = <?= (int)$flashDuration ?> * 1000;
const _flashDelay    = <?= (int)$flashDelay ?>   * 1000;

function triggerMarqueeFlash(message, color, bg) {
    if (!_flashEnabled) return;
    setTimeout(() => {
        const bar   = document.getElementById('marqueeFlash');
        const inner = document.getElementById('marqueeFlashInner');
        if (!bar || !inner) return;
        color = color || '#ffc107';
        bg    = bg    || '#0a0a0a';
        const dur = (_flashDuration/1000) + 's';
        bar.style.cssText   = 'display:flex;position:fixed;top:0;left:0;width:100%;z-index:9999;overflow:hidden;white-space:nowrap;align-items:center;height:38px;background:'+bg+';border-bottom:2px solid '+color+';box-shadow:0 0 20px '+color+'88;';
        inner.style.cssText = 'display:inline-block;font-size:clamp(13px,2.5vw,20px);font-weight:900;color:'+color+';letter-spacing:2px;font-family:Orbitron,sans-serif;text-shadow:0 0 12px '+color+';padding:0 2rem;animation:marquee-scroll '+dur+' linear forwards;';
        inner.textContent   = '⚡ ' + message + ' ⚡';
        bar.style.animation = 'marquee-flash-blink 0.6s ease-in-out 4';
        bar.style.display   = 'flex';
        setTimeout(() => {
            bar.style.display = 'none';
            bar.style.animation = '';
            inner.style.animation = '';
            inner.textContent = '';
        }, _flashDuration + _flashDelay);
    }, _flashDelay);
}
// Déclencheurs globaux
window.addEventListener('jetegage:notification', e => triggerMarqueeFlash(e.detail.message, '#0dcaf0', '#000011'));
window.addEventListener('jetegage:trophy',       e => triggerMarqueeFlash('🏆 ' + e.detail.title, '#ffc107', '#110a00'));
window.addEventListener('jetegage:bet',          e => triggerMarqueeFlash('⚡ ' + e.detail.message, '#28a745', '#001100'));

// Flash auto si notifs non lues au chargement
<?php if (!empty($unreadNotif) && $unreadNotif > 0 && $flashEnabled): ?>
document.addEventListener('DOMContentLoaded', () => {
    triggerMarqueeFlash(
        '<?= $unreadNotif ?> nouvelle<?= $unreadNotif>1?"s":"" ?> notification<?= $unreadNotif>1?"s":"" ?> !',
        '#0dcaf0', '#00080f'
    );
});
<?php endif; ?>
</script>

<nav class="navbar navbar-expand-lg navbar-oracle sticky-top">
    <div class="container-fluid px-3">
        <a class="navbar-brand" href="index.php">
            JETEGAGEQUE <span style="font-size:0.5rem;color:#888;">v2.0</span>
        </a>

        <?php if ($isLoggedIn && $currentUser): ?>
        <!-- Statut en ligne -->
        <span class="me-2 d-none d-lg-inline" style="font-size:0.7rem;">
            <?php
            $rs = $currentUser['role_status'] ?? 'offline';
            $dotClass = 'status-offline';
            $label    = 'Hors ligne';
            if ($rs === 'online') { $dotClass = 'status-online';  $label = 'En ligne'; }
            if ($rs === 'dnd')    { $dotClass = 'status-dnd';     $label = 'Ne pas déranger'; }
            ?>
            <span class="status-dot <?= $dotClass ?>"></span>
            <span style="color:#aaa;"><?= $label ?></span>
        </span>
        <?php endif; ?>

        <button class="navbar-toggler border-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon" style="filter:invert(1);"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ms-auto align-items-lg-center gap-1">

                <?php if ($isLoggedIn): ?>

                    <li class="nav-item">
                        <a class="nav-link <?= ($currentPage??'')==='index.php'?'active':'' ?>" href="index.php">
                            <i class="fa-solid fa-house fa-xs"></i> Dashboard
                        </a>
                    </li>

                    <?php if ($isFullMember):
                        // Compteur messages non lus
                        $unreadPM = 0;
                        try {
                            $pmStmt = $pdo->prepare("SELECT COUNT(*) FROM private_messages WHERE receiver_id=? AND is_read=0");
                            $pmStmt->execute([$currentUser['id']]);
                            $unreadPM = (int)$pmStmt->fetchColumn();
                        } catch (Exception $e) {}
                    ?>
                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='messages.php'?'active':'' ?>" href="messages.php" style="position:relative;">
                                <i class="fa-solid fa-envelope fa-xs"></i>
                                <?php if ($unreadPM > 0): ?>
                                    <span class="badge bg-danger" style="font-size:0.5rem;position:absolute;top:2px;right:0;"><?= $unreadPM ?></span>
                                <?php endif; ?>
                            </a>
                        </li>

                        <!-- CLOCHE NOTIFICATIONS -->
                        <?php
                        $unreadNotif = 0; $notifList = [];
                        try {
                            $nStmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
                            $nStmt->execute([$currentUser['id']]);
                            $notifList   = $nStmt->fetchAll();
                            $unreadNotif = count(array_filter($notifList, fn($n) => !(int)$n['is_read']));
                        } catch (Exception $e) {}
                        if (isset($_GET['mark_notif_read'])) {
                            try { $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=?")->execute([$currentUser['id']]); } catch (Exception $e) {}
                            header("Location: " . strtok($_SERVER['REQUEST_URI'],'?')); exit;
                        }
                        ?>
                        <li class="nav-item dropdown">
                            <a class="nav-link" href="#" data-bs-toggle="dropdown" style="position:relative;" id="notifDropdown">
                                <i class="fa-solid fa-bell fa-xs"></i>
                                <?php if ($unreadNotif > 0): ?>
                                <span class="badge bg-danger" style="font-size:0.5rem;position:absolute;top:2px;right:-2px;"><?= $unreadNotif ?></span>
                                <?php endif; ?>
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end" style="min-width:300px;max-height:360px;overflow-y:auto;background:#0d0d1a;border:1px solid #0dcaf0;">
                                <li class="px-3 py-2 d-flex justify-content-between align-items-center" style="border-bottom:1px solid #1a1a3a;">
                                    <span class="fw-bold text-info" style="font-size:0.7rem;letter-spacing:1px;">NOTIFICATIONS</span>
                                    <?php if ($unreadNotif > 0): ?>
                                    <a href="?mark_notif_read=1" class="text-muted" style="font-size:0.6rem;text-decoration:none;">Tout lire</a>
                                    <?php endif; ?>
                                </li>
                                <?php if (empty($notifList)): ?>
                                <li class="px-3 py-3 text-center text-muted" style="font-size:0.7rem;">Aucune notification</li>
                                <?php else: foreach ($notifList as $notif):
                                    $nRead = (int)$notif['is_read'];
                                    $nMsg  = $notif['message'] ?? '';
                                    $nLink = $notif['link'] ?? '';
                                    $nTime = date('d/m H:i', strtotime($notif['created_at']));
                                    $nId   = (int)$notif['id'];
                                    $nBg   = $nRead ? 'transparent' : 'rgba(13,202,240,0.06)';
                                    $nDot  = $nRead ? '' : '<span style="width:6px;height:6px;border-radius:50%;background:#0dcaf0;display:inline-block;flex-shrink:0;margin-top:5px;"></span>';

                                    $isFriendReq = strpos($nMsg,"veut t'ajouter") !== false;
                                    $isBetReq    = strpos($nMsg,'gage') !== false && strpos($nMsg,'attend') !== false;
                                    $isFriendAcc = strpos($nMsg,"accepté") !== false;
                                    $betId = 0; if (preg_match('/#(\d+)/', $nMsg, $bm)) $betId=(int)$bm[1];
                                    $friendId = 0; if ($isFriendReq && preg_match('/friend_request=(\d+)/', $nLink, $fm)) $friendId=(int)$fm[1];

                                    if ($isFriendReq)     { $nIcon='fa-user-plus';  $nColor='#0dcaf0'; }
                                    elseif ($isFriendAcc) { $nIcon='fa-user-check'; $nColor='#28a745'; }
                                    elseif ($isBetReq)    { $nIcon='fa-bolt';       $nColor='#ffc107'; }
                                    else                  { $nIcon='fa-circle-info';$nColor='#6c757d'; }

                                    $nData = htmlspecialchars(json_encode([
                                        'id'        => $nId,  'msg'     => $nMsg,
                                        'type'      => $isFriendReq?'friend_req':($isBetReq?'bet_req':'info'),
                                        'friend_id' => $friendId, 'bet_id' => $betId,
                                        'link'      => $nLink,    'icon'   => $nIcon,
                                        'color'     => $nColor,   'time'   => $nTime,
                                    ]), ENT_QUOTES);
                                ?>
                                <li>
                                    <div class="dropdown-item" style="background:<?=$nBg?>;padding:8px 12px;white-space:normal;cursor:pointer;"
                                         onclick="openNotifModal(<?=$nData?>)">
                                        <div class="d-flex gap-2 align-items-start">
                                            <?=$nDot?>
                                            <div style="width:22px;flex-shrink:0;text-align:center;padding-top:1px;">
                                                <i class="fa-solid <?=$nIcon?>" style="font-size:0.75rem;color:<?=$nColor?>;"></i>
                                            </div>
                                            <div style="flex:1;min-width:0;">
                                                <div style="font-size:0.68rem;color:#ddd;line-height:1.3;"><?=htmlspecialchars($nMsg)?></div>
                                                <div style="font-size:0.58rem;color:#888;margin-top:2px;"><?=$nTime?></div>
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <?php endforeach; endif; ?>
                            </ul>
                        </li>

                        <?php if (!$isPrivateUser): // v1.7 — caché pour comptes privés ?>
                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='stats.php'?'active':'' ?>" href="stats.php">
                                <i class="fa-solid fa-chart-bar fa-xs"></i> Stats
                            </a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='user_score.php'?'active':'' ?>" href="user_score.php">
                                <i class="fa-solid fa-star fa-xs"></i> Score
                            </a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='trophees.php'?'active':'' ?>" href="trophees.php">
                                <i class="fa-solid fa-trophy fa-xs"></i> Trophées
                            </a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='upgrade.php'?'active':'' ?>" href="upgrade.php">
                                <i class="fa-solid fa-star fa-xs"></i> Forfaits
                            </a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='store.php'?'active':'' ?>" href="store.php">
                                <i class="fa-solid fa-store fa-xs"></i> Boutique
                            </a>
                        </li>
                        <?php endif; // v1.7 ?>

                        <!-- Menu Gestion Cercle (Oracle + Admin) -->
                        <?php if ($isOracleUser || $isAdminUser): ?>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
                                <i class="fa-solid fa-eye fa-xs"></i> L'Oracle
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="gestion_cercle.php"><i class="fa-solid fa-users-gear fa-xs me-1"></i> Gestion du cercle</a></li>
                                <li><a class="dropdown-item" href="create_circle.php"><i class="fa-solid fa-circle-plus fa-xs me-1"></i> Mes cercles</a></li>
                                <li><a class="dropdown-item" href="chat_history.php"><i class="fa-solid fa-clock-rotate-left fa-xs me-1"></i> Historique chat</a></li>
                                <?php if (!$isPrivateUser): // v1.7 ?>
                                <li><a class="dropdown-item" href="oracle_vote.php"><i class="fa-solid fa-vote-yea fa-xs me-1"></i> Vote Oracle</a></li>
                                <li><a class="dropdown-item" href="oracle_judge.php"><i class="fa-solid fa-gavel fa-xs me-1"></i> Arbitrage gages</a></li>
                                <li><a class="dropdown-item" href="oracle_mailing.php"><i class="fa-solid fa-envelope fa-xs me-1"></i> Listes de distribution</a></li>
                                <li><a class="dropdown-item" href="marquee_manage.php"><i class="fa-solid fa-scroll fa-xs me-1"></i> Bande défilante</a></li>
                                <?php endif; // v1.7 ?>
                            </ul>
                        </li>
                        <?php endif; ?>

                        <!-- Menu Admin -->
                        <?php if ($isAdminUser): ?>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle text-danger" href="#" data-bs-toggle="dropdown">
                                <i class="fa-solid fa-shield-halved fa-xs"></i> Admin
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="admin.php"><i class="fa-solid fa-gauge fa-xs me-1"></i> Panneau Admin</a></li>
                                <li><a class="dropdown-item" href="admin_users.php"><i class="fa-solid fa-users fa-xs me-1"></i> Gestion Membres</a></li>
                                <li><a class="dropdown-item" href="admin_bets.php"><i class="fa-solid fa-list-check fa-xs me-1"></i> Gestion Gages</a></li>
                                <li><a class="dropdown-item" href="admin_reports.php"><i class="fa-solid fa-flag fa-xs me-1"></i> Reports</a></li>
                                <li><a class="dropdown-item" href="admin_config.php"><i class="fa-solid fa-sliders fa-xs me-1"></i> Configuration</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="admin_trophees.php"><i class="fa-solid fa-award fa-xs me-1"></i> Trophées</a></li>
                                <li><a class="dropdown-item" href="admin_events.php"><i class="fa-solid fa-calendar-days fa-xs me-1"></i> Événements</a></li>
                                <li><a class="dropdown-item" href="admin_chat.php"><i class="fa-solid fa-comments fa-xs me-1"></i> Chat</a></li>
                                <li><a class="dropdown-item" href="admin_appearance.php"><i class="fa-solid fa-palette fa-xs me-1"></i> Apparence</a></li>
                                <li><a class="dropdown-item" href="admin_wallet.php"><i class="fa-solid fa-coins fa-xs me-1"></i> Portefeuille Jetons</a></li>
                                <li><a class="dropdown-item" href="admin_droits.php"><i class="fa-solid fa-shield-halved fa-xs me-1"></i> Droits d'accès</a></li>
                                <li><a class="dropdown-item" href="admin_limites.php"><i class="fa-solid fa-sliders fa-xs me-1"></i> Limites par grade</a></li>
                                <li><a class="dropdown-item" href="admin_commandites.php"><i class="fa-solid fa-handshake fa-xs me-1"></i> Commanditaires</a></li>
                                <li><a class="dropdown-item" href="admin_pricing.php"><i class="fa-solid fa-tag fa-xs me-1"></i> Prix &amp; Forfaits</a></li>
                                <li><a class="dropdown-item" href="admin_gage_rules.php"><i class="fa-solid fa-gavel fa-xs me-1"></i> Règles des gages</a></li>
                                <li><a class="dropdown-item" href="admin_terms.php"><i class="fa-solid fa-language fa-xs me-1"></i> Terminologie</a></li>
                                <li><a class="dropdown-item" href="admin_emails.php"><i class="fa-solid fa-envelope-open-text fa-xs me-1"></i> Templates courriels</a></li>
                                <li><a class="dropdown-item" href="admin_chat_icons.php"><i class="fa-solid fa-face-smile fa-xs me-1"></i> Icônes du chat</a></li>
                                <li><a class="dropdown-item" href="admin_anomalies.php"><i class="fa-solid fa-triangle-exclamation fa-xs me-1"></i> Anomalies</a></li>
                                <li><a class="dropdown-item" href="admin_bad_words.php"><i class="fa-solid fa-filter fa-xs me-1"></i> Filtre de mots</a></li>
                                <li><a class="dropdown-item" href="admin_bet_keywords.php"><i class="fa-solid fa-tags fa-xs me-1"></i> Classification gages</a></li>
                                <li><a class="dropdown-item" href="admin_notes.php"><i class="fa-solid fa-clipboard-list fa-xs me-1"></i> Notes & Tâches</a></li>
                                <li><a class="dropdown-item" href="admin_bugs.php"><i class="fa-solid fa-bug fa-xs me-1"></i> Bugs rapportés</a></li>
                                <li><a class="dropdown-item" href="admin_server.php"><i class="fa-solid fa-server fa-xs me-1"></i> Serveur</a></li>
                                <li><a class="dropdown-item" href="admin_backup.php"><i class="fa-solid fa-database fa-xs me-1"></i> Backups</a></li>
                                <li><a class="dropdown-item" href="admin_store.php"><i class="fa-solid fa-store fa-xs me-1"></i> Boutique</a></li>
                            </ul>
                        </li>
                        <?php endif; ?>

                        <!-- Boutique Admin Store -->
                        <?php if ((int)($currentUser['is_admin_store'] ?? 0) === 1): ?>
                        <li class="nav-item">
                            <a class="nav-link text-warning" href="store_manage.php">
                                <i class="fa-solid fa-store fa-xs"></i> Ma Boutique
                            </a>
                        </li>
                        <?php endif; ?>

                        <li class="nav-item">
                            <a class="nav-link <?= ($currentPage??'')==='configuration.php'?'active':'' ?>" href="configuration.php">
                                <i class="fa-solid fa-gear fa-xs"></i> Config
                            </a>
                        </li>

                    <?php endif; // isFullMember ?>

                    <!-- Statut + Déconnexion -->
                    <li class="nav-item dropdown ms-lg-2">
                        <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown" style="font-size:0.75rem;">
                            <?php
                            $tier = $currentUser['tier'] ?? 'free';
                            if ($tier === 'premium')      echo '<span class="badge badge-gold px-2 py-1" style="font-size:0.6rem;">PREMIUM</span>';
                            elseif ($tier === 'premium_plus') echo '<span class="badge badge-silver px-2 py-1" style="font-size:0.6rem;">PREMIUM+</span>';
                            else echo '<i class="fa-solid fa-user fa-xs"></i>';
                            ?>
                            <?= htmlspecialchars($currentUser['username'] ?? '') ?>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li class="px-3 py-2">
                                <?php if (!$isMinor): ?>
                                <a href="wallet.php" class="text-decoration-none d-flex align-items-center gap-2">
                                    <span class="text-warning fw-bold" style="font-size:0.9rem;"><?= number_format($walletPoints) ?></span>
                                    <span style="color:#aaa;font-size:0.65rem;">jetons</span>
                                </a>
                                <?php endif; ?>
                            </li>
                            <li><hr class="dropdown-divider my-1"></li>
                            <li class="px-3 py-1">
                                <small style="color:#aaa;" class="d-block">Changer statut</small>
                                <div class="d-flex gap-1 mt-1">
                                    <a href="set_status.php?s=online"  class="btn btn-xs btn-outline-success">o</a>
                                    <a href="set_status.php?s=offline" class="btn btn-xs btn-outline-warning">o</a>
                                    <a href="set_status.php?s=dnd"     class="btn btn-xs btn-outline-danger">o</a>
                                </div>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <?php if (!$isMinor): ?>
                            <li><a class="dropdown-item" href="wallet.php"><i class="fa-solid fa-coins fa-xs me-1"></i> Mon Portefeuille</a></li>
                            <li><a class="dropdown-item" href="wallet_shop.php"><i class="fa-solid fa-store fa-xs me-1"></i> Boutique Jetons</a></li>
                            <?php endif; ?>
                            <li><a class="dropdown-item" href="profile.php"><i class="fa-solid fa-user fa-xs me-1"></i> Mon Profil</a></li>
                            <li><a class="dropdown-item" href="configuration.php"><i class="fa-solid fa-gear fa-xs me-1"></i> Configuration</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="index.php?logout=1"><i class="fa-solid fa-right-from-bracket fa-xs me-1"></i> Quitter</a></li>
                        </ul>
                    </li>

                <?php else: ?>
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Connexion</a>
                    </li>
                <?php endif; ?>

                <!-- Sélecteur de langue -->
                <li class="nav-item ms-1">
                    <div class="dropdown">
                        <button class="btn btn-xs dropdown-toggle"
                                data-bs-toggle="dropdown"
                                style="background:rgba(255,255,255,0.06);border:1px solid #333;color:#aaa;font-size:0.62rem;padding:3px 8px;border-radius:5px;">
                            🌐 FR
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" style="min-width:160px;background:#0d0d1a;border:1px solid #333;">
                            <li>
                                <a class="dropdown-item active" href="?lang=fr" style="font-size:0.7rem;color:#0dcaf0;">
                                    🇨🇦 Français (actif)
                                </a>
                            </li>
                            <li>
                                <span class="dropdown-item d-flex justify-content-between align-items-center"
                                      style="font-size:0.7rem;color:#666;cursor:default;">
                                    🇺🇸 English
                                    <span style="font-size:0.55rem;background:rgba(255,193,7,0.15);border:1px solid rgba(255,193,7,0.3);color:#ffc107;border-radius:4px;padding:1px 5px;">En construction</span>
                                </span>
                            </li>
                        </ul>
                    </div>
                </li>

            </ul>
        </div>
    </div>
</nav>

<?php if (!empty($_SESSION['admin_impersonating'])): ?>
<div style="background:#dc3545;color:#fff;text-align:center;padding:5px;font-size:0.75rem;font-weight:bold;position:sticky;top:56px;z-index:1000;">
     MODE ADMIN — Tu navigues en tant que <strong><?= htmlspecialchars($currentUser['username'] ?? '?') ?></strong>
    &nbsp;|&nbsp;
    <a href="admin_as_user.php?action=exit" style="color:#fff;font-weight:bold;text-decoration:underline;">
        ← RETOUR ADMIN (<?= htmlspecialchars($_SESSION['admin_original_name'] ?? '') ?>)
    </a>
</div>
<?php endif; ?>

<?php
// --- CONFIG MARQUISE + FLASH ---
$marqueeBg      = '#0d0d0d';
$flashEnabled   = 1;
$flashDuration  = 5;
$flashDelay     = 2;
try {
    $cfgM = $pdo->query("SELECT config_key,config_value FROM admin_config WHERE config_key IN ('marquee_bg','flash_enabled','flash_duration','flash_delay')")->fetchAll(PDO::FETCH_KEY_PAIR);
    $marqueeBg    = $cfgM['marquee_bg']     ?? '#0d0d0d';
    $flashEnabled = (int)($cfgM['flash_enabled']  ?? 1);
    $flashDuration= (int)($cfgM['flash_duration'] ?? 5);
    $flashDelay   = (int)($cfgM['flash_delay']    ?? 2);
} catch (Exception $e) {}
echo '<style>:root{--marquee-bg:'.htmlspecialchars($marqueeBg).'}</style>';

// --- MARQUISE DÉFILANTE ---
if ($isLoggedIn && isset($pdo)) {
    try {
        $stmtM = $pdo->prepare("
            SELECT m.message, m.text_color, m.speed, c.name as circle_name
            FROM marquee m
            LEFT JOIN circles c ON m.circle_id = c.id
            WHERE m.is_active = 1
              AND (m.circle_id IS NULL OR m.circle_id = ?)
              AND (m.end_date IS NULL OR m.end_date >= NOW())
            ORDER BY m.id DESC LIMIT 5
        ");
        $stmtM->execute([$activeCircleId]);
        $marqueeItems = $stmtM->fetchAll();
        if (!empty($marqueeItems)) {
            $speedMap = ['slow'=>'50s','normal'=>'30s','quick'=>'15s','super_quick'=>'7s'];
            echo '<div class="marquee-bar">';
            foreach ($marqueeItems as $mi) {
                $spd = $speedMap[$mi['speed']] ?? '30s';
                $col = htmlspecialchars($mi['text_color'] ?? '#ffffff');
                $txt = '';
                if ($mi['circle_name']) $txt .= '<strong style="color:#00d4ff;">✦ ' . htmlspecialchars($mi['circle_name']) . '</strong> — ';
                $txt .= htmlspecialchars($mi['message']);
                echo "<div class='marquee-inner' style='animation-duration:{$spd};color:{$col};font-size:0.78rem;padding:0 2rem;'>{$txt}</div>";
            }
            echo '</div>';
        }
    } catch (Exception $e) { /* silencieux */ }
}
?>

<!-- ══ MODAL NOTIFICATIONS ══════════════════════════════════ -->
<div id="notifModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,0.78);"
     onclick="if(event.target===this)closeNotifModal()">
    <div id="notifModalBox" style="margin:60px auto;width:min(440px,92vw);background:#0d0d1a;border:1px solid #0dcaf0;border-radius:10px;overflow:hidden;box-shadow:0 0 40px rgba(13,202,240,0.15);">
        <div id="notifModalHead" style="background:#050520;padding:12px 16px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #1a1a3a;">
            <span id="notifModalTitle" class="fw-bold" style="font-size:0.8rem;color:#0dcaf0;letter-spacing:1px;"></span>
            <button onclick="closeNotifModal()" style="background:none;border:none;color:#999;font-size:1rem;cursor:pointer;line-height:1;">✕</button>
        </div>
        <div id="notifModalBody" style="padding:20px 16px;max-height:70vh;overflow-y:auto;"></div>
    </div>
</div>

<script>
function closeNotifModal() {
    document.getElementById('notifModal').style.display = 'none';
}

function openNotifModal(data) {
    fetch('?mark_one_notif=' + data.id, {method:'GET'}).catch(()=>{});
    const modal = document.getElementById('notifModal');
    const title = document.getElementById('notifModalTitle');
    const body  = document.getElementById('notifModalBody');
    const head  = document.getElementById('notifModalHead');
    head.style.borderBottom = '1px solid ' + (data.color || '#0dcaf0');
    title.style.color = data.color || '#0dcaf0';
    body.innerHTML = '<div style="text-align:center;padding:20px 0;color:#888;font-size:0.7rem;">Chargement...</div>';
    modal.style.display = 'block';

    // DEMANDE D'AMI
    if (data.type === 'friend_req' && data.friend_id > 0) {
        title.innerHTML = '<i class="fa-solid fa-user-plus me-2"></i>DEMANDE D\'AMI';
        body.innerHTML = `
            <div style="text-align:center;margin-bottom:16px;">
                <div style="width:52px;height:52px;border-radius:50%;background:#0d6efd;margin:0 auto 10px;display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:700;color:#fff;">?</div>
                <div style="font-size:0.85rem;color:#ddd;margin-bottom:4px;">${data.msg}</div>
                <div style="font-size:0.6rem;color:#888;">${data.time}</div>
            </div>
            <div style="display:flex;gap:10px;">
                <button id="notifAcceptBtn" onclick="notifAcceptFriend(${data.friend_id})"
                        style="flex:1;background:rgba(40,167,69,0.2);border:1px solid #28a745;color:#777;border-radius:6px;padding:9px;font-size:0.75rem;font-weight:700;cursor:pointer;">
                    <i class="fa-solid fa-check me-1"></i>Accepter
                </button>
                <button onclick="notifDeclineFriend(${data.friend_id})"
                        style="flex:1;background:rgba(220,53,69,0.12);border:1px solid #dc3545;color:#dc3545;border-radius:6px;padding:9px;font-size:0.75rem;font-weight:700;cursor:pointer;">
                    <i class="fa-solid fa-xmark me-1"></i>Refuser
                </button>
            </div>`;

    // GAGE
    } else if (data.bet_id > 0) {
        title.innerHTML = data.type==='bet_req'
            ? '<i class="fa-solid fa-bolt me-2"></i>INVITATION À UN GAGE'
            : '<i class="fa-solid fa-trophy me-2"></i>RÉSULTAT DE GAGE';
        body.innerHTML = '<div style="text-align:center;padding:12px;color:#888;font-size:0.7rem;">Chargement du gage...</div>';
        fetch('fetch_bet_notif.php?id=' + data.bet_id)
            .then(r => r.text())
            .then(html => {
                let actions = data.type==='bet_req'
                    ? `<div style="display:flex;gap:10px;margin-top:12px;">
                        <a href="bet_accept.php?id=${data.bet_id}" style="flex:1;background:rgba(255,193,7,0.15);border:1px solid #ffc107;color:#ffc107;border-radius:6px;padding:9px;font-size:0.75rem;font-weight:700;text-align:center;text-decoration:none;">
                            <i class="fa-solid fa-handshake me-1"></i>Répondre au gage
                        </a>
                        <button onclick="closeNotifModal()" style="flex:1;background:rgba(108,117,125,0.12);border:1px solid #555;color:#888;border-radius:6px;padding:9px;font-size:0.75rem;font-weight:700;cursor:pointer;">Plus tard</button>
                       </div>`
                    : `<button onclick="closeNotifModal()" style="display:block;width:100%;margin-top:10px;background:none;border:1px solid #222;color:#999;border-radius:6px;padding:7px;font-size:0.7rem;cursor:pointer;">Fermer</button>`;
                body.innerHTML = html + actions;
            })
            .catch(() => {
                body.innerHTML = `<div style="padding:12px;background:#0a0a14;border-radius:6px;margin-bottom:12px;">
                    <div style="font-size:0.7rem;color:#ffc107;">Gage #${data.bet_id}</div>
                    <div style="font-size:0.82rem;color:#ddd;margin-top:4px;">${data.msg}</div>
                </div>
                <a href="bet_accept.php?id=${data.bet_id}" style="display:block;background:rgba(255,193,7,0.15);border:1px solid #ffc107;color:#ffc107;border-radius:6px;padding:8px;text-align:center;text-decoration:none;font-size:0.72rem;font-weight:700;">Voir le gage</a>`;
            });

    // INFO GÉNÉRALE
    } else {
        const icons = {'fa-trophy':'🏆','fa-gavel':'⚖️','fa-circle-nodes':'🔵','fa-user-check':'✅','fa-circle-info':'ℹ️'};
        title.innerHTML = '<i class="fa-solid ' + data.icon + ' me-2"></i>NOTIFICATION';
        let actionBtn = data.link && data.link !== '#'
            ? `<a href="${data.link}" style="display:block;margin-top:12px;background:rgba(13,202,240,0.1);border:1px solid #0dcaf0;color:#0dcaf0;border-radius:6px;padding:8px;font-size:0.72rem;font-weight:700;text-align:center;text-decoration:none;">Voir →</a>`
            : '';
        body.innerHTML = `
            <div style="text-align:center;padding:8px 0 16px;">
                <div style="font-size:2rem;margin-bottom:10px;">${icons[data.icon]||'ℹ️'}</div>
                <div style="font-size:0.82rem;color:#ddd;line-height:1.5;">${data.msg}</div>
                <div style="font-size:0.6rem;color:#888;margin-top:6px;">${data.time}</div>
            </div>${actionBtn}
            <button onclick="closeNotifModal()" style="display:block;width:100%;margin-top:8px;background:none;border:1px solid #222;color:#999;border-radius:6px;padding:7px;font-size:0.7rem;cursor:pointer;">Fermer</button>`;
    }
}

function notifAcceptFriend(id) {
    const btn = document.getElementById('notifAcceptBtn');
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-1"></i>...'; }
    fetch('friend_actions.php?action=accept&id=' + id)
        .then(() => {
            document.getElementById('notifModalBody').innerHTML = `
                <div style="text-align:center;padding:20px 0;">
                    <div style="font-size:2rem;margin-bottom:10px;">✅</div>
                    <div style="font-size:0.82rem;color:#777;font-weight:600;">Demande acceptée !</div>
                </div>
                <button onclick="closeNotifModal()" style="display:block;width:100%;margin-top:8px;background:rgba(40,167,69,0.15);border:1px solid #28a745;color:#777;border-radius:6px;padding:8px;font-size:0.72rem;font-weight:700;cursor:pointer;">Fermer</button>`;
        });
}

function notifDeclineFriend(id) {
    fetch('friend_actions.php?action=decline&id=' + id)
        .then(() => {
            document.getElementById('notifModalBody').innerHTML = `
                <div style="text-align:center;padding:20px 0;">
                    <div style="font-size:2rem;margin-bottom:10px;">🚫</div>
                    <div style="font-size:0.82rem;color:#888;">Demande refusée.</div>
                </div>
                <button onclick="closeNotifModal()" style="display:block;width:100%;margin-top:8px;background:none;border:1px solid #333;color:#999;border-radius:6px;padding:8px;font-size:0.7rem;cursor:pointer;">Fermer</button>`;
        });
}

// Marquer une notification comme lue
<?php if ($isLoggedIn && isset($_GET['mark_one_notif'])): ?>
<?php try { $pdo->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND user_id=?")->execute([(int)$_GET['mark_one_notif'], $currentUser['id']]); } catch(Exception $e) {} ?>
<?php endif; ?>
</script>
