<?php

namespace App\Filters;

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

class RoleFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
{
    $user = $request->user ?? null;

    if (!$user || empty($arguments)) {
        return service('response')
            ->setStatusCode(403)
            ->setJSON([
                'status'  => false,
                'message' => 'Akses ditolak'
            ]);
    }

    // 🔥 FIX: akses sebagai OBJECT, bukan array
    $userRole = $user->role ?? null;

    if (!$userRole || !in_array($userRole, $arguments, true)) {
        return service('response')
            ->setStatusCode(403)
            ->setJSON([
                'status'  => false,
                'message' => 'Role tidak memiliki izin'
            ]);
    }
}


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