<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\Exceptions\PageNotFoundException;
use App\Helpers\globals;
use App\Models\Log\LogModel;

class AuthoFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
    	$uri      = current_url(true);
	    $segment1 = $uri->setSilent()->getSegment(1); //modul
	    $segment2 = $uri->setSilent()->getSegment(2); //menu
	    $segment3 = $uri->setSilent()->getSegment(3);
    	
	    function _cek_modul($modul){
			$usr_modul = Globals::get_modul();
			if (!in_array($modul, array_column($usr_modul, 'fname'))) {
				$res = 0;
			} else {
				$res = 1;
			}

			return $res;
		}

		function _cek_menu($menu){
			$usr_menu = Globals::get_menu();
			if (!in_array($menu, array_column($usr_menu, 'method'))) {
				$res = 0;
			} else {
				$res = 1;
			}

			return $res;
		}

		if (_cek_modul($segment1) == 0) {
			throw PageNotFoundException::forPageNotFound();
		}

        if (_cek_menu($segment2) == 0) {
			throw PageNotFoundException::forPageNotFound();
		}
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    	//SIMPAN LOG------------------------------------------------------
        $id_user = session()->get('user')['id'];

        if ($id_user) {
            $logModel = new LogModel();
            $logModel->save([
                'id_user' => $id_user,
                'aksi' => $request->getMethod() . ' ' . $request->getURI()
            ]);
        }
        //END SIMPAN LOG--------------------------------------------------
    }
}