<?php

namespace App\Filters;

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

class RoleFilter implements FilterInterface
{
    protected $roles;

    public function __construct(array $roles = [])
    {
        $this->roles = $roles;
    }

    public function before(RequestInterface $request, $arguments = null)
    {
        $auth = service('auth');

        if (!$auth->check()) {
            return redirect()->to('/login');
        }

        $user = $auth->user();

        // Pastikan user memiliki role yang diizinkan
        if (!in_array($user->role, $this->roles)) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Tidak perlu
    }
}
