<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = '';
if (isset($_GET['saved'])) {
    $msg = match($_GET['saved']) {
        'code'       => "Code admin sauvegarde !",
        'config'     => "Configuration sauvegardee !",
        'disclaimer' => "Disclaimer sauvegarde !",
        default      => "Sauvegarde !"
    };
}

// Creer la table admin_config si absente
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS admin_config (
        id           INT(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        config_key   VARCHAR(100) NOT NULL UNIQUE,
        config_value TEXT         DEFAULT NULL
    )");
} catch (Exception $e) {}

$configKeys = [
    'pts_chat'     => ['Chat (message envoye)',         1],
    'pts_message'  => ['Messagerie privee',             10],
    'pts_vote'     => ['Voter sur un gage',             5],
    'pts_login'    => ['Connexion',                     2],
    'pts_bet_view' => ['Voir le detail d un gage',      1],
    'pts_profile'  => ['Voir un profil',                1],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    try {
        foreach ($configKeys as $key => $info) {
            $val = max(0, (int)($_POST[$key] ?? $info[1]));
            $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES (?,?) ON DUPLICATE KEY UPDATE config_value=?")->execute([$key,$val,$val]);
        }
        header("Location: admin_config.php?saved=config"); exit;
    } catch (Exception $e) { $msg = "Erreur: " . $e->getMessage(); }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_disclaimer'])) {
    try {
        $disc = trim(htmlspecialchars($_POST['disclaimer_text'] ?? ''));
        $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('disclaimer_text',?) ON DUPLICATE KEY UPDATE config_value=?")->execute([$disc,$disc]);
        header("Location: admin_config.php?saved=disclaimer"); exit;
    } catch (Exception $e) { $msg = "Erreur: " . $e->getMessage(); }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_admin_code'])) {
    $code = trim($_POST['admin_code'] ?? '');
    if (strlen($code) >= 4) {
        try {
            $hashed = password_hash($code, PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('admin_login_code',?) ON DUPLICATE KEY UPDATE config_value=?")->execute([$hashed,$hashed]);
            header("Location: admin_config.php?saved=code"); exit;
        } catch (Exception $e) { $msg = "Erreur: " . $e->getMessage(); }
    } else { $msg = "Le code doit avoir au moins 4 caracteres."; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_media'])) {
    try {
        $bmStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='block_media'");
        $bmStmt->execute();
        $blockMedia = (int)($bmStmt->fetchColumn() ?? 0);
        $newVal = $blockMedia ? 0 : 1;
        $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('block_media',?) ON DUPLICATE KEY UPDATE config_value=?")->execute([$newVal,$newVal]);
        header("Location: admin_config.php"); exit;
    } catch (Exception $e) {}
}

$currentVals = [];
foreach ($configKeys as $key => $info) {
    try {
        $r = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
        $r->execute([$key]);
        $row = $r->fetch();
        $currentVals[$key] = $row ? (int)$row['config_value'] : $info[1];
    } catch (Exception $e) { $currentVals[$key] = $info[1]; }
}

try {
    $discStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='disclaimer_text'");
    $discStmt->execute();
    $disclaimerText = $discStmt->fetchColumn() ?: "Ce site ne transige pas d'argent reel.";
} catch (Exception $e) { $disclaimerText = "Ce site ne transige pas d'argent reel."; }

try {
    $adminCodeStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='admin_login_code'");
    $adminCodeStmt->execute();
    $adminCodeVal = $adminCodeStmt->fetchColumn();
    $adminCodeSet = !empty($adminCodeVal) && strlen($adminCodeVal) > 10;
} catch (Exception $e) { $adminCodeSet = false; }

try {
    $bmStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='block_media'");
    $bmStmt->execute();
    $blockMedia = (int)($bmStmt->fetchColumn() ?? 0);
} catch (Exception $e) { $blockMedia = 0; }


// ── Sauvegarder config marquise ─────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_marquee_config'])) {
    $fields = [
        'marquee_bg'      => trim($_POST['marquee_bg']      ?? '#0d0d0d'),
        'flash_enabled'   => isset($_POST['flash_enabled'])  ? '1' : '0',
        'flash_duration'  => max(2, min(15, (int)($_POST['flash_duration'] ?? 5))),
        'flash_delay'     => max(0, min(10, (int)($_POST['flash_delay']    ?? 2))),
    ];
    foreach ($fields as $k => $v) {
        $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES (?,?) ON DUPLICATE KEY UPDATE config_value=?")
            ->execute([$k, $v, $v]);
    }
    $msg = "Configuration marquise sauvegardée.";
}


// ── Lire config marquise ─────────────────────────────────────
$mCfg = [];
try {
    $mCfg = $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);
} catch (Exception $e) {}
$mBg       = $mCfg['marquee_bg']      ?? '#0d0d0d';
$mFlashOn  = ($mCfg['flash_enabled']  ?? '1') === '1';
$mDuration = (int)($mCfg['flash_duration'] ?? 5);
$mDelay    = (int)($mCfg['flash_delay']    ?? 2);

include 'header.php';
?>

<div class="container mt-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <div class="row justify-content-center">
        <div class="col-md-7">
            <h5 class="oracle-text text-warning mb-3">CONFIGURATION — POINTS ET PARAMETRES</h5>

            <?php if ($msg): ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>

            <div class="card bg-dark border-secondary shadow">
                <div class="card-header bg-secondary text-white py-2 fw-bold small"> VALEUR DES POINTS D'INTERACTION</div>
                <div class="card-body">
                    <form method="POST">
                        <table class="table table-dark table-sm small mb-3">
                            <thead>
                                <tr><th>Action</th><th class="text-center" style="width:120px;">Points</th></tr>
                            </thead>
                            <tbody>
                            <?php foreach ($configKeys as $key => $info): ?>
                            <tr>
                                <td class="text-white"><?= $info[0] ?></td>
                                <td>
                                    <input type="number" name="<?= $key ?>" class="form-control form-control-sm text-center"
                                           value="<?= $currentVals[$key] ?>" min="0" max="999">
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                        <div class="text-end">
                            <button type="submit" name="save_config" class="btn btn-warning fw-bold">ENREGISTRER</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Option bloquer photos/videos
$photoStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='block_media'");
$photoStmt->execute();
$blockMedia = (int)($photoStmt->fetchColumn() ?? 0);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_media'])) {
    $newVal = $blockMedia ? 0 : 1;
    $ex = $pdo->prepare("SELECT config_key FROM admin_config WHERE config_key='block_media'");
    $ex->execute();
    if ($ex->fetch()) $pdo->prepare("UPDATE admin_config SET config_value=? WHERE config_key='block_media'")->execute([$newVal]);
    else $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('block_media',?)")->execute([$newVal]);
    $blockMedia = $newVal;
    header("Location: admin_config.php"); exit;
}
?>

<div class="container mb-4">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card bg-dark border-<?= $blockMedia ? 'danger' : 'secondary' ?> shadow">
                <div class="card-header text-white py-2 fw-bold small">Medias (photos / videos)</div>
                <div class="card-body py-2">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="text-white small">Upload de photos dans le chat et les gages</div>
                            <div style="font-size:0.65rem;">
                                Statut : <span class="<?= $blockMedia ? 'text-danger' : 'text-success' ?> fw-bold">
                                    <?= $blockMedia ? 'BLOQUE' : 'AUTORISE' ?></span>
                            </div>
                        </div>
                        <form method="POST">
                            <button type="submit" name="toggle_media"
                                    class="btn <?= $blockMedia ? 'btn-success' : 'btn-danger' ?> btn-sm fw-bold"
                                    onclick="return confirm('<?= $blockMedia ? 'Autoriser' : 'Bloquer' ?> les medias ?')">
                                <?= $blockMedia ? 'Autoriser' : 'Bloquer' ?>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- DISCLAIMER CONFIGURABLE -->
<div class="container mb-4">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-white py-2 fw-bold small">Disclaimer (pied de page)</div>
                <div class="card-body">
                    <form method="POST">
                        <textarea name="disclaimer_text" class="form-control bg-dark text-white border-secondary mb-2" style="background-color:#212529!important;color:#fff!important;"
                                  rows="3"><?= htmlspecialchars($disclaimerText) ?></textarea>
                        <button type="submit" name="save_disclaimer" class="btn btn-warning btn-sm fw-bold">Sauvegarder</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- STRUCTURE BDD + NETTOYAGE -->
<div class="container mb-4">
    <div class="row justify-content-center g-3">

        <!-- STRUCTURE BDD -->
        <div class="col-md-7">
            <div class="card bg-dark border-info shadow">
                <div class="card-header text-info py-2 fw-bold small">
                    <i class="fa-solid fa-database fa-xs me-1"></i>Structure de la base de données
                </div>
                <div class="card-body py-2">
                    <p style="color:#aaa;font-size:0.72rem;">Exporter la structure complète (tables + champs) de la base de données.</p>
                    <div class="d-flex gap-2 flex-wrap">
                        <a href="admin_db_export.php?format=txt" class="btn btn-outline-info btn-sm fw-bold">
                            <i class="fa-solid fa-file-lines fa-xs me-1"></i>Télécharger .txt
                        </a>
                        <a href="admin_db_export.php?format=csv" class="btn btn-outline-warning btn-sm fw-bold">
                            <i class="fa-solid fa-file-csv fa-xs me-1"></i>Télécharger .csv
                        </a>
                        <a href="admin_db_export.php?format=xls" class="btn btn-outline-success btn-sm fw-bold">
                            <i class="fa-solid fa-file-excel fa-xs me-1"></i>Télécharger .xls
                        </a>
                        <a href="admin_db_export.php?format=view" class="btn btn-outline-secondary btn-sm fw-bold" target="_blank">
                            <i class="fa-solid fa-eye fa-xs me-1"></i>Voir en ligne
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- REMISE À ZÉRO COMPLÈTE -->
        <div class="col-12 mb-3">
            <div class="card bg-dark border-danger shadow" style="border-width:2px!important;">
                <div class="card-header py-2 fw-bold small" style="background:#1a0000;border-bottom:2px solid #dc3545;color:#dc3545;letter-spacing:1px;">
                    <i class="fa-solid fa-skull-crossbones fa-xs me-1"></i>REMISE À ZÉRO COMPLÈTE — BASE DE DONNÉES
                </div>
                <div class="card-body py-3">
                    <div class="row g-2">
                        <div class="col-md-8">
                            <div style="background:rgba(220,53,69,0.07);border:1px solid rgba(220,53,69,0.3);border-radius:6px;padding:10px;font-size:0.65rem;">
                                <div class="text-danger fw-bold mb-2" style="font-size:0.68rem;">⚠️ Sera effacé définitivement :</div>
                                <div class="row g-0" style="color:#bbb;">
                                    <div class="col-6">
                                        🗑️ Tous les gages + votes + preuves<br>
                                        🗑️ Messages chat + messages privés<br>
                                        🗑️ Toutes les notifications<br>
                                        🗑️ Tous les cercles et membres<br>
                                        🗑️ Toutes les relations d'amitié<br>
                                        🗑️ Signalements / bugs / Oracle
                                    </div>
                                    <div class="col-6">
                                        🗑️ Tous les usagers <span class="text-warning">(sauf admin)</span><br>
                                        🗑️ Stats, trophées gagnés, wallet<br>
                                        🗑️ Tentatives connexion<br>
                                        🗑️ Tokens reset mot de passe<br>
                                        🗑️ Demandes de cercles<br>
                                        🗑️ Ventes boutique
                                    </div>
                                </div>
                                <div class="mt-2 pt-2" style="border-top:1px solid rgba(220,53,69,0.2);color:#28a745;font-size:0.6rem;">
                                    ✅ Conservé : config, apparence, mots-clés, règles gages, définitions trophées, boutique (items), forfaits, événements, templates courriels, icônes chat, marquise, commanditaires, notes admin
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 d-flex flex-column justify-content-center">
                            <div id="reset-zone">
                                <button onclick="resetStart()" class="btn btn-danger fw-bold w-100">
                                    <i class="fa-solid fa-skull-crossbones me-1"></i>REMETTRE À ZÉRO
                                </button>
                            </div>
                            <div id="reset-confirm" style="display:none;">
                                <div style="font-size:0.68rem;color:#ffc107;margin-bottom:6px;">Tapez <strong>RESET</strong> pour confirmer :</div>
                                <div class="d-flex gap-2 mb-2">
                                    <input type="text" id="reset-input" placeholder="RESET"
                                           class="form-control form-control-sm bg-black text-white border-danger"
                                           style="font-size:0.8rem;font-weight:700;text-transform:uppercase;letter-spacing:3px;"
                                           oninput="resetCheckInput(this.value)">
                                    <button onclick="resetCancel()" class="btn btn-outline-secondary btn-sm">✕</button>
                                </div>
                                <button id="reset-confirm-btn" onclick="resetExecute()" disabled
                                        class="btn btn-danger btn-sm fw-bold w-100" style="opacity:0.4;">
                                    ☠️ CONFIRMER
                                </button>
                            </div>
                            <div id="reset-result" style="display:none;margin-top:10px;font-size:0.6rem;max-height:200px;overflow-y:auto;background:#0a0a0a;border:1px solid #333;border-radius:6px;padding:8px;line-height:1.8;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- EFFACER TOUS LES GAGES -->
        <div class="col-md-5">
            <div class="card bg-dark border-danger shadow">
                <div class="card-header text-danger py-2 fw-bold small">
                    <i class="fa-solid fa-trash-can fa-xs me-1"></i>Remise à zéro — Gages
                </div>
                <div class="card-body py-2">
                    <p style="color:#aaa;font-size:0.72rem;">Efface <strong style="color:#dc3545;">tous les gages</strong> du site. Action irréversible — à utiliser avant l'ouverture officielle.</p>
                    <?php
                    $purgeStep = $_SESSION['purge_bets_step'] ?? 0;
                    if ($purgeStep === 2) {
                        // Étape 3: attendre "oui" tapé
                    }
                    ?>
                    <div id="purge-zone">
                        <button onclick="purgeStart()" class="btn btn-outline-danger btn-sm fw-bold w-100" id="purge-btn1">
                            <i class="fa-solid fa-skull-crossbones fa-xs me-1"></i>Effacer tous les gages
                        </button>
                    </div>

                    <!-- Confirmation JS en 2 étapes -->
                    <div id="purge-confirm" style="display:none;margin-top:8px;">
                        <div style="background:rgba(220,53,69,0.12);border:1px solid #dc3545;border-radius:6px;padding:10px;margin-bottom:8px;">
                            <div style="font-size:0.72rem;color:#dc3545;font-weight:700;margin-bottom:4px;">⚠️ ATTENTION — ACTION IRRÉVERSIBLE</div>
                            <div style="font-size:0.68rem;color:#aaa;">Cette action supprimera définitivement <strong style="color:#fff;">tous les gages</strong>, les votes et les preuves photos associées.</div>
                        </div>
                        <div style="font-size:0.7rem;color:#ffc107;margin-bottom:6px;">Pour confirmer, tapez <strong>OUI</strong> ci-dessous :</div>
                        <div class="d-flex gap-2">
                            <input type="text" id="purge-input" placeholder="Tapez OUI..."
                                   class="form-control form-control-sm bg-black text-white border-danger"
                                   style="font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:2px;"
                                   oninput="purgeCheckInput(this.value)">
                            <button onclick="purgeCancel()" class="btn btn-outline-secondary btn-sm">✕</button>
                        </div>
                        <button id="purge-confirm-btn" onclick="purgeExecute()" disabled
                                class="btn btn-danger btn-sm fw-bold w-100 mt-2" style="opacity:0.4;">
                            <i class="fa-solid fa-trash-can fa-xs me-1"></i>Confirmer la suppression
                        </button>
                        <div id="purge-result" style="display:none;margin-top:8px;font-size:0.7rem;"></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
function purgeStart() {
    document.getElementById('purge-btn1').style.display = 'none';
    document.getElementById('purge-confirm').style.display = 'block';
    setTimeout(() => document.getElementById('purge-input').focus(), 100);
}
function purgeCancel() {
    document.getElementById('purge-btn1').style.display = 'block';
    document.getElementById('purge-confirm').style.display = 'none';
    document.getElementById('purge-input').value = '';
    document.getElementById('purge-confirm-btn').disabled = true;
    document.getElementById('purge-confirm-btn').style.opacity = '0.4';
}
function purgeCheckInput(val) {
    const ok = val.trim().toUpperCase() === 'OUI';
    const btn = document.getElementById('purge-confirm-btn');
    btn.disabled = !ok;
    btn.style.opacity = ok ? '1' : '0.4';
}
function purgeExecute() {
    const btn = document.getElementById('purge-confirm-btn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-1"></i>Suppression...';
    fetch('admin_purge_bets.php', {method:'POST'})
        .then(r => r.json())
        .then(data => {
            const res = document.getElementById('purge-result');
            res.style.display = 'block';
            if (data.ok) {
                res.innerHTML = '<span style="color:#28a745;"><i class="fa-solid fa-circle-check me-1"></i>'+ data.count +' gage(s) supprimé(s) avec succès.</span>';
                document.getElementById('purge-confirm').querySelector('.d-flex').style.display = 'none';
                btn.style.display = 'none';
            } else {
                res.innerHTML = '<span style="color:#dc3545;">Erreur: ' + (data.error||'Inconnue') + '</span>';
                btn.disabled = false;
                btn.innerHTML = 'Réessayer';
            }
        })
        .catch(() => {
            btn.disabled = false;
            btn.innerHTML = 'Réessayer';
        });
}

// ── REMISE À ZÉRO COMPLÈTE ────────────────────────────────────
function resetStart() {
    document.getElementById('reset-zone').style.display = 'none';
    document.getElementById('reset-confirm').style.display = 'block';
    setTimeout(() => document.getElementById('reset-input').focus(), 100);
}
function resetCancel() {
    document.getElementById('reset-zone').style.display = 'block';
    document.getElementById('reset-confirm').style.display = 'none';
    document.getElementById('reset-input').value = '';
    document.getElementById('reset-confirm-btn').disabled = true;
    document.getElementById('reset-confirm-btn').style.opacity = '0.4';
}
function resetCheckInput(val) {
    const ok = val.trim().toUpperCase() === 'RESET';
    const btn = document.getElementById('reset-confirm-btn');
    btn.disabled = !ok;
    btn.style.opacity = ok ? '1' : '0.4';
}
function resetExecute() {
    const btn = document.getElementById('reset-confirm-btn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-1"></i>Remise à zéro en cours...';
    const res = document.getElementById('reset-result');
    res.style.display = 'block';
    res.innerHTML = '<span style="color:#ffc107;">⏳ Opération en cours, ne fermez pas cette page...</span>';

    fetch('admin_reset_complet.php', {method: 'POST'})
        .then(r => r.json())
        .then(data => {
            if (data.ok) {
                let html = '<div style="color:#28a745;font-weight:bold;margin-bottom:6px;">✅ Remise à zéro terminée — Admin conservé (ID:' + data.admin + ')</div>';
                (data.log || []).forEach(line => {
                    const color = line.startsWith('✅') ? '#28a745' : line.startsWith('⚠️') ? '#ffc107' : '#dc3545';
                    html += '<div style="color:' + color + ';">' + line + '</div>';
                });
                html += '<div style="color:#0dcaf0;font-weight:bold;margin-top:8px;">🔄 Rechargement dans 3 secondes...</div>';
                res.innerHTML = html;
                document.getElementById('reset-confirm').style.display = 'none';
                setTimeout(() => window.location.href = 'admin_config.php', 3000);
            } else {
                res.innerHTML = '<span style="color:#dc3545;">❌ Erreur : ' + (data.error || 'Inconnue') + '</span>';
                btn.disabled = false;
                btn.innerHTML = '☠️ Réessayer';
            }
        })
        .catch(() => {
            res.innerHTML = '<span style="color:#dc3545;">❌ Erreur réseau. Vérifiez la console.</span>';
            btn.disabled = false;
            btn.innerHTML = '☠️ Réessayer';
        });
}
</script>

<!-- CONFIGURATION MARQUISE -->
<div class="container mb-4">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card bg-dark border-warning shadow">
                <div class="card-header py-2 fw-bold small" style="background:#1a1200;border-bottom:1px solid #3a2a00;color:#ffc107;">
                    <i class="fa-solid fa-scroll fa-xs me-2"></i>MARQUISE DÉFILANTE — CONFIGURATION
                </div>
                <div class="card-body">
                    <form method="POST">
                        <div class="row g-3">
                            <!-- Couleur de fond -->
                            <div class="col-6">
                                <label class="small text-muted mb-1" style="font-size:0.68rem;">COULEUR FOND</label>
                                <div class="d-flex gap-2 align-items-center">
                                    <input type="color" name="marquee_bg" value="<?= htmlspecialchars($mBg) ?>"
                                           class="form-control form-control-color form-control-sm border-secondary"
                                           style="width:50px;height:32px;padding:2px;background:#111;">
                                    <input type="text" id="mBgHex" value="<?= htmlspecialchars($mBg) ?>"
                                           class="form-control form-control-sm bg-dark text-white border-secondary"
                                           style="font-family:monospace;max-width:100px;"
                                           oninput="document.querySelector('[name=marquee_bg]').value=this.value">
                                </div>
                                <script>
                                document.querySelector('[name=marquee_bg]').addEventListener('input', function() {
                                    document.getElementById('mBgHex').value = this.value;
                                });
                                </script>
                            </div>

                            <!-- Aperçu -->
                            <div class="col-6 d-flex align-items-end">
                                <div id="marqueePreview" style="width:100%;height:32px;border-radius:4px;border:1px solid #333;background:<?= htmlspecialchars($mBg) ?>;display:flex;align-items:center;padding:0 10px;">
                                    <span style="font-size:0.65rem;color:#ffc107;font-weight:700;font-family:'Orbitron',sans-serif;">Aperçu de la marquise</span>
                                </div>
                                <script>
                                document.querySelector('[name=marquee_bg]').addEventListener('input', function() {
                                    document.getElementById('marqueePreview').style.background = this.value;
                                });
                                </script>
                            </div>

                            <!-- Flash activé -->
                            <div class="col-12">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" name="flash_enabled" id="flashEnabled" value="1" <?= $mFlashOn?'checked':'' ?>>
                                    <label class="form-check-label small text-warning" for="flashEnabled" style="font-size:0.72rem;">
                                        Activer le flash alerte (notification, trophée, nouveau gage)
                                    </label>
                                </div>
                            </div>

                            <!-- Délai avant flash -->
                            <div class="col-4">
                                <label class="small text-muted mb-1" style="font-size:0.65rem;">DÉLAI AVANT (sec)</label>
                                <input type="number" name="flash_delay" value="<?= $mDelay ?>" min="0" max="10"
                                       class="form-control form-control-sm bg-dark text-white border-secondary">
                                <small class="text-muted" style="font-size:0.58rem;">Délai après l'event</small>
                            </div>

                            <!-- Durée du flash -->
                            <div class="col-4">
                                <label class="small text-muted mb-1" style="font-size:0.65rem;">DURÉE (sec)</label>
                                <input type="number" name="flash_duration" value="<?= $mDuration ?>" min="2" max="15"
                                       class="form-control form-control-sm bg-dark text-white border-secondary">
                                <small class="text-muted" style="font-size:0.58rem;">Durée affichage</small>
                            </div>

                            <!-- Test -->
                            <div class="col-4 d-flex align-items-end">
                                <button type="button" onclick="(function(){ const bar=document.getElementById('marqueeFlash'),inner=document.getElementById('marqueeFlashInner'); if(!bar||!inner){alert('Div flash introuvable!');return;} 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:#1a1000;border-bottom:2px solid #ffc107;'; inner.style.cssText='display:inline-block;font-size:18px;font-weight:900;color:#ffc107;letter-spacing:2px;font-family:Orbitron,sans-serif;padding:0 2rem;animation:marquee-scroll 5s linear forwards;'; inner.textContent='⚡ TEST FLASH — NOTIFICATION ! ⚡'; setTimeout(()=>{bar.style.display='none';inner.textContent='';},6000); })()"
                                        class="btn btn-outline-warning btn-sm w-100 fw-bold" style="font-size:0.68rem;">
                                    ▶ Tester le flash
                                </button>
                            </div>
                        </div>

                        <div class="mt-3">
                            <button type="submit" name="save_marquee_config" class="btn btn-warning btn-sm fw-bold">
                                <i class="fa-solid fa-floppy-disk fa-xs me-1"></i>Enregistrer
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- CODE DOUBLE VERIFICATION ADMIN -->
<div class="container mb-4">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card bg-dark border-danger shadow">
                <div class="card-header text-danger py-2 fw-bold small">Code de vérification Admin</div>
                <div class="card-body">
                    <p style="color:#aaa;font-size:0.72rem;">Si configuré, les admins devront entrer ce code en plus de leur mot de passe.</p>
                    <span class="badge <?= $adminCodeSet ? 'bg-success' : 'bg-secondary' ?> mb-2">
                        <?= $adminCodeSet ? 'Code actif' : 'Aucun code configuré' ?>
                    </span>
                    <form method="POST" class="mt-2">
                        <div class="input-group input-group-sm">
                            <input type="password" name="admin_code" class="form-control bg-dark text-white border-secondary"
                                   placeholder="Nouveau code (min 4 car.)" autocomplete="new-password">
                            <button type="submit" name="save_admin_code" class="btn btn-danger fw-bold">Définir</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
