<?php

namespace App\Filters;

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

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $employee = new Employee();

        if (!$employee->is_logged_in()) {
            return redirect()->to(base_url('login'));
        }

        // If a module_id is passed as argument, check permission
        if (!empty($arguments[0])) {
            $module_id = $arguments[0];
            $person_id = session()->get('person_id');

            if (!$employee->has_permission($module_id, $person_id)) {
                return redirect()->to(base_url('no_access/' . $module_id));
            }
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No post-processing needed
    }
}
