<?php
class Gate
{
    public static function can(string $permission): bool
    {
        if (!Auth::check()) {
            return false;
        }
        $perms = Auth::permissions();
        if (in_array('*', $perms, true)) {
            return true; // super_admin
        }
        return in_array($permission, $perms, true);
    }

    public static function canAny(array $permissions): bool
    {
        foreach ($permissions as $p) {
            if (self::can($p)) {
                return true;
            }
        }
        return false;
    }

    public static function canAll(array $permissions): bool
    {
        foreach ($permissions as $p) {
            if (!self::can($p)) {
                return false;
            }
        }
        return true;
    }

    public static function authorize(string $permission): void
    {
        if (!self::can($permission)) {
            http_response_code(403);
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                Response::json(['success' => false, 'message' => 'Forbidden'], 403);
            }
            $viewPath = ROOT_PATH . '/views/errors/403.php';
            if (file_exists($viewPath)) {
                include $viewPath;
            } else {
                echo '<h1>403 Forbidden</h1><p>You do not have permission to access this resource.</p>';
            }
            exit;
        }
    }
}