<?php

namespace App\Filters;

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

class PermissionFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (!$arguments) return;

        $db = \Config\Database::connect();
        $id_role = session()->get('id_role');
        $permission_name = $arguments[0]; // Nama permission yang diminta di route

        // Cek ke database apakah role ini punya permission tersebut
        $hasPermission = $db->table('role_permissions rp')
            ->join('permissions p', 'p.id_permission = rp.id_permission')
            ->where('rp.id_role', $id_role)
            ->where('p.nama_permission', $permission_name)
            ->countAllResults();

        if ($hasPermission == 0) {
            return redirect()->to('/dashboard')->with('error', 'Anda tidak memiliki izin untuk fitur ini.');
        }
    }

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