<?php
// components/Permission.php
namespace Components;

class Permission
{
    /**
     * All known roles in the system (static list for mock permission system)
     */
    public static function allRoles(): array
    {
        return ['saas_user', 'saas_superuser', 'saas_admin', 'core_user', 'core_admin'];
    }

    /**
     * Determine the current user role (mocked).
     * Priority: GET[role] -> $_SERVER['BEEZUI_ROLE'] -> env BEEZUI_ROLE -> default 'core_admin'.
     */
    public static function currentRole(): string
    {
//        $role = $_GET['role'] ?? ($_SERVER['BEEZUI_ROLE'] ?? getenv('BEEZUI_ROLE')) ?? 'core_admin';

        $role = 'core_admin';
//        $role = 'saas_superuser';

        $role = strtolower((string)$role);
        // keep only letters and underscore
        $role = preg_replace('/[^a-z_]/', '', $role);
        $valid = self::allRoles();
        if (!in_array($role, $valid, true)) {
            $role = 'core_admin';
        }
        return $role;
    }

    /**
     * Check if the current user has access to a field definition.
     * If no permissions map is provided, allow access by default.
     * Supports both 'permissions' (map role=>bool) and legacy 'permission'.
     */
    public static function hasAccess(array $def): bool
    {
        $map = $def['permissions'] ?? ($def['permission'] ?? null);
        if (!is_array($map)) {
            return true; // no restriction
        }
        $role = self::currentRole();
        if (array_key_exists($role, $map)) {
            return (bool)$map[$role];
        }
        // Unknown role in the map -> deny by default for safety
        return false;
    }

    /**
     * Return a list of roles that are explicitly NOT permitted for the given field definition.
     * Only considers roles present in the permissions map. If no map, returns empty array.
     */
    public static function deniedRoles(array $def): array
    {
        $map = $def['permissions'] ?? ($def['permission'] ?? null);
        if (!is_array($map)) { return []; }
        $denied = [];
        foreach ($map as $role => $allowed) {
            if (!$allowed) { $denied[] = (string)$role; }
        }
        return $denied;
    }
}
