<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use App\Models\PermissionModel;

class PermissionGuard implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $requiredPermissionName = $arguments[0] ?? null;
        $role_id = session()->get('role_id');

        if (!$requiredPermissionName || !$role_id) {
            return redirect()->to(route_to('admin.login.show'))->with('error', 'You are not allowed to access this page.');
        }

        $db = \Config\Database::connect();
        $allowed = $db->table('role_permissions as rp')
                      ->join('permissions as p', 'p.id = rp.permission_id')
                      ->where('rp.role_id', $role_id)
                      ->where('p.name', $requiredPermissionName)
                      ->countAllResults();


        if ($allowed < 1) {
            return redirect()->to(service('request')->getUserAgent()->getReferrer() ?? route_to('admin.dashboard'))
                             ->with('error', 'Access Denied. You do not have the required permission.');
        }
    }

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