<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class DynamicAuth implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();
        if (!$session->get('logged_in')) {
            return redirect()->to('/login')->with('error', 'Sesi berakhir, silakan login.');
        }

        $db = \Config\Database::connect();
        $router = service('router');
        
        // Dapatkan rute internal yang sedang berjalan saat ini
        $currentURI = $router->controllerName() . '::' . $router->methodName();
        
        // Cari segmen URL saat ini
        $uri = $request->getUri()->getPath();
        $segments = explode('/', $uri);
        $matchRoute = isset($segments[0]) ? $segments[0] . (isset($segments[1]) ? '/' . $segments[1] : '') : '';

        // Validasi kecocokan rute di tabel menu database
        $menu = $db->table('menus')->where('url_rute', $matchRoute)->get()->getRowArray();
        
        if ($menu) {
            $allowedRoles = explode(',', $menu['role_akses']);
            if (!in_array($session->get('role'), $allowedRoles)) {
                return redirect()->to('/login')->with('error', 'Hak Akses Anda Dicabut oleh Superadmin.');
            }
        }
    }

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