<?php

namespace App\Filters;

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

class AdminOnlyFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $roles = session()->get('roles') ?? [];
        if (!in_array('admin', $roles) && !in_array('superadmin', $roles)) {
            $uri = current_url(true);
            $segment1 = $uri->getSegment(1);
            $segment2 = $uri->getSegment(2);

            // If they are 'keuangan', they can only access pengajuan and laporan
            if (in_array('keuangan', $roles)) {
                $allowedPaths = ['pengajuan', 'laporan'];
                $isAllowed = ($segment1 === 'keuangan' && in_array($segment2, $allowedPaths));

                if (!$isAllowed) {
                    return redirect()->to(base_url('keuangan/laporan'))->with('error', 'Akses Terbatas: Menu tersebut hanya untuk Admin.');
                }
            } else {
                // Not admin, superadmin, or keuangan
                return redirect()->to('/')->with('error', 'Akses Ditolak.');
            }
        }
    }

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