<?php

require_once __DIR__ . '/db/auth.php';
require_once __DIR__ . '/db/scstatsitem.php';

auth_start_session();
auth_bootstrap();
scstatsitem_bootstrap();

if (!auth_is_admin()) {
    header('Location: index.php');
    exit;
}

$flash = auth_flash_get();
$flash_type = $flash['type'] ?? '';
$flash_message = $flash['message'] ?? '';

$db = db();
$csrf_token = auth_csrf_token();

$allowed_units = ['%', '°C', 'RPM', 'Q', 'SCU'];


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submitted_csrf = $_POST['csrf_token'] ?? '';
    if (!auth_validate_csrf($submitted_csrf)) {
        auth_flash_set('error', 'Jeton CSRF invalide.');
        header('Location: scstatsitem.php');
        exit;
    }

    $action = $_POST['action'] ?? '';

    if ($action === 'add_stat') {
        $name = trim($_POST['name'] ?? '');
        $unit = trim($_POST['unit'] ?? '%');
        if (!in_array($unit, $allowed_units, true)) {
            $unit = '%';
        }

        if ($name === '') {
            auth_flash_set('error', 'Le nom de la statistique est requis.');
        } else {
            try {
                $stmt = $db->prepare('INSERT INTO tbl_scstatsitem (cl_scstatsitem_name, cl_scstatsitem_unit) VALUES (:name, :unit)');
                $stmt->execute([
                    'name' => $name,
                    'unit' => $unit,
                ]);
                auth_flash_set('success', 'Statistique ajoutée avec succès.');
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    auth_flash_set('error', 'Cette statistique existe déjà.');
                } else {
                    auth_flash_set('error', 'Erreur lors de l\'ajout : ' . $e->getMessage());
                }
            }
        }

        header('Location: scstatsitem.php');
        exit;
    }

    if ($action === 'update_stat') {
        $id = (int) ($_POST['stat_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $unit = trim($_POST['unit'] ?? '%');
        if (!in_array($unit, $allowed_units, true)) {
            $unit = '%';
        }

        if ($id <= 0 || $name === '') {
            auth_flash_set('error', 'Données invalides.');
        } else {
            try {
                $stmt = $db->prepare('UPDATE tbl_scstatsitem SET cl_scstatsitem_name = :name, cl_scstatsitem_unit = :unit WHERE cl_scstatsitem_id = :id');
                $stmt->execute([
                    'name' => $name,
                    'unit' => $unit,
                    'id' => $id,
                ]);
                auth_flash_set('success', 'Statistique mise à jour.');
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    auth_flash_set('error', 'Cette statistique existe déjà.');
                } else {
                    auth_flash_set('error', 'Erreur lors de la mise à jour : ' . $e->getMessage());
                }
            }
        }

        header('Location: scstatsitem.php');
        exit;
    }

    if ($action === 'delete_stat') {
        $id = (int) ($_POST['stat_id'] ?? 0);

        if ($id > 0) {
            try {
                $stmt = $db->prepare('DELETE FROM tbl_scstatsitem WHERE cl_scstatsitem_id = :id');
                $stmt->execute(['id' => $id]);
                auth_flash_set('success', 'Statistique supprimée.');
            } catch (PDOException $e) {
                auth_flash_set('error', 'Erreur lors de la suppression : ' . $e->getMessage());
            }
        }

        header('Location: scstatsitem.php');
        exit;
    }
}

$stmt_stats = $db->query('SELECT * FROM tbl_scstatsitem ORDER BY cl_scstatsitem_name ASC, cl_scstatsitem_id ASC');
$stats_items = $stmt_stats->fetchAll();

$current_session_user = $_SESSION['user'] ?? '';
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stats Item | R.E.A.C.T. Admin</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
    <link rel="stylesheet" type="text/css" href="css/default.css">
    <style>
        :root {
            --primary: #a29b78;
            --primary-glow: rgba(162, 155, 120, 0.4);
            --bg-dark: #080a0f;
            --card-bg: rgba(20, 24, 33, 0.85);
            --border-glow: rgba(162, 155, 120, 0.25);
            --danger: #ff4d4d;
            --success: #00ff88;
        }

        @font-face {
            font-family: 'Electrolize';
            src: url('fonts/Electrolize-Regular.ttf') format('truetype');
        }

        body {
            background: radial-gradient(circle at top right, #1a1f2e, var(--bg-dark));
            background-attachment: fixed;
            color: #e0e0e0;
            font-family: 'Electrolize', sans-serif;
            margin: 0;
            overflow-x: hidden;
            min-height: 100vh;
        }

        .admin-layout {
            display: flex;
            flex-direction: column;
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
            animation: fadeIn 0.6s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .admin-topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1.5rem 2rem;
            background: var(--card-bg);
            backdrop-filter: blur(10px);
            border: 1px solid var(--border-glow);
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        }

        .topbar-info h1 {
            margin: 0;
            font-size: 1.5rem;
            letter-spacing: 2px;
            text-transform: uppercase;
            background: linear-gradient(90deg, #fff, var(--primary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .topbar-info p {
            margin: 0.25rem 0 0;
            font-size: 0.85rem;
            color: var(--primary);
            opacity: 0.8;
        }

        .btn-modern {
            padding: 0.6rem 1.2rem;
            border: 1px solid var(--primary);
            background: transparent;
            color: #fff;
            font-family: 'Electrolize', sans-serif;
            font-size: 0.9rem;
            text-transform: uppercase;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            border-radius: 4px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .btn-modern:hover {
            background: var(--primary);
            color: var(--bg-dark);
            box-shadow: 0 0 15px var(--primary-glow);
        }

        .btn-modern.danger { border-color: var(--danger); color: var(--danger); }
        .btn-modern.danger:hover { background: var(--danger); color: #fff; }

        .btn-mini { padding: 0.3rem 0.6rem; font-size: 0.75rem; }

        .nav-tabs { display: flex; gap: 1rem; margin-bottom: 2rem; border-bottom: 1px solid var(--border-glow); padding-bottom: 1rem; }
        .nav-tabs a { text-decoration: none; color: #888; text-transform: uppercase; font-size: 0.9rem; transition: color 0.3s; }
        .nav-tabs a:hover, .nav-tabs a.active { color: var(--primary); }

        .admin-grid {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 2rem;
        }

        .side-panel, .main-panel { display: flex; flex-direction: column; gap: 2rem; }

        .glass-card {
            background: var(--card-bg);
            border: 1px solid var(--border-glow);
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(10px);
        }

        .glass-card h2 {
            margin: 0 0 1.25rem;
            color: var(--primary);
            font-size: 1.1rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .form-group { margin-bottom: 1rem; }

        label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.85rem;
            color: var(--primary);
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .form-control {
            width: 100%;
            padding: 0.8rem;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border-glow);
            border-radius: 6px;
            color: #fff;
            font-family: 'Electrolize', sans-serif;
            box-sizing: border-box;
            transition: all 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-glow);
        }

        .form-help {
            margin-top: 0.75rem;
            color: #9ca3af;
            font-size: 0.85rem;
            line-height: 1.5;
        }

        .flash {
            padding: 1rem 1.25rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            border: 1px solid var(--border-glow);
            background: rgba(20, 24, 33, 0.9);
        }

        .flash.success { border-color: rgba(0, 255, 136, 0.35); color: var(--success); }
        .flash.error { border-color: rgba(255, 77, 77, 0.35); color: #ff8a8a; }

        .modern-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 520px;
        }

        .modern-table th,
        .modern-table td {
            padding: 0.9rem 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.06);
            vertical-align: middle;
        }

        .modern-table th {
            text-align: left;
            color: var(--primary);
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .modern-table tr:hover td {
            background: rgba(255, 255, 255, 0.02);
        }

        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #777;
        }

        @media (max-width: 980px) {
            .admin-grid {
                grid-template-columns: 1fr;
            }

            .admin-topbar {
                flex-direction: column;
                gap: 1rem;
                align-items: flex-start;
            }

            .nav-tabs {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <header class="admin-topbar">
            <div class="topbar-info">
                <h1>Stats Item</h1>
                <p>Gestion libre des statistiques d'objets</p>
            </div>
            <div style="display:flex; gap:10px; flex-wrap:wrap;">
                <span style="align-self:center; opacity:0.8;">Session: <?php echo htmlspecialchars($current_session_user, ENT_QUOTES, 'UTF-8'); ?></span>
                <a href="index.php" class="btn-modern">Retour au site</a>
                <a href="logout.php" class="btn-modern danger">Session End</a>
            </div>
        </header>

        <nav class="nav-tabs">
            <a href="admin.php">Utilisateurs</a>
            <a href="scwebhook.php">WEBHOOK</a>
            <a href="scnotification.php">NOTIF DISCORD</a>
            <a href="scitems.php">Base d'Objets</a>
            <a href="scstatsitem.php" class="active">Stats Item</a>
            <a href="scitemcustom.php">Item Custom</a>
            <a href="scmining.php">Scanner Minage</a>
            <a href="scmanufactures.php">Manufactures</a>
            <a href="scvaisseaux.php">Vaisseaux</a>
            <a href="scpreset.php">Presets Vaisseau</a>
        </nav>

        <?php if ($flash_message !== ''): ?>
            <div class="flash <?php echo htmlspecialchars($flash_type, ENT_QUOTES, 'UTF-8'); ?>">
                <?php echo htmlspecialchars($flash_message, ENT_QUOTES, 'UTF-8'); ?>
            </div>
        <?php endif; ?>

        <div class="admin-grid">
            <div class="side-panel">
                <section class="glass-card">
                    <h2 id="formTitle">Nouvelle Stat Item</h2>
                    <form id="statsItemForm" method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="action" id="formAction" value="add_stat">
                        <input type="hidden" name="stat_id" id="statId" value="">

                        <div class="form-group">
                            <label for="statName">Nom de la statistique</label>
                            <input type="text" name="name" id="statName" class="form-control" required placeholder="Ex : Puissance, Résistance, Vitesse...">
                            <div class="form-help">Ajoute autant de stats que tu veux. Chaque ligne représente une statistique personnalisée que tu pourras gérer librement.</div>
                        </div>

                        <div class="form-group">
                            <label for="statUnit">Unité de la statistique</label>
                            <select name="unit" id="statUnit" class="form-control">
                                <?php foreach ($allowed_units as $unit_option): ?>
                                    <option value="<?php echo htmlspecialchars($unit_option, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $unit_option === '%' ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($unit_option, ENT_QUOTES, 'UTF-8'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <button type="submit" id="submitBtn" class="btn-modern" style="width: 100%;">Ajouter</button>
                        <button type="button" id="cancelBtn" class="btn-modern" style="width: 100%; margin-top: 10px; display: none;" onclick="resetForm()">Annuler</button>
                    </form>
                </section>
            </div>

            <main class="main-panel">
                <section class="glass-card">
                    <h2>Liste des Stats Item</h2>
                    <div style="overflow-x: auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Nom</th>
                                    <th>Unité</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($stats_items)): ?>
                                    <tr>
                                        <td colspan="4" class="empty-state">Aucune statistique enregistrée.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($stats_items as $stat): ?>
                                        <tr>
                                            <td style="width: 70px; opacity: 0.5;">#<?php echo (int) $stat['cl_scstatsitem_id']; ?></td>
                                            <td>
                                                <strong style="color: var(--primary); text-transform: uppercase;">
                                                    <?php echo htmlspecialchars($stat['cl_scstatsitem_name'], ENT_QUOTES, 'UTF-8'); ?>
                                                </strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($stat['cl_scstatsitem_unit'], ENT_QUOTES, 'UTF-8'); ?></td>
                                            <td style="text-align: right;">
                                                <div style="display: flex; gap: 5px; justify-content: flex-end;">
                                                    <button
                                                        type="button"
                                                        class="btn-modern btn-mini"
                                                        onclick='editStatItem(<?php echo json_encode([
                                                            "id" => (int) $stat["cl_scstatsitem_id"],
                                                            "name" => $stat["cl_scstatsitem_name"],
                                                            "unit" => $stat["cl_scstatsitem_unit"],
                                                        ], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>)'>
                                                        Edit
                                                    </button>
                                                    <form method="post" onsubmit="return confirm('Supprimer cette statistique ?');">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8'); ?>">
                                                        <input type="hidden" name="action" value="delete_stat">
                                                        <input type="hidden" name="stat_id" value="<?php echo (int) $stat['cl_scstatsitem_id']; ?>">
                                                        <button type="submit" class="btn-modern btn-mini danger">X</button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            </main>
        </div>
    </div>

    <script>
        function editStatItem(data) {
            document.getElementById('formAction').value = 'update_stat';
            document.getElementById('statId').value = data.id;
            document.getElementById('statName').value = data.name;
            document.getElementById('statUnit').value = data.unit || '%';
            document.getElementById('submitBtn').innerText = 'Mettre à jour';
            document.getElementById('cancelBtn').style.display = 'block';
            document.getElementById('formTitle').innerText = 'Modifier Stat Item';
            document.getElementById('statsItemForm').scrollIntoView({ behavior: 'smooth' });
        }

        function resetForm() {
            document.getElementById('formAction').value = 'add_stat';
            document.getElementById('statId').value = '';
            document.getElementById('statsItemForm').reset();
            document.getElementById('submitBtn').innerText = 'Ajouter';
            document.getElementById('cancelBtn').style.display = 'none';
            document.getElementById('formTitle').innerText = 'Nouvelle Stat Item';
        }
    </script>
</body>
</html>
