<?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 (! session()->get('is_logged_in')) {
            return redirect()->to('/user/login');
        }

        $required = $arguments[0] ?? null;
        if ($required) {
            $perms = session('permissions') ?? [];
            if (! in_array($required, $perms, true)) {
                return redirect()->to('/')->with('error', 'Access denied.');
            }
        }

        return null;
    }

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