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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];

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

// Créer table si absente
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS bug_reports (
        id          INT(11)     NOT NULL AUTO_INCREMENT PRIMARY KEY,
        user_id     INT(11)     NOT NULL,
        menu        VARCHAR(100) DEFAULT NULL,
        section     VARCHAR(100) DEFAULT NULL,
        bug_type    ENUM('affichage','fonctionnalite','performance','securite','autre') DEFAULT 'autre',
        description TEXT        NOT NULL,
        status      ENUM('nouveau','en_cours','resolu') DEFAULT 'nouveau',
        created_at  TIMESTAMP   DEFAULT CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_bug'])) {
    $menu    = trim(htmlspecialchars($_POST['menu']        ?? ''));
    $section = trim(htmlspecialchars($_POST['section']     ?? ''));
    $type    = $_POST['bug_type']    ?? 'autre';
    $desc    = trim(htmlspecialchars($_POST['description'] ?? ''));

    if (empty($desc)) {
        $error = "La description est requise.";
    } else {
        try {
            $pdo->prepare("INSERT INTO bug_reports (user_id, menu, section, bug_type, description) VALUES (?,?,?,?,?)")
                ->execute([$userId, $menu, $section, $type, $desc]);

            // Notifier l'admin
            try {
                $adminIds = $pdo->query("SELECT id FROM users WHERE admin=1")->fetchAll(PDO::FETCH_COLUMN);
                foreach ($adminIds as $aid) {
                    addNotification($pdo, $aid, "Nouveau bug reporte par {$user['username']} : [{$type}] {$menu}", "admin_bugs.php");
                }
            } catch (Exception $e) {}

            $msg = "Bug rapporte ! Merci pour ton aide. Notre equipe va l'examiner.";
        } catch (Exception $e) { $error = "Erreur: " . $e->getMessage(); }
    }
}

include 'header.php';
?>

<div class="container mt-4 px-4" style="max-width:600px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Retour</a>
        <h5 class="text-danger fw-bold mb-0">Rapporter un bug</h5>
    </div>

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

    <div class="card bg-dark border-danger shadow">
        <div class="card-body">
            <form method="POST">
                <div class="mb-3">
                    <label class="text-white fw-bold small d-block mb-1">Menu / Page</label>
                    <select name="menu" class="form-select form-select-sm bg-dark text-white border-secondary">
                        <option value="">-- Selectionner --</option>
                        <option>Dashboard</option>
                        <option>Chat / Mur</option>
                        <option>Gages</option>
                        <option>Messagerie</option>
                        <option>Amis</option>
                        <option>Statistiques</option>
                        <option>Trophées</option>
                        <option>Forfaits</option>
                        <option>Boutique</option>
                        <option>L'Oracle</option>
                        <option>Admin</option>
                        <option>Configuration</option>
                        <option>Profil</option>
                        <option>Autre</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="text-white fw-bold small d-block mb-1">Section spécifique</label>
                    <input type="text" name="section" class="form-control form-control-sm bg-dark text-white border-secondary"
                           placeholder="Ex: Formulaire de création de gage, Bouton envoyer...">
                </div>
                <div class="mb-3">
                    <label class="text-white fw-bold small d-block mb-1">Type de bug</label>
                    <select name="bug_type" class="form-select form-select-sm bg-dark text-white border-secondary">
                        <option value="affichage">Affichage (visuel, label, couleur)</option>
                        <option value="fonctionnalite">Fonctionnalité (bouton, action)</option>
                        <option value="performance">Performance (lenteur, freeze)</option>
                        <option value="securite">Sécurité</option>
                        <option value="autre">Autre</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="text-white fw-bold small d-block mb-1">Description du bug *</label>
                    <textarea name="description" class="form-control bg-dark text-white border-secondary" rows="4"
                              placeholder="Décris ce qui se passe, ce que tu attendais, et les étapes pour reproduire..." required></textarea>
                </div>
                <div class="mb-3">
                    <small class="text-muted" style="font-size:0.65rem;">
                        Soumis le : <?= date('d M Y H:i') ?> | Utilisateur : <?= htmlspecialchars($user['username']) ?>
                    </small>
                </div>
                <button type="submit" name="submit_bug" class="btn btn-danger fw-bold w-100">ENVOYER LE RAPPORT</button>
            </form>
        </div>
    </div>
</div>

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