<?php
require_once dirname(__DIR__) . '/bootstrap.php';

$auth->requireRole(ROLE_APP_ADMIN);

$db = Database::getInstance();
$totalUsers  = $db->fetchOne("SELECT COUNT(*) AS cnt FROM users")['cnt'];
$activeUsers = $db->fetchOne("SELECT COUNT(*) AS cnt FROM users WHERE active = 1")['cnt'];
$recentLogins = $db->fetchAll(
    "SELECT u.id, u.username, u.last_login
     FROM users u
     WHERE u.last_login IS NOT NULL
     ORDER BY u.last_login DESC LIMIT 5"
);
// Charger les rôles pour chaque user
foreach ($recentLogins as &$_r) {
    $rs = $db->fetchAll(
        "SELECT r.name FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = ?",
        [$_r['id']]
    );
    $_r['roles'] = array_column($rs, 'name');
}
unset($_r);

View::display(__DIR__ . '/views/index.php', [
    'totalUsers'   => $totalUsers,
    'activeUsers'  => $activeUsers,
    'recentLogins' => $recentLogins,
]);
