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

// Créer la table si besoin
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS bad_words (
        id INT AUTO_INCREMENT PRIMARY KEY,
        word VARCHAR(100) NOT NULL,
        replacement VARCHAR(20) DEFAULT '***',
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_word (word)
    )");
} catch (Exception $e) {}

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

// --- AJOUTER ---
if (isset($_POST['action']) && $_POST['action'] === 'add') {
    $word = trim(strtolower($_POST['word'] ?? ''));
    $repl = trim($_POST['replacement'] ?? '***');
    if (strlen($word) < 2) {
        $err = "Le mot doit faire au moins 2 caractères.";
    } else {
        try {
            $pdo->prepare("INSERT INTO bad_words (word, replacement) VALUES (?, ?) ON DUPLICATE KEY UPDATE replacement=?, active=1")
                ->execute([$word, $repl, $repl]);
            $msg = "✅ Mot « {$word} » ajouté.";
        } catch (Exception $e) { $err = "Erreur : " . $e->getMessage(); }
    }
}

// --- MODIFIER ---
if (isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id   = (int)$_POST['id'];
    $word = trim(strtolower($_POST['word'] ?? ''));
    $repl = trim($_POST['replacement'] ?? '***');
    $active = isset($_POST['active']) ? 1 : 0;
    if (strlen($word) < 2) {
        $err = "Le mot doit faire au moins 2 caractères.";
    } else {
        try {
            $pdo->prepare("UPDATE bad_words SET word=?, replacement=?, active=? WHERE id=?")
                ->execute([$word, $repl, $active, $id]);
            $msg = "✅ Mot mis à jour.";
        } catch (Exception $e) { $err = "Erreur : " . $e->getMessage(); }
    }
}

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

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

// Charger la liste
$words = $pdo->query("SELECT * FROM bad_words ORDER BY word ASC")->fetchAll();

// Mot en cours d'édition
$editWord = null;
if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    foreach ($words as $w) { if ($w['id'] === $editId) { $editWord = $w; break; } }
}

$currentPage = 'admin_bad_words.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-info mb-0 fw-bold" style="letter-spacing:1px;">
                <i class="fa-solid fa-filter me-2"></i>FILTRE DE MOTS
            </h5>
            <small class="text-muted">Mots remplacés automatiquement dans les gages, le chat et les profils</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"><?= $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 ajout / édition -->
        <div class="col-md-4">
            <div class="card bg-dark border-info">
                <div class="card-header py-2" style="background:#050520;border-bottom:1px solid #0dcaf0;">
                    <span class="text-info fw-bold" style="font-size:0.72rem;letter-spacing:1px;">
                        <?= $editWord ? '✏️ MODIFIER LE MOT' : '➕ AJOUTER UN MOT' ?>
                    </span>
                </div>
                <div class="card-body p-3">
                    <form method="POST">
                        <input type="hidden" name="action" value="<?= $editWord ? 'edit' : 'add' ?>">
                        <?php if ($editWord): ?>
                        <input type="hidden" name="id" value="<?= $editWord['id'] ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">MOT À FILTRER</label>
                            <input type="text" name="word" class="form-control form-control-sm bg-dark text-white border-secondary"
                                   placeholder="ex: maudit, tabarnac..."
                                   value="<?= htmlspecialchars($editWord['word'] ?? '') ?>"
                                   required maxlength="100">
                            <div class="text-muted mt-1" style="font-size:0.6rem;">Insensible à la casse. Correspond aux mots entiers seulement.</div>
                        </div>

                        <div class="mb-3">
                            <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">REMPLACEMENT</label>
                            <input type="text" name="replacement" class="form-control form-control-sm bg-dark text-white border-secondary"
                                   placeholder="*** ou 😶 ou #@!%"
                                   value="<?= htmlspecialchars($editWord['replacement'] ?? '***') ?>"
                                   maxlength="20">
                            <div class="d-flex gap-1 mt-2 flex-wrap">
                                <?php foreach (['***','😶','#@!%','[censuré]','🤐'] as $opt): ?>
                                <button type="button" onclick="document.querySelector('[name=replacement]').value='<?= $opt ?>'"
                                        class="btn btn-xs btn-outline-secondary py-0" style="font-size:0.6rem;"><?= $opt ?></button>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <?php if ($editWord): ?>
                        <div class="mb-3 form-check">
                            <input type="checkbox" name="active" class="form-check-input" id="activeCheck"
                                   <?= $editWord['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">
                            <button type="submit" class="btn btn-info btn-sm fw-bold flex-grow-1">
                                <?= $editWord ? 'ENREGISTRER' : 'AJOUTER' ?>
                            </button>
                            <?php if ($editWord): ?>
                            <a href="admin_bad_words.php" class="btn btn-outline-secondary btn-sm">Annuler</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Info zones filtrées -->
            <div class="card bg-dark border-secondary mt-3">
                <div class="card-body p-3">
                    <div class="text-warning fw-bold mb-2" style="font-size:0.65rem;">📍 ZONES FILTRÉES</div>
                    <div class="text-muted small" style="font-size:0.62rem;">
                        <div class="mb-1">✅ Description des gages</div>
                        <div class="mb-1">✅ Messages du chat</div>
                        <div class="mb-1">✅ Profil utilisateur (bio)</div>
                    </div>
                    <hr class="border-secondary my-2">
                    <div class="text-muted" style="font-size:0.6rem;">
                        Le filtre s'applique à l'<strong class="text-white">affichage seulement</strong>.
                        Le texte original est conservé en base de données.
                    </div>
                </div>
            </div>
        </div>

        <!-- Colonne droite : liste des mots -->
        <div class="col-md-8">
            <div class="card bg-dark border-secondary">
                <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#050520;">
                    <span class="text-white fw-bold" style="font-size:0.72rem;letter-spacing:1px;">
                        LISTE DES MOTS (<?= count($words) ?>)
                    </span>
                    <input type="text" id="searchWords" oninput="filterWords(this.value)"
                           class="form-control form-control-sm bg-dark text-white border-secondary"
                           placeholder="🔍 Rechercher..." style="width:160px;font-size:0.65rem;">
                </div>
                <div class="card-body p-0">
                    <?php if (empty($words)): ?>
                    <div class="text-center text-muted py-4 small">
                        <i class="fa-solid fa-list-check fa-2x mb-2 d-block opacity-25"></i>
                        Aucun mot filtré pour l'instant.<br>Ajoutez-en un à gauche.
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover mb-0" style="font-size:0.68rem;" id="wordsTable">
                            <thead style="background:#0a0a1a;">
                                <tr>
                                    <th class="py-2 ps-3">MOT</th>
                                    <th class="py-2">REMPLACÉ PAR</th>
                                    <th class="py-2 text-center">STATUT</th>
                                    <th class="py-2 text-center">ACTIONS</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($words as $w): ?>
                            <tr class="word-row" data-word="<?= htmlspecialchars(strtolower($w['word'])) ?>">
                                <td class="py-2 ps-3">
                                    <code class="text-warning" style="font-size:0.68rem;"><?= htmlspecialchars($w['word']) ?></code>
                                </td>
                                <td class="py-2">
                                    <span class="text-info"><?= htmlspecialchars($w['replacement']) ?></span>
                                </td>
                                <td class="py-2 text-center">
                                    <a href="?toggle=<?= $w['id'] ?>" title="<?= $w['active'] ? 'Désactiver' : 'Activer' ?>">
                                        <?php if ($w['active']): ?>
                                        <span class="badge bg-success" style="font-size:0.55rem;">ACTIF</span>
                                        <?php else: ?>
                                        <span class="badge bg-secondary" style="font-size:0.55rem;">INACTIF</span>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td class="py-2 text-center">
                                    <div class="d-flex gap-1 justify-content-center">
                                        <a href="?edit=<?= $w['id'] ?>" class="btn btn-xs btn-outline-warning py-0" title="Modifier">✏️</a>
                                        <a href="?delete=<?= $w['id'] ?>"
                                           onclick="return confirm('Supprimer le mot « <?= htmlspecialchars(addslashes($w['word'])) ?> » ?')"
                                           class="btn btn-xs btn-outline-danger py-0" title="Supprimer">🗑️</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Zone de test -->
            <div class="card bg-dark border-secondary mt-3">
                <div class="card-header py-2" style="background:#050520;">
                    <span class="text-white fw-bold" style="font-size:0.7rem;">🧪 TESTER LE FILTRE</span>
                </div>
                <div class="card-body p-3">
                    <div class="d-flex gap-2">
                        <input type="text" id="testInput" class="form-control form-control-sm bg-dark text-white border-secondary"
                               placeholder="Tapez une phrase à tester..." style="font-size:0.68rem;">
                        <button onclick="testFilter()" class="btn btn-outline-info btn-sm" style="white-space:nowrap;font-size:0.65rem;">Tester</button>
                    </div>
                    <div id="testResult" class="mt-2 p-2 rounded" style="display:none;background:#0a0a1a;font-size:0.68rem;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Recherche dans la liste
function filterWords(q) {
    q = q.toLowerCase().trim();
    document.querySelectorAll('.word-row').forEach(row => {
        row.style.display = (!q || row.dataset.word.includes(q)) ? '' : 'none';
    });
}

// Test client-side du filtre (approximatif — les vrais remplacements sont côté PHP)
const badWords = {
    <?php foreach ($words as $w): ?>
    <?= json_encode(strtolower($w['word'])) ?>: <?= json_encode($w['replacement']) ?>,
    <?php endforeach; ?>
};

function testFilter() {
    let text = document.getElementById('testInput').value;
    if (!text.trim()) return;
    let result = text;
    for (const [word, repl] of Object.entries(badWords)) {
        const regex = new RegExp('\\b' + word.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + '\\b', 'giu');
        result = result.replace(regex, repl);
    }
    const div = document.getElementById('testResult');
    div.style.display = 'block';
    const changed = result !== text;
    div.innerHTML = changed
        ? `<span class="text-warning">⚠️ Filtré :</span> <span class="text-white">${result}</span>`
        : `<span class="text-success">✅ Aucun mot interdit détecté.</span>`;
}

document.getElementById('testInput').addEventListener('keypress', e => {
    if (e.key === 'Enter') testFilter();
});
</script>

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