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

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

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

// Créer les clés de limites si absentes
$defaultLimits = [
    'limit_circles_free'        => 1,
    'limit_circles_premium'     => 5,
    'limit_circles_premplus'    => 20,
    'limit_circles_admin'       => 999,
    'limit_bets_free'           => 10,
    'limit_bets_premium'        => 50,
    'limit_bets_premplus'       => 200,
    'limit_bets_admin'          => 999,
    'limit_friends_free'        => 20,
    'limit_friends_premium'     => 100,
    'limit_friends_premplus'    => 500,
    'limit_friends_admin'       => 999,
    'limit_photos_free'         => 2,
    'limit_photos_premium'      => 10,
    'limit_photos_premplus'     => 30,
    'limit_photos_admin'        => 999,
    'limit_pm_free'             => 20,
    'limit_pm_premium'          => 200,
    'limit_pm_premplus'         => 999,
    'limit_pm_admin'            => 999,
];
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS admin_config (
        config_key VARCHAR(100) NOT NULL PRIMARY KEY,
        config_value TEXT DEFAULT NULL
    )");
    foreach ($defaultLimits as $k => $v) {
        $pdo->prepare("INSERT IGNORE INTO admin_config (config_key, config_value) VALUES (?,?)")->execute([$k, $v]);
    }
} catch (Exception $e) {}

// Sauvegarder
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_limits'])) {
    try {
        foreach ($defaultLimits as $key => $def) {
            $val = (int)($_POST[$key] ?? $def);
            if ($val <= 0) $val = 0;
            $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES (?,?) ON DUPLICATE KEY UPDATE config_value=?")
                ->execute([$key, $val, $val]);
        }
        $msg = "Limites sauvegardées !";
    } catch (Exception $e) { $error = $e->getMessage(); }
}

// Lire les valeurs actuelles
$limits = [];
foreach ($defaultLimits as $k => $v) {
    try {
        $s = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
        $s->execute([$k]);
        $limits[$k] = (int)($s->fetchColumn() ?? $v);
    } catch (Exception $e) { $limits[$k] = $v; }
}

// Stats réelles par grade
try {
    $stats = $pdo->query("
        SELECT
            tier,
            COUNT(*) AS nb_membres,
            SUM(CASE WHEN admin=1 THEN 1 ELSE 0 END) AS nb_admins,
            AVG(points) AS avg_pts,
            AVG(wallet_points) AS avg_wallet,
            SUM(wallet_points) AS total_wallet
        FROM users
        GROUP BY tier
        ORDER BY FIELD(tier,'admin','premium_plus','premium','free')
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $stats = []; }

// Stats globales par grade (cercles, gages, amis)
function statByTier($pdo, $sql, $tier) {
    try {
        $s = $pdo->prepare($sql);
        $s->execute([$tier]);
        return (int)$s->fetchColumn();
    } catch (Exception $e) { return 0; }
}

$tiers = ['free','premium','premium_plus','admin'];
$tierData = [];
foreach ($tiers as $t) {
    $tierData[$t] = [
        'membres'  => statByTier($pdo, "SELECT COUNT(*) FROM users WHERE tier=?", $t),
        'cercles'  => statByTier($pdo, "SELECT COUNT(DISTINCT cm.circle_id) FROM circle_members cm JOIN users u ON u.id=cm.user_id WHERE u.tier=?", $t),
        'gages'    => statByTier($pdo, "SELECT COUNT(*) FROM bets b JOIN users u ON u.id=b.user_id WHERE u.tier=?", $t),
        'amis'     => statByTier($pdo, "SELECT COUNT(*) FROM friends f JOIN users u ON u.id=f.user_id WHERE u.tier=? AND f.status='active'", $t),
        'messages' => statByTier($pdo, "SELECT COUNT(*) FROM messages m JOIN users u ON u.id=m.user_id WHERE u.tier=?", $t),
        'wallet'   => statByTier($pdo, "SELECT COALESCE(SUM(wallet_points),0) FROM users WHERE tier=?", $t),
    ];
}
// Admin séparé
$adminCount = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE admin=1")->fetchColumn();
$tierData['admin']['membres'] = $adminCount;

$tierMeta = [
    'free'        => ['label'=>'FREE',      'color'=>'#aaaaaa', 'bg'=>'rgba(170,170,170,0.08)', 'border'=>'#333'],
    'premium'     => ['label'=>'PREMIUM',   'color'=>'#d4af37', 'bg'=>'rgba(212,175,55,0.08)',  'border'=>'rgba(212,175,55,0.4)'],
    'premium_plus'=> ['label'=>'PREMIUM+',  'color'=>'#a9a9a9', 'bg'=>'rgba(169,169,169,0.08)', 'border'=>'rgba(169,169,169,0.4)'],
    'admin'       => ['label'=>'ADMIN',     'color'=>'#dc3545', 'bg'=>'rgba(220,53,69,0.08)',   'border'=>'rgba(220,53,69,0.4)'],
];

$limitGroups = [
    'circles' => ['label'=>'Cercles créés',    'icon'=>'fa-circle-nodes',  'suffix'=>''],
    'bets'    => ['label'=>'Gages actifs',     'icon'=>'fa-bolt',          'suffix'=>''],
    'friends' => ['label'=>'Amis max',         'icon'=>'fa-user-group',    'suffix'=>''],
    'photos'  => ['label'=>'Photos par gage',  'icon'=>'fa-image',         'suffix'=>''],
    'pm'      => ['label'=>'Messages privés',  'icon'=>'fa-envelope',      'suffix'=>''],
];

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
.lim-card   { border-radius:8px; padding:14px; }
.lim-input  { background:#0a0a14; border:1px solid #333; color:#ddd; border-radius:5px; padding:4px 8px; font-size:0.75rem; width:70px; text-align:center; }
.lim-input:focus { outline:none; border-color:#fd7e14; }
.stat-pill  { display:inline-block; background:#0a0a0a; border:1px solid #1a1a1a; border-radius:5px; padding:3px 9px; font-size:0.62rem; color:#999; margin:2px; }
.stat-pill strong { color:#ddd; }
.tier-header{ font-size:0.65rem; font-weight:700; letter-spacing:2px; text-transform:uppercase; }
</style>

<div class="container-fluid mt-3 mb-5" style="max-width:1100px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm">
            <i class="fa-solid fa-arrow-left fa-xs me-1"></i>Admin
        </a>
        <h4 class="oracle-text text-warning mb-0" style="letter-spacing:2px;">
            <i class="fa-solid fa-sliders me-2"></i>LIMITES PAR GRADE
        </h4>
    </div>

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

    <!-- ── STATS RÉELLES ──────────────────────────────────────── -->
    <div class="row g-3 mb-4">
        <?php foreach ($tiers as $t):
            $m = $tierMeta[$t];
            $d = $tierData[$t];
        ?>
        <div class="col-md-3">
            <div class="lim-card" style="background:<?= $m['bg'] ?>;border:1px solid <?= $m['border'] ?>;">
                <div class="tier-header mb-3" style="color:<?= $m['color'] ?>;">
                    <?= $m['label'] ?>
                    <span style="float:right;font-size:1.1rem;font-weight:700;color:<?= $m['color'] ?>;"><?= number_format($d['membres']) ?></span>
                </div>
                <div>
                    <div class="stat-pill"><i class="fa-solid fa-circle-nodes fa-xs me-1"></i><strong><?= number_format($d['cercles']) ?></strong> cercles</div>
                    <div class="stat-pill"><i class="fa-solid fa-bolt fa-xs me-1"></i><strong><?= number_format($d['gages']) ?></strong> gages</div>
                    <div class="stat-pill"><i class="fa-solid fa-user-group fa-xs me-1"></i><strong><?= number_format($d['amis']) ?></strong> amis</div>
                    <div class="stat-pill"><i class="fa-solid fa-comments fa-xs me-1"></i><strong><?= number_format($d['messages']) ?></strong> messages</div>
                    <div class="stat-pill"><i class="fa-solid fa-coins fa-xs me-1"></i><strong><?= number_format($d['wallet']) ?></strong> jetons total</div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- ── TABLEAU DE LIMITES ÉDITABLES ──────────────────────── -->
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header d-flex justify-content-between align-items-center py-2" style="background:#050520;border-bottom:1px solid #1a1a3a;">
            <span class="oracle-text text-warning fw-bold" style="font-size:0.78rem;letter-spacing:1px;">
                <i class="fa-solid fa-sliders me-2"></i>LIMITES CONFIGURABLES
            </span>
            <span class="text-muted" style="font-size:0.6rem;">999 = illimité</span>
        </div>
        <div class="card-body p-0">
            <form method="POST">
                <table class="table table-dark table-sm mb-0" style="min-width:600px;">
                    <thead>
                        <tr style="background:#0a0a1a;">
                            <th style="font-size:0.62rem;color:#888;padding:10px 14px;width:35%;">Fonctionnalité</th>
                            <?php foreach ($tierMeta as $t => $m): ?>
                            <th class="text-center" style="font-size:0.62rem;color:<?= $m['color'] ?>;padding:10px 8px;">
                                <?= $m['label'] ?>
                            </th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($limitGroups as $key => $info): ?>
                        <tr style="border-bottom:1px solid #111;">
                            <td style="padding:10px 14px;">
                                <i class="fa-solid <?= $info['icon'] ?> fa-xs me-2 text-muted"></i>
                                <span style="font-size:0.72rem;color:#ddd;"><?= $info['label'] ?></span>
                            </td>
                            <?php foreach (['free','premium','premium_plus','admin'] as $t):
                                $k = "limit_{$key}_{$t}";
                                $k = str_replace('premium_plus','premplus',$k);
                                $v = $limits[$k] ?? $defaultLimits[$k] ?? 0;
                                $col = $tierMeta[$t]['color'];
                            ?>
                            <td class="text-center" style="padding:8px;">
                                <input type="number" name="<?= $k ?>" value="<?= $v ?>"
                                       class="lim-input"
                                       style="border-color:<?= $tierMeta[$t]['border'] ?>;"
                                       min="0" max="9999">
                            </td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="p-3 d-flex justify-content-between align-items-center" style="border-top:1px solid #1a1a1a;">
                    <span class="text-muted" style="font-size:0.62rem;">
                        <i class="fa-solid fa-circle-info fa-xs me-1"></i>
                        Les limites sont lues depuis <code>admin_config</code> — mettez à jour <code>fetch_user_circles.php</code> et <code>create_circle.php</code> pour les utiliser dynamiquement.
                    </span>
                    <button type="submit" name="save_limits" class="btn btn-warning btn-sm fw-bold" style="font-size:0.72rem;">
                        <i class="fa-solid fa-floppy-disk fa-xs me-1"></i>Enregistrer
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ── TABLEAU RÉCAP DROITS ───────────────────────────────── -->
    <div class="card bg-dark border-secondary shadow mt-4">
        <div class="card-header py-2" style="background:#050520;border-bottom:1px solid #1a1a3a;">
            <span class="oracle-text text-info fw-bold" style="font-size:0.78rem;letter-spacing:1px;">
                <i class="fa-solid fa-table-list me-2"></i>RÉCAP DES DROITS ET LIMITES
            </span>
        </div>
        <div class="card-body p-0" style="overflow-x:auto;">
        <table class="table table-dark table-sm mb-0">
            <thead>
                <tr style="background:#0a0a1a;">
                    <th style="font-size:0.62rem;color:#888;padding:8px 12px;">Fonctionnalité</th>
                    <?php foreach ($tierMeta as $t => $m): ?>
                    <th class="text-center" style="font-size:0.62rem;color:<?= $m['color'] ?>;padding:8px;"><?= $m['label'] ?></th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php
            // Définir les capacités sous forme de données
            $caps = [
                ['Créer un gage',            true,  true,  true,  true],
                ['Gage global (ouvert)',      true,  true,  true,  true],
                ['Voter OUI/NON',            true,  true,  true,  true],
                ['Mise de jetons sur gage',  false, true,  true,  true],
                ['Pastilles dashboard',      false, true,  true,  true],
                ['Pastille Mes Cercles',     true,  true,  true,  true],
                ['Couleur texte chat',       false, false, true,  true],
                ['Photo dans le chat',       false, false, true,  true],
                ['Icônes Premium chat',      false, true,  true,  true],
                ['Icônes Premium+ chat',     false, false, true,  true],
                ['Messagerie privée',        true,  true,  true,  true],
                ['Système d\'amis',          true,  true,  true,  true],
                ['Oracle (juger gages)',     false, false, false, true],
                ['Créer un cercle',          true,  true,  true,  true],
                ['Panneau admin',            false, false, false, true],
            ];
            $icon = fn($v) => $v
                ? '<i class="fa-solid fa-circle-check" style="color:#777;font-size:0.85rem;"></i>'
                : '<i class="fa-regular fa-circle" style="color:#777;font-size:0.85rem;"></i>';
            foreach ($caps as $row):
            ?>
            <tr style="border-bottom:1px solid #0d0d0d;">
                <td style="font-size:0.7rem;color:#ccc;padding:6px 12px;"><?= htmlspecialchars($row[0]) ?></td>
                <td class="text-center"><?= $icon($row[1]) ?></td>
                <td class="text-center"><?= $icon($row[2]) ?></td>
                <td class="text-center"><?= $icon($row[3]) ?></td>
                <td class="text-center"><?= $icon($row[4]) ?></td>
            </tr>
            <?php endforeach; ?>
            <!-- Limites numériques -->
            <?php foreach ($limitGroups as $key => $info):
                $vals = [];
                foreach (['free','premium','premplus','admin'] as $t) {
                    $k = "limit_{$key}_{$t}";
                    $vals[] = $limits[$k] ?? ($defaultLimits[$k] ?? '?');
                }
            ?>
            <tr style="border-bottom:1px solid #0d0d0d;background:#080810;">
                <td style="font-size:0.7rem;color:#ccc;padding:6px 12px;">
                    <i class="fa-solid <?= $info['icon'] ?> fa-xs me-1 text-muted"></i><?= $info['label'] ?>
                </td>
                <?php foreach ($vals as $i => $val):
                    $colors = ['#aaa','#d4af37','#a9a9a9','#dc3545'];
                    $v = $val == 999 ? '∞' : $val;
                ?>
                <td class="text-center" style="font-size:0.78rem;font-weight:700;color:<?= $colors[$i] ?>;"><?= $v ?></td>
                <?php endforeach; ?>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>
</div>

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