<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Restricts a route to specific staff roles, e.g. `'role:manager'` in the
 * route's filter list. Always runs after 'auth', so a session is guaranteed
 * to exist by the time this checks the role.
 *
 * Roles are plain strings on the tenant `users` table (see Module 9): only
 * `manager` and `front_desk` exist in Phase 1. Kept as free-form strings
 * rather than a hard-coded enum so Phase 2+ roles (fnb, housekeeping, ...)
 * are just new values, not a migration.
 */
class RoleAccess implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $allowedRoles = $arguments ?? [];
        $session      = session();
        $userRole     = $session->get('userRole');

        if ($userRole === null || ($allowedRoles !== [] && ! in_array($userRole, $allowedRoles, true))) {
            return service('response')
                ->setStatusCode(403)
                ->setBody(view('errors/forbidden'));
        }

        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // no-op
    }
}
