<?php
// =============================================================
//  GET /api/v1/admin_rbac/roles_list
//
//  Mobile equivalent of app/roles.php's left-hand role list. Adds a
//  permission_count and user_count per role (the desktop page fetches
//  permission_count separately via AJAX per-click, and user_count only
//  inside the delete handler) so the mobile list and delete-safety UI
//  can both be driven from one call instead of one-per-role fetches.
//  Gated on manage_permissions, same as roles.php.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Api::error(405, 'MethodNotAllowed', 'Use GET');
}

api_authenticate();
api_require_permission('manage_permissions');

$roles = $conn->query("
    SELECT
        r.id, r.name, r.display_name, r.description, r.is_system,
        (SELECT COUNT(*) FROM role_permissions rp WHERE rp.role_id = r.id) AS permission_count,
        (SELECT COUNT(*) FROM users u WHERE u.role_id = r.id) AS user_count
    FROM roles r
    ORDER BY r.display_name
")->fetch_all(MYSQLI_ASSOC);

foreach ($roles as &$role) {
    $role['id']               = (int)$role['id'];
    $role['is_system']        = (bool)$role['is_system'];
    $role['permission_count'] = (int)$role['permission_count'];
    $role['user_count']       = (int)$role['user_count'];
}
unset($role);

Api::success(['roles' => $roles]);
