<?php

namespace App\Filters;

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

class AppRoleFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! auth()->loggedIn()) {
            return redirect()->route('login');
        }

        $roles = array_filter((array) $arguments);
        if ($roles === []) {
            return null;
        }

        $userId = auth()->id();

        if ($userId === null || ! service('authorization')->userHasRole((int) $userId, $roles)) {
            return service('response')
                ->setStatusCode(ResponseInterface::HTTP_FORBIDDEN)
                ->setBody(view('errors/html/error_403', [
                    'message' => 'Nu ai permisiunea necesara pentru aceasta sectiune.',
                ]));
        }

        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): void
    {
    }
}
