<?php
namespace App\Filters;

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

class PermissionFilter implements FilterInterface
{
    public function before(RequestInterface $request, $args = null)
    {
        if (!session('login')) {
            return redirect()->to('login');
        }

        $db = \Config\Database::connect();
        $url = trim(service('uri')->getPath(), '/');
        $role = session('role_id');

        $menu = $db->table('menus')->where('url', $url)->get()->getRow();

        if (!$menu) return; // bebas akses

        $perm = $db->table('menu_roles')
            ->where('role_id', $role)
            ->where('menu_id', $menu->id)
            ->get()->getRow();

        if (!$perm || !$perm->can_view) {
            die('<h2>403 - Akses Ditolak</h2>');
        }
    }

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