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

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

$msg = ''; $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // --- Icônes ---
    if (isset($_POST['add_icon'])) {
        $emoji   = trim($_POST['emoji']);
        $label   = trim(htmlspecialchars($_POST['label']));
        $cat     = $_POST['category'] ?? 'general';
        $tier    = in_array($_POST['required_tier'],['free','premium','premium_plus','admin']) ? $_POST['required_tier'] : 'free';
        $pts     = max(0,(int)$_POST['required_points']);
        $sort    = (int)$_POST['sort_order'];
        if ($emoji) {
            $pdo->prepare("INSERT INTO chat_icons (emoji,label,category,required_tier,required_points,sort_order) VALUES (?,?,?,?,?,?)")
                ->execute([$emoji,$label,$cat,$tier,$pts,$sort]);
            $msg = "Icône {$emoji} ajoutée !";
        }
    }
    if (isset($_POST['delete_icon'])) {
        $pdo->prepare("DELETE FROM chat_icons WHERE id=?")->execute([(int)$_POST['icon_id']]);
        $msg = "Icône supprimée.";
    }
    if (isset($_POST['toggle_icon'])) {
        $pdo->prepare("UPDATE chat_icons SET is_active=? WHERE id=?")->execute([(int)$_POST['new_val'],(int)$_POST['icon_id']]);
        $msg = "Icône mise à jour.";
    }

    // --- Messages auto ---
    if (isset($_POST['add_auto_msg'])) {
        $txt = trim(htmlspecialchars($_POST['auto_message']));
        if ($txt) { $pdo->prepare("INSERT INTO chat_auto_messages (message) VALUES (?)")->execute([$txt]); $msg = "Message automatique ajouté !"; }
    }
    if (isset($_POST['delete_auto_msg'])) {
        $pdo->prepare("DELETE FROM chat_auto_messages WHERE id=?")->execute([(int)$_POST['auto_id']]);
        $msg = "Message supprimé.";
    }
    if (isset($_POST['toggle_auto_msg'])) {
        $pdo->prepare("UPDATE chat_auto_messages SET is_active=? WHERE id=?")->execute([(int)$_POST['new_val'],(int)$_POST['auto_id']]);
        $msg = "Statut mis à jour.";
    }
    if (isset($_POST['edit_auto_msg'])) {
        $txt = trim(htmlspecialchars($_POST['auto_message_edit']));
        $pdo->prepare("UPDATE chat_auto_messages SET message=? WHERE id=?")->execute([$txt,(int)$_POST['auto_id']]);
        $msg = "Message mis à jour.";
    }
}

try { $icons    = $pdo->query("SELECT * FROM chat_icons ORDER BY required_tier, required_points, sort_order")->fetchAll(); } catch(Exception $e) { $icons = []; }
try { $autoMsgs = $pdo->query("SELECT * FROM chat_auto_messages ORDER BY id")->fetchAll(); } catch(Exception $e) { $autoMsgs = []; }
try {
    $flagged = $pdo->query("SELECT m.*, COUNT(cr.id) as nb_reports FROM messages m LEFT JOIN chat_reports cr ON cr.message_id = m.id WHERE m.is_flagged=1 GROUP BY m.id ORDER BY m.id DESC LIMIT 20")->fetchAll();
} catch(Exception $e) { $flagged = []; }

include 'header.php';
?>

<div class="container-fluid mt-4 px-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <h5 class="oracle-text text-info mb-3">GESTION DU CHAT</h5>

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

    <div class="row g-4">

        <!-- ICÔNES -->
        <div class="col-md-5">
            <div class="card bg-dark border-info shadow mb-3">
                <div class="card-header py-2 fw-bold small text-info"> ICÔNES DE CHAT</div>
                <div class="card-body">
                    <form method="POST" class="mb-3">
                        <div class="row g-2">
                            <div class="col-3">
                                <label class="small text-white d-block mb-1">Emoji</label>
                                <input type="text" name="emoji" class="form-control form-control-sm text-center" placeholder="" maxlength="5" required>
                            </div>
                            <div class="col-5">
                                <label class="small text-white d-block mb-1">Label</label>
                                <input type="text" name="label" class="form-control form-control-sm" placeholder="Feu" maxlength="30">
                            </div>
                            <div class="col-4">
                                <label class="small text-white d-block mb-1">Grade min.</label>
                                <select name="required_tier" class="form-select form-select-sm">
                                    <option value="free">Free</option>
                                    <option value="premium">Premium</option>
                                    <option value="premium_plus">Premium+</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            <div class="col-4">
                                <label class="small text-white d-block mb-1">Pts interact. min.</label>
                                <input type="number" name="required_points" class="form-control form-control-sm" value="0" min="0">
                            </div>
                            <div class="col-4">
                                <label class="small text-white d-block mb-1">Catégorie</label>
                                <select name="category" class="form-select form-select-sm">
                                    <option value="general">Général</option>
                                    <option value="premium">Premium</option>
                                    <option value="premium_plus">Premium+</option>
                                    <option value="special">Spécial</option>
                                </select>
                            </div>
                            <div class="col-4">
                                <label class="small text-white d-block mb-1">Ordre</label>
                                <input type="number" name="sort_order" class="form-control form-control-sm" value="0">
                            </div>
                        </div>
                        <div class="mt-2 text-end">
                            <button type="submit" name="add_icon" class="btn btn-info btn-sm fw-bold">+ AJOUTER</button>
                        </div>
                    </form>

                    <!-- Liste icônes -->
                    <div style="max-height:300px;overflow-y:auto;">
                        <table class="table table-dark table-sm small mb-0">
                            <thead><tr><th>Emoji</th><th>Label</th><th>Grade</th><th>Pts</th><th>Actif</th><th></th></tr></thead>
                            <tbody>
                            <?php foreach ($icons as $ic): ?>
                            <tr>
                                <td style="font-size:1.1rem;"><?= $ic['emoji'] ?></td>
                                <td class="text-muted"><?= htmlspecialchars($ic['label']??'') ?></td>
                                <td><span class="badge bg-secondary" style="font-size:0.55rem;"><?= $ic['required_tier'] ?></span></td>
                                <td class="text-muted"><?= $ic['required_points'] ?></td>
                                <td>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="icon_id" value="<?= $ic['id'] ?>">
                                        <input type="hidden" name="new_val" value="<?= $ic['is_active']?0:1 ?>">
                                        <button type="submit" name="toggle_icon" class="btn btn-xs py-0 <?= $ic['is_active']?'btn-success':'btn-outline-secondary' ?>"><?= $ic['is_active']?'✓':'✗' ?></button>
                                    </form>
                                </td>
                                <td>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="icon_id" value="<?= $ic['id'] ?>">
                                        <button type="submit" name="delete_icon" class="btn btn-xs btn-outline-danger py-0" onclick="return confirm('Supprimer ?')">X️</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($icons)): ?><tr><td colspan="6" class="text-center text-muted py-2">Aucune icône. Exécute chat_module.sql d'abord.</td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-7">
            <!-- MESSAGES AUTO -->
            <div class="card bg-dark border-warning shadow mb-3">
                <div class="card-header py-2 fw-bold small text-warning">MESSAGES AUTOMATIQUES (DÉRAPAGE)</div>
                <div class="card-body">
                    <form method="POST" class="mb-3 d-flex gap-2">
                        <input type="text" name="auto_message" class="form-control form-control-sm" placeholder="Ex: Tu dérapes ! Reviens-nous." required>
                        <button type="submit" name="add_auto_msg" class="btn btn-warning btn-sm fw-bold flex-shrink-0">+ AJOUTER</button>
                    </form>
                    <table class="table table-dark table-sm small mb-0">
                        <thead><tr><th>#</th><th>Message</th><th>Actif</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach ($autoMsgs as $am): ?>
                        <tr>
                            <td class="text-muted"><?= $am['id'] ?></td>
                            <td>
                                <form method="POST" class="d-flex gap-1">
                                    <input type="hidden" name="auto_id" value="<?= $am['id'] ?>">
                                    <input type="text" name="auto_message_edit" class="form-control form-control-sm"
                                           value="<?= htmlspecialchars($am['message']) ?>">
                                    <button type="submit" name="edit_auto_msg" class="btn btn-xs btn-outline-warning py-0 flex-shrink-0"></button>
                                </form>
                            </td>
                            <td>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="auto_id" value="<?= $am['id'] ?>">
                                    <input type="hidden" name="new_val" value="<?= $am['is_active']?0:1 ?>">
                                    <button type="submit" name="toggle_auto_msg" class="btn btn-xs py-0 <?= $am['is_active']?'btn-success':'btn-outline-secondary' ?>"><?= $am['is_active']?'✓':'✗' ?></button>
                                </form>
                            </td>
                            <td>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="auto_id" value="<?= $am['id'] ?>">
                                    <button type="submit" name="delete_auto_msg" class="btn btn-xs btn-outline-danger py-0" onclick="return confirm('Supprimer ?')">X️</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($autoMsgs)): ?><tr><td colspan="4" class="text-center text-muted py-2">Aucun message. Exécute chat_module.sql d'abord.</td></tr><?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- MESSAGES SIGNALÉS -->
            <?php if (!empty($flagged)): ?>
            <div class="card bg-dark border-danger shadow">
                <div class="card-header py-2 fw-bold small text-danger">MESSAGES SIGNALES (<?= count($flagged) ?>)</div>
                <div class="card-body p-2" style="max-height:200px;overflow-y:auto;">
                    <?php foreach ($flagged as $fm): ?>
                    <div class="d-flex justify-content-between align-items-center p-1 mb-1 rounded" style="background:#1a0a0a;border:1px solid #dc3545;">
                        <div>
                            <strong class="text-warning" style="font-size:0.7rem;"><?= htmlspecialchars($fm['username']??'?') ?></strong>
                            <span class="text-white ms-1" style="font-size:0.7rem;"><?= htmlspecialchars(mb_substr($fm['content']??'',0,60)) ?></span>
                            <small class="text-muted d-block" style="font-size:0.6rem;"><?= $fm['nb_reports'] ?> signalement(s)</small>
                        </div>
                        <form method="POST">
                            <input type="hidden" name="msg_id_clear" value="<?= $fm['id'] ?>">
                            <button onclick="if(confirm('Effacer ce message ?')){fetch('admin_clear_msg.php?id=<?= $fm['id'] ?>').then(()=>location.reload())}" type="button" class="btn btn-xs btn-outline-danger py-0">X️</button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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