<?php
// =============================================================
//  GET /api/v1/admin_rbac/permissions_list
//
//  Mobile equivalent of app/manage_permission.php's main table: every
//  permission with its role usage count (0 = "not assigned anywhere",
//  same red/green distinction the desktop page makes), plus the
//  distinct module list so the mobile screen can offer the same
//  filter chips without a separate request.
// =============================================================

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

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

api_authenticate();
api_require_permission('manage_permissions');

$permissions = $conn->query("
    SELECT
        p.id, p.name, p.description, p.module, p.display_name,
        COUNT(rp.role_id) AS role_count
    FROM permissions p
    LEFT JOIN role_permissions rp ON rp.permission_id = p.id
    GROUP BY p.id
    ORDER BY p.module ASC, p.name ASC
")->fetch_all(MYSQLI_ASSOC);

$modulesStats = [];
foreach ($permissions as &$perm) {
    $perm['id']         = (int)$perm['id'];
    $perm['role_count'] = (int)$perm['role_count'];
    $module = $perm['module'] ?: 'uncategorized';
    $modulesStats[$module] = ($modulesStats[$module] ?? 0) + 1;
}
unset($perm);

$totalPermissions = count($permissions);
$assignedCount    = count(array_filter($permissions, fn($p) => $p['role_count'] > 0));

Api::success([
    'permissions'        => $permissions,
    'modules_stats'      => $modulesStats,
    'total_permissions'  => $totalPermissions,
    'assigned_count'     => $assignedCount,
    'unassigned_count'   => $totalPermissions - $assignedCount,
]);
