<?php

namespace App\Filters;

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

class RoleFilter implements FilterInterface
{
    /**
     * Usage: $routes->group('admin', ['filter' => 'role:admin,super_admin'], ...)
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! auth()->loggedIn()) {
            return redirect()->to('/login');
        }

        if (empty($arguments)) {
            return;
        }

        $user = auth()->user();

        foreach ($arguments as $group) {
            if ($user->inGroup($group)) {
                return; // Access granted
            }
        }

        return redirect()->to('/')->with('error', 'Anda tidak memiliki akses ke halaman ini.');
    }

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