<?php

namespace App\Filters;

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

class RoleFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (!session()->get('isLoggedIn')) {
            return redirect()->to('/login');
        }

        $role = session()->get('role');

        // Jika ada argumen role, periksa kecocokan
        if (!empty($arguments)) {
            $allowed = is_array($arguments) ? $arguments : [$arguments];

            if (!in_array($role, $allowed)) {
                // Redirect ke halaman sesuai role
                if ($role === 'petugas') {
                    return redirect()->to('/dashboard');
                }

                return redirect()->to('/katalog');
            }
        }
    }

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