<?php

namespace App\Filters;

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

class RoleFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Bypass auth for localhost/127.0.0.1
        $ip = $request->getIPAddress();
        if ($ip === '127.0.0.1' || $ip === '::1') {
            return;
        }
        
        $session = session();

        // Cek login
        if (! $session->get('isLoggedIn')) {
            return redirect()->to('/login');
        }

        // Kalau filter menerima argumen dari routes misal (role:1,2,3), lalu periksa denagn userlevel
        if ($arguments) {
            
            $allowedRoles = array_map('intval', $arguments); // ubah arguments dalam bentuk array string ke array integer
            $userRoleId = (int) $session->get('userroleid');

            // Bandingkan dengan userlevel
            if (! in_array($userRoleId, $allowedRoles)) {
                return redirect()->to('/unauthorized'); // misalnya ke halaman error
            }
        }
    }

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