<?php
declare(strict_types=1);

namespace App\Middleware;

use Core\Middleware;
use Core\Session;

/**
 * Restrict access to controllers based on user role.
 * Configure via: protected static array $allowedRoles = ['FuelDesk','Administrator'];
 * inside the controller, then list this middleware in middleware().
 */
final class RoleGate implements Middleware
{
    public function handle(array $context): void
    {
        $fqcn = $context['controller'] ?? '';
        if (!class_exists($fqcn) || !property_exists($fqcn, 'allowedRoles')) return;

        $allowed = $fqcn::$allowedRoles;
        $user = Session::user();
        if (!$user || !in_array($user['role'] ?? '', $allowed, true)) {
            http_response_code(403);
            echo '<h1>403 — Not authorised</h1>';
            exit;
        }
    }
}
