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

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

// Stats DB
try {
    $dbSize = $pdo->query("
        SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as size_mb
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
    ")->fetchColumn();
} catch (Exception $e) { $dbSize = 0; }

// Stats utilisateurs
$nbUsers    = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$nbBets     = (int)$pdo->query("SELECT COUNT(*) FROM bets")->fetchColumn();
$nbMessages = (int)$pdo->query("SELECT COUNT(*) FROM messages")->fetchColumn();
$nbCircles  = (int)$pdo->query("SELECT COUNT(*) FROM circles WHERE status='active'")->fetchColumn();

// Nouveaux ce mois
$thisMonth = date('Y-m-01');
$newUsers  = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE created_at >= '{$thisMonth}'")->fetchColumn();
$newBets   = (int)$pdo->query("SELECT COUNT(*) FROM bets WHERE id > 0")->fetchColumn();

// Actifs aujourd'hui
try {
    $activeToday = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE last_activity >= DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
} catch (Exception $e) { $activeToday = 0; }

// Espace disque uploads
$uploadsDir = __DIR__ . '/uploads/';
$diskUsed = 0;
if (is_dir($uploadsDir)) {
    $iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploadsDir, RecursiveDirectoryIterator::SKIP_DOTS));
    foreach ($iter as $file) { $diskUsed += $file->getSize(); }
}
$diskUsedMB = round($diskUsed / 1024 / 1024, 2);

// PHP info
$phpVersion  = PHP_VERSION;
$maxUpload   = ini_get('upload_max_filesize');
$maxPost     = ini_get('post_max_size');
$memLimit    = ini_get('memory_limit');

// Progression du mois
$today    = (int)date('d');
$daysInMonth = (int)date('t');
$monthPct = round($today / $daysInMonth * 100);

// Progression de l'année
$dayOfYear   = (int)date('z') + 1;
$daysInYear  = date('L') ? 366 : 365;
$yearPct     = round($dayOfYear / $daysInYear * 100);

include 'header.php';
?>

<div class="container mt-4 px-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm">&larr; Admin</a>
        <h5 class="text-info fw-bold mb-0">Tableau de bord serveur</h5>
    </div>

    <!-- STATS PRINCIPALES -->
    <div class="row g-3 mb-4">
        <?php $stats = [
            ['Utilisateurs',  $nbUsers,    'text-info',    'Membres inscrits'],
            ['Actifs 24h',    $activeToday,'text-success', 'Connectes aujourd\'hui'],
            ['Gages',         $nbBets,     'text-warning', 'Total crees'],
            ['Messages chat', $nbMessages, 'text-primary', 'Total envoyes'],
            ['Cercles actifs',$nbCircles,  'text-info',    'Groupes actifs'],
            ['Nouveaux/mois', $newUsers,   'text-success', 'Inscrits ce mois'],
        ]; ?>
        <?php foreach ($stats as [$label, $val, $color, $sub]): ?>
        <div class="col-6 col-md-4 col-lg-2">
            <div class="card bg-dark border-secondary text-center p-2 h-100">
                <div class="<?= $color ?> fw-bold" style="font-size:1.4rem;"><?= number_format($val) ?></div>
                <div class="text-white small"><?= $label ?></div>
                <div class="text-muted" style="font-size:0.6rem;"><?= $sub ?></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="row g-3 mb-4">
        <!-- ESPACE DISQUE -->
        <div class="col-md-6">
            <div class="card bg-dark border-secondary shadow p-3">
                <h6 class="text-warning fw-bold mb-3">Stockage</h6>
                <div class="d-flex justify-content-between mb-1">
                    <span class="text-white small">Base de données</span>
                    <span class="text-info fw-bold"><?= $dbSize ?> Mo</span>
                </div>
                <div class="d-flex justify-content-between mb-1">
                    <span class="text-white small">Fichiers uploadés</span>
                    <span class="text-info fw-bold"><?= $diskUsedMB ?> Mo</span>
                </div>
                <div class="d-flex justify-content-between mb-3">
                    <span class="text-white small">Total estimé</span>
                    <span class="text-warning fw-bold"><?= round($dbSize + $diskUsedMB, 2) ?> Mo</span>
                </div>

                <h6 class="text-warning fw-bold mb-2">PHP</h6>
                <div class="d-flex justify-content-between mb-1">
                    <span class="text-muted small">Version PHP</span>
                    <span class="text-white small"><?= $phpVersion ?></span>
                </div>
                <div class="d-flex justify-content-between mb-1">
                    <span class="text-muted small">Upload max</span>
                    <span class="text-white small"><?= $maxUpload ?></span>
                </div>
                <div class="d-flex justify-content-between mb-1">
                    <span class="text-muted small">POST max</span>
                    <span class="text-white small"><?= $maxPost ?></span>
                </div>
                <div class="d-flex justify-content-between">
                    <span class="text-muted small">Mémoire max</span>
                    <span class="text-white small"><?= $memLimit ?></span>
                </div>
            </div>
        </div>

        <!-- PROGRESSION TEMPORELLE -->
        <div class="col-md-6">
            <div class="card bg-dark border-secondary shadow p-3">
                <h6 class="text-warning fw-bold mb-3">Progression temporelle</h6>

                <div class="mb-3">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-white small">Mois en cours (<?= date('F Y') ?>)</span>
                        <span class="text-info small">Jour <?= $today ?>/<?= $daysInMonth ?></span>
                    </div>
                    <div class="progress" style="height:12px;background:#1a1a1a;">
                        <div class="progress-bar bg-info progress-bar-striped" style="width:<?= $monthPct ?>%;"></div>
                    </div>
                    <div class="text-muted text-end" style="font-size:0.6rem;"><?= $monthPct ?>%</div>
                </div>

                <div class="mb-3">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-white small">Année en cours (<?= date('Y') ?>)</span>
                        <span class="text-warning small">Jour <?= $dayOfYear ?>/<?= $daysInYear ?></span>
                    </div>
                    <div class="progress" style="height:12px;background:#1a1a1a;">
                        <div class="progress-bar bg-warning progress-bar-striped" style="width:<?= $yearPct ?>%;"></div>
                    </div>
                    <div class="text-muted text-end" style="font-size:0.6rem;"><?= $yearPct ?>%</div>
                </div>

                <div class="border-top border-secondary pt-3 mt-2">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted small">Date/heure serveur</span>
                        <span class="text-white small"><?= date('d M Y H:i:s') ?></span>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted small">Timezone</span>
                        <span class="text-white small"><?= date_default_timezone_get() ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ACTIVITÉ RÉCENTE -->
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header text-info fw-bold small py-2">Dernières connexions</div>
        <div class="table-responsive">
            <table class="table table-dark table-sm small mb-0">
                <thead><tr><th>Membre</th><th>Forfait</th><th>Dernière activité</th><th>Statut</th></tr></thead>
                <tbody>
                <?php
                $recent = $pdo->query("SELECT username, tier, last_activity, role_status FROM users ORDER BY last_activity DESC LIMIT 10")->fetchAll();
                foreach ($recent as $u):
                    $lastAct = strtotime($u['last_activity'] ?? '2000-01-01');
                    $online  = (time() - $lastAct) < 300;
                    $dot     = $online ? 'background:#28a745' : 'background:#555';
                    $tierCol = match($u['tier']??'free') { 'admin'=>'text-danger','premium_plus'=>'text-warning','premium'=>'text-info',default=>'text-muted' };
                ?>
                <tr>
                    <td class="text-white"><?= htmlspecialchars($u['username']) ?></td>
                    <td><span class="<?= $tierCol ?>"><?= strtoupper($u['tier']??'FREE') ?></span></td>
                    <td class="text-muted" style="font-size:0.65rem;"><?= $u['last_activity'] ? date('d M H:i', $lastAct) : '-' ?></td>
                    <td><span style="width:8px;height:8px;border-radius:50%;display:inline-block;<?= $dot ?>"></span></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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