<?php
/**
 * GET /api/lab/get_roles.php
 * Devuelve todos los roles con sus módulos asignados.
 * Solo admins.
 */
require_once __DIR__ . '/_helpers.php';
requireAdmin();

$db = Database::getInstance();

$roles = $db->fetchAll("SELECT id, name, slug, description, color, home_page, is_system, created_at FROM roles ORDER BY id ASC");

foreach ($roles as &$role) {
    $mods = $db->fetchAll(
        "SELECT module_slug FROM role_modules WHERE role_id = ? ORDER BY module_slug",
        [$role['id']]
    );
    $role['modules']    = array_column($mods, 'module_slug');
    $role['is_system']  = (bool)$role['is_system'];
    $role['user_count'] = (int)$db->fetch(
        "SELECT COUNT(*) AS c FROM admin_users WHERE role_id = ?",
        [$role['id']]
    )['c'];
}
unset($role);

jsonOk(['roles' => $roles]);
