<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

// Créer tables si besoin
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS bet_keywords (
        id INT AUTO_INCREMENT PRIMARY KEY,
        keyword VARCHAR(100) NOT NULL,
        category VARCHAR(50) NOT NULL,
        subcategory VARCHAR(50) NOT NULL,
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_kw (keyword)
    )");
    try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS bet_category VARCHAR(50) DEFAULT NULL"); } catch(Exception $e){}
    try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS bet_subcategory VARCHAR(50) DEFAULT NULL"); } catch(Exception $e){}
} catch (Exception $e) {}

$msg = ''; $err = '';

// --- AJOUTER ---
if (isset($_POST['action']) && $_POST['action'] === 'add') {
    $kw   = trim(strtolower($_POST['keyword'] ?? ''));
    $cat  = trim($_POST['category'] ?? '');
    $sub  = trim($_POST['subcategory'] ?? '');
    if (strlen($kw) < 2)    $err = "Le mot-clé doit faire au moins 2 caractères.";
    elseif (empty($cat))    $err = "La catégorie est obligatoire.";
    elseif (empty($sub))    $err = "La sous-catégorie est obligatoire.";
    else {
        try {
            $pdo->prepare("INSERT INTO bet_keywords (keyword, category, subcategory) VALUES (?,?,?) ON DUPLICATE KEY UPDATE category=?, subcategory=?, active=1")
                ->execute([$kw, $cat, $sub, $cat, $sub]);
            $msg = "✅ Mot-clé « {$kw} » ajouté → {$cat} / {$sub}";
        } catch (Exception $e) { $err = "Erreur : " . $e->getMessage(); }
    }
}

// --- MODIFIER ---
if (isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id  = (int)$_POST['id'];
    $kw  = trim(strtolower($_POST['keyword'] ?? ''));
    $cat = trim($_POST['category'] ?? '');
    $sub = trim($_POST['subcategory'] ?? '');
    $active = isset($_POST['active']) ? 1 : 0;
    if (strlen($kw) < 2) $err = "Le mot-clé doit faire au moins 2 caractères.";
    elseif (empty($cat)) $err = "La catégorie est obligatoire.";
    elseif (empty($sub)) $err = "La sous-catégorie est obligatoire.";
    else {
        try {
            $pdo->prepare("UPDATE bet_keywords SET keyword=?, category=?, subcategory=?, active=? WHERE id=?")
                ->execute([$kw, $cat, $sub, $active, $id]);
            $msg = "✅ Mot-clé mis à jour.";
        } catch (Exception $e) { $err = "Erreur : " . $e->getMessage(); }
    }
}

// --- SUPPRIMER ---
if (isset($_GET['delete'])) {
    try { $pdo->prepare("DELETE FROM bet_keywords WHERE id=?")->execute([(int)$_GET['delete']]); $msg = "🗑️ Supprimé."; }
    catch (Exception $e) { $err = "Erreur suppression."; }
}

// --- TOGGLE ---
if (isset($_GET['toggle'])) {
    try { $pdo->prepare("UPDATE bet_keywords SET active = 1 - active WHERE id=?")->execute([(int)$_GET['toggle']]); header("Location: admin_bet_keywords.php"); exit; }
    catch (Exception $e) {}
}

// --- RECLASSIFIER TOUS LES GAGES EXISTANTS ---
if (isset($_POST['action']) && $_POST['action'] === 'reclassify') {
    $bets = $pdo->query("SELECT id, description FROM bets")->fetchAll();
    $count = 0;
    foreach ($bets as $b) {
        $result = detectBetCategory($b['description'], $pdo);
        $cat = $result['category'] ?? null;
        $sub = $result['subcategory'] ?? null;
        $pdo->prepare("UPDATE bets SET bet_category=?, bet_subcategory=? WHERE id=?")->execute([$cat, $sub, $b['id']]);
        if ($result) $count++;
    }
    $msg = "✅ {$count} gage(s) classifié(s) sur " . count($bets) . " au total.";
}

// Charger données
$keywords = $pdo->query("SELECT * FROM bet_keywords ORDER BY category ASC, subcategory ASC, keyword ASC")->fetchAll();

// Catégories existantes pour l'autocomplete
$existingCats = array_unique(array_column($keywords, 'category'));
$existingSubs = array_unique(array_column($keywords, 'subcategory'));

// Statistiques de classification
try {
    $statsTotal = (int)$pdo->query("SELECT COUNT(*) FROM bets")->fetchColumn();
    $statsClassified = (int)$pdo->query("SELECT COUNT(*) FROM bets WHERE bet_category IS NOT NULL")->fetchColumn();
    $statsByCat = $pdo->query("SELECT bet_category, bet_subcategory, COUNT(*) as cnt FROM bets WHERE bet_category IS NOT NULL GROUP BY bet_category, bet_subcategory ORDER BY cnt DESC")->fetchAll();
} catch (Exception $e) { $statsTotal = $statsClassified = 0; $statsByCat = []; }

// Mot en édition
$editKw = null;
if (isset($_GET['edit'])) {
    foreach ($keywords as $k) { if ($k['id'] == (int)$_GET['edit']) { $editKw = $k; break; } }
}

// Grouper par catégorie pour l'affichage
$grouped = [];
foreach ($keywords as $kw) { $grouped[$kw['category']][$kw['subcategory']][] = $kw; }

$currentPage = 'admin_bet_keywords.php';
include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container mt-4 mb-5">

    <!-- En-tête -->
    <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
        <div>
            <h5 class="text-warning mb-0 fw-bold" style="letter-spacing:1px;">
                <i class="fa-solid fa-tags me-2"></i>CLASSIFICATION DES GAGES
            </h5>
            <small class="text-muted">Mots-clés qui détectent automatiquement la catégorie et sous-catégorie d'un gage</small>
        </div>
        <a href="admin_config.php" class="btn btn-outline-secondary btn-sm">← Config</a>
    </div>

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

    <div class="row g-3">

        <!-- Colonne gauche : formulaire + stats -->
        <div class="col-md-4">

            <!-- Formulaire ajout/édition -->
            <div class="card bg-dark border-warning mb-3">
                <div class="card-header py-2" style="background:#050520;border-bottom:1px solid #ffc107;">
                    <span class="text-warning fw-bold" style="font-size:0.72rem;letter-spacing:1px;">
                        <?= $editKw ? '✏️ MODIFIER' : '➕ AJOUTER UN MOT-CLÉ' ?>
                    </span>
                </div>
                <div class="card-body p-3">
                    <form method="POST">
                        <input type="hidden" name="action" value="<?= $editKw ? 'edit' : 'add' ?>">
                        <?php if ($editKw): ?>
                        <input type="hidden" name="id" value="<?= $editKw['id'] ?>">
                        <?php endif; ?>

                        <div class="mb-2">
                            <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">MOT-CLÉ DÉTECTÉ</label>
                            <input type="text" name="keyword" id="kwInput"
                                   class="form-control form-control-sm bg-dark text-white border-secondary"
                                   placeholder="ex: canadien, lnh, hockey..."
                                   value="<?= htmlspecialchars($editKw['keyword'] ?? '') ?>"
                                   required maxlength="100" autocomplete="off">
                            <div class="text-muted mt-1" style="font-size:0.6rem;">Insensible à la casse. Correspond aux mots entiers.</div>
                        </div>

                        <div class="mb-2">
                            <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">CATÉGORIE</label>
                            <input type="text" name="category" id="catInput"
                                   class="form-control form-control-sm bg-dark text-white border-secondary"
                                   placeholder="ex: Sport, Politique, Arts..."
                                   value="<?= htmlspecialchars($editKw['category'] ?? '') ?>"
                                   required maxlength="50" autocomplete="off"
                                   list="catList">
                            <datalist id="catList">
                                <?php foreach ($existingCats as $c): ?>
                                <option value="<?= htmlspecialchars($c) ?>">
                                <?php endforeach; ?>
                            </datalist>
                        </div>

                        <div class="mb-2">
                            <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">SOUS-CATÉGORIE</label>
                            <input type="text" name="subcategory" id="subInput"
                                   class="form-control form-control-sm bg-dark text-white border-secondary"
                                   placeholder="ex: Hockey, Football, Tennis..."
                                   value="<?= htmlspecialchars($editKw['subcategory'] ?? '') ?>"
                                   required maxlength="50" autocomplete="off"
                                   list="subList">
                            <datalist id="subList">
                                <?php foreach ($existingSubs as $s): ?>
                                <option value="<?= htmlspecialchars($s) ?>">
                                <?php endforeach; ?>
                            </datalist>
                        </div>

                        <?php if ($editKw): ?>
                        <div class="mb-2 form-check">
                            <input type="checkbox" name="active" class="form-check-input" id="activeCheck"
                                   <?= $editKw['active'] ? 'checked' : '' ?>>
                            <label class="form-check-label text-white small" for="activeCheck" style="font-size:0.65rem;">Actif</label>
                        </div>
                        <?php endif; ?>

                        <div class="d-flex gap-2 mt-3">
                            <button type="submit" class="btn btn-warning btn-sm fw-bold flex-grow-1" style="color:#000;">
                                <?= $editKw ? 'ENREGISTRER' : 'AJOUTER' ?>
                            </button>
                            <?php if ($editKw): ?>
                            <a href="admin_bet_keywords.php" class="btn btn-outline-secondary btn-sm">Annuler</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Statistiques -->
            <div class="card bg-dark border-secondary mb-3">
                <div class="card-header py-2" style="background:#050520;">
                    <span class="text-white fw-bold" style="font-size:0.7rem;">📊 STATISTIQUES</span>
                </div>
                <div class="card-body p-3">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted small" style="font-size:0.65rem;">Gages classifiés</span>
                        <span class="text-warning fw-bold small"><?= $statsClassified ?> / <?= $statsTotal ?></span>
                    </div>
                    <?php if ($statsTotal > 0): ?>
                    <div class="progress mb-3" style="height:4px;">
                        <div class="progress-bar bg-warning" style="width:<?= round($statsClassified/$statsTotal*100) ?>%;"></div>
                    </div>
                    <?php endif; ?>
                    <?php foreach ($statsByCat as $s): ?>
                    <div class="d-flex justify-content-between align-items-center mb-1">
                        <div style="font-size:0.6rem;">
                            <span class="text-warning"><?= htmlspecialchars($s['bet_category']) ?></span>
                            <span class="text-muted"> · <?= htmlspecialchars($s['bet_subcategory']) ?></span>
                        </div>
                        <span class="badge bg-secondary" style="font-size:0.55rem;"><?= $s['cnt'] ?></span>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($statsByCat)): ?>
                    <div class="text-muted text-center" style="font-size:0.62rem;">Aucun gage classifié pour l'instant.</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Reclassifier les gages existants -->
            <div class="card bg-dark border-secondary">
                <div class="card-body p-3">
                    <div class="text-white fw-bold mb-1" style="font-size:0.7rem;">🔄 RECLASSIFIER</div>
                    <div class="text-muted mb-2" style="font-size:0.62rem;">
                        Applique les mots-clés actuels sur tous les gages existants en BD.
                    </div>
                    <form method="POST">
                        <input type="hidden" name="action" value="reclassify">
                        <button type="submit" class="btn btn-outline-warning btn-sm w-100"
                                onclick="return confirm('Reclassifier tous les gages existants ?')"
                                style="font-size:0.65rem;">
                            Lancer la reclassification
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Colonne droite : liste groupée par catégorie -->
        <div class="col-md-8">

            <!-- Barre de recherche + test -->
            <div class="card bg-dark border-secondary mb-3">
                <div class="card-body p-3">
                    <div class="row g-2">
                        <div class="col-6">
                            <input type="text" id="searchKw" oninput="filterKw(this.value)"
                                   class="form-control form-control-sm bg-dark text-white border-secondary"
                                   placeholder="🔍 Rechercher un mot-clé..." style="font-size:0.65rem;">
                        </div>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <input type="text" id="testKwInput"
                                       class="form-control bg-dark text-white border-secondary"
                                       placeholder="🧪 Tester une phrase..." style="font-size:0.65rem;">
                                <button onclick="testKw()" class="btn btn-outline-warning" style="font-size:0.6rem;">Tester</button>
                            </div>
                        </div>
                    </div>
                    <div id="testKwResult" style="display:none;font-size:0.65rem;margin-top:6px;padding:6px 10px;background:#0a0a1a;border-radius:4px;"></div>
                </div>
            </div>

            <?php if (empty($grouped)): ?>
            <div class="card bg-dark border-secondary">
                <div class="card-body text-center text-muted py-5 small">
                    <i class="fa-solid fa-tags fa-2x mb-2 d-block opacity-25"></i>
                    Aucun mot-clé configuré.<br>Ajoutez-en un à gauche.
                </div>
            </div>
            <?php else: ?>
            <?php foreach ($grouped as $cat => $subs): ?>
            <div class="card bg-dark border-secondary mb-3 kw-group" data-cat="<?= htmlspecialchars(strtolower($cat)) ?>">
                <div class="card-header py-2 d-flex align-items-center justify-content-between" style="background:#0a0a1a;">
                    <span class="fw-bold text-warning" style="font-size:0.72rem;letter-spacing:1px;">
                        <i class="fa-solid fa-folder-open me-1"></i><?= htmlspecialchars(strtoupper($cat)) ?>
                    </span>
                    <span class="badge bg-warning text-dark" style="font-size:0.55rem;">
                        <?= array_sum(array_map('count', $subs)) ?> mots-clés
                    </span>
                </div>
                <div class="card-body p-2">
                    <?php foreach ($subs as $sub => $kws): ?>
                    <div class="mb-2">
                        <div class="text-info fw-bold mb-1" style="font-size:0.62rem;letter-spacing:0.5px;">
                            <i class="fa-solid fa-chevron-right fa-xs me-1"></i><?= htmlspecialchars($sub) ?>
                        </div>
                        <div class="d-flex flex-wrap gap-1 ps-2">
                            <?php foreach ($kws as $kw): ?>
                            <div class="kw-item d-flex align-items-center gap-1"
                                 data-kw="<?= htmlspecialchars(strtolower($kw['keyword'])) ?>"
                                 style="background:<?= $kw['active'] ? 'rgba(255,193,7,0.08)' : 'rgba(100,100,100,0.08)' ?>;border:1px solid <?= $kw['active'] ? 'rgba(255,193,7,0.3)' : '#333' ?>;border-radius:12px;padding:2px 8px;">
                                <code style="font-size:0.6rem;color:<?= $kw['active'] ? '#ffc107' : '#666' ?>;"><?= htmlspecialchars($kw['keyword']) ?></code>
                                <a href="?edit=<?= $kw['id'] ?>" title="Modifier" style="color:#888;font-size:0.55rem;text-decoration:none;">✏️</a>
                                <a href="?toggle=<?= $kw['id'] ?>" title="<?= $kw['active'] ? 'Désactiver' : 'Activer' ?>" style="color:#888;font-size:0.55rem;text-decoration:none;"><?= $kw['active'] ? '🟢' : '⚫' ?></a>
                                <a href="?delete=<?= $kw['id'] ?>" onclick="return confirm('Supprimer « <?= htmlspecialchars(addslashes($kw['keyword'])) ?> » ?')" title="Supprimer" style="color:#888;font-size:0.55rem;text-decoration:none;">🗑️</a>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Données JS pour test côté client
const kwData = [
    <?php foreach ($keywords as $kw): ?>
    { keyword: <?= json_encode(strtolower($kw['keyword'])) ?>, category: <?= json_encode($kw['category']) ?>, subcategory: <?= json_encode($kw['subcategory']) ?>, active: <?= $kw['active'] ? 'true' : 'false' ?> },
    <?php endforeach; ?>
];

// Trier par longueur décroissante (comme PHP)
kwData.sort((a, b) => b.keyword.length - a.keyword.length);

function testKw() {
    const text = document.getElementById('testKwInput').value.toLowerCase();
    if (!text.trim()) return;
    let found = null;
    for (const kw of kwData) {
        if (!kw.active) continue;
        const regex = new RegExp('\\b' + kw.keyword.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + '\\b', 'iu');
        if (regex.test(text)) { found = kw; break; }
    }
    const div = document.getElementById('testKwResult');
    div.style.display = 'block';
    div.innerHTML = found
        ? `✅ Détecté : <span class="text-warning fw-bold">${found.keyword}</span> → <span class="text-info">${found.category}</span> / <span class="text-white">${found.subcategory}</span>`
        : `<span class="text-muted">Aucune correspondance trouvée.</span>`;
}

document.getElementById('testKwInput').addEventListener('keypress', e => { if (e.key === 'Enter') testKw(); });

// Filtrer les mots-clés affichés
function filterKw(q) {
    q = q.toLowerCase().trim();
    document.querySelectorAll('.kw-item').forEach(el => {
        el.style.display = (!q || el.dataset.kw.includes(q)) ? '' : 'none';
    });
    // Cacher les groupes vides
    document.querySelectorAll('.kw-group').forEach(grp => {
        const visible = [...grp.querySelectorAll('.kw-item')].some(el => el.style.display !== 'none');
        grp.style.display = visible || !q ? '' : 'none';
    });
}

// Pré-remplir sous-catégorie selon catégorie connue
const catSubMap = {};
kwData.forEach(kw => {
    if (!catSubMap[kw.category]) catSubMap[kw.category] = new Set();
    catSubMap[kw.category].add(kw.subcategory);
});
</script>

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