<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Auth;

class RequireRole
{
    /** @param array<int,string> $roles */
    public function __construct(private array $roles) {}

    public function handle(): void
    {
        if (!Auth::check()) {
            $_SESSION['_flash']['error'] = t('hub.login.required');
            $_SESSION['after_login'] = $_SERVER['REQUEST_URI'] ?? '/hub';
            redirect('/hub/login');
        }
        if (!Auth::hasRole($this->roles)) {
            http_response_code(403);
            require MAT_ROOT . '/src/Views/errors/403.php';
            exit;
        }
        $u = Auth::user();
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        $allowedPaths = ['/hub/change-password', '/hub/setup-pin', '/hub/logout'];
        $onAllowed = false;
        foreach ($allowedPaths as $p) { if (str_starts_with($uri, $p)) { $onAllowed = true; break; } }

        // Force password change if flagged (temp password from admin)
        if ($u && !empty($u['must_change_password']) && !$onAllowed) {
            redirect('/hub/change-password');
        }

        // Force first-login PIN setup — STAFF and ARTIST, not ADMIN
        if ($u && in_array($u['role'] ?? '', ['STAFF', 'ARTIST'], true) && empty($u['pin_hash']) && !$onAllowed) {
            redirect('/hub/setup-pin');
        }
    }
}
