<?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)
    {
        $user = $request->user ?? null;

        if (!$user) {
            return service('response')->setJSON([
                'status' => false,
                'message' => 'User tidak ditemukan'
            ])->setStatusCode(401);
        }

        // role dari token
        $userRole = $user->role;

        // role yang diizinkan dari route
        $allowedRoles = $arguments;

        if (!in_array($userRole, $allowedRoles)) {
            return service('response')->setJSON([
                'status' => false,
                'message' => 'Akses ditolak (role tidak sesuai)'
            ])->setStatusCode(403);
        }
    }

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