<?php
// =============================================================
//  GET /api/v1/admin_rbac/role_permissions_get?role_id=7
//
//  Mobile equivalent of include/get_role_permissions.php: the full
//  permission catalogue grouped by module, plus which permission IDs
//  the given role currently holds. Same shape (permissions_grouped,
//  role_permissions) so the mobile checklist screen mirrors roles.php's
//  right-hand panel exactly.
// =============================================================

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

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

api_authenticate();
api_require_permission('manage_permissions');

$roleId = (int)($_GET['role_id'] ?? 0);
if ($roleId <= 0) Api::error(422, 'ValidationError', 'A valid role_id is required.');

$roleCheck = $conn->prepare("SELECT id, display_name FROM roles WHERE id = ?");
$roleCheck->bind_param('i', $roleId);
$roleCheck->execute();
$role = $roleCheck->get_result()->fetch_assoc();
$roleCheck->close();
if (!$role) Api::error(404, 'NotFound', 'Role not found.');

$allPermissionsResult = $conn->query("SELECT * FROM permissions ORDER BY module, id");
$allPermissions      = [];
$permissionsGrouped  = [];
while ($perm = $allPermissionsResult->fetch_assoc()) {
    $perm['id']            = (int)$perm['id'];
    $allPermissions[]      = $perm;
    $module                = $perm['module'] ?? 'General';
    $permissionsGrouped[$module][] = $perm;
}

$stmt = $conn->prepare("SELECT permission_id FROM role_permissions WHERE role_id = ?");
$stmt->bind_param('i', $roleId);
$stmt->execute();
$result = $stmt->get_result();
$rolePermissionIds = [];
while ($row = $result->fetch_assoc()) {
    $rolePermissionIds[] = (int)$row['permission_id'];
}
$stmt->close();

Api::success([
    'role_id'             => $roleId,
    'role_display_name'   => $role['display_name'],
    'permissions_grouped' => $permissionsGrouped,
    'role_permissions'    => $rolePermissionIds,
    'permissions'         => $allPermissions,
]);
