<?php
declare(strict_types=1);

function loadJson(string $path): array {
  if (!is_file($path)) return [];
  return json_decode(file_get_contents($path), true) ?? [];
}

function getUserRolesFromJson(string $username, string $usersJsonPath = __DIR__ . '/users.json'): array {
  $data = loadJson($usersJsonPath);
  foreach ($data['users'] ?? [] as $u) {
    if (strcasecmp($u['username'] ?? '', $username) === 0) {
      return $u['roles'] ?? [];
    }
  }
  return [];
}

function buildPermissions(array $roles, string $permissionsJsonPath = __DIR__ . '/permissions.json'): array {
  $map = loadJson($permissionsJsonPath);
  $out = [];
  foreach ($roles as $role) {
    if (!isset($map['roles'][$role])) continue;
    foreach ($map['roles'][$role] as $perm => $val) {
      $out[$perm] = (bool)$val;
    }
  }
  return $out;
}

function can(array $allowlist, string $key): bool {
  if (isset($allowlist[$key])) return (bool)$allowlist[$key];
  foreach ($allowlist as $pattern => $val) {
    if ($val !== true) continue;
    $glob = str_replace('.', '/', $pattern);
    $needle = str_replace('.', '/', $key);
    if (fnmatch($glob, $needle)) return true;
  }
  return false;
}

function resolveUserPermissions(string $username): array {
  $roles = getUserRolesFromJson($username);
  $perms = buildPermissions($roles);
  return [$roles, $perms];
}
