<?php

namespace App\Filters;

use App\Modules\Auth\Entities\Role;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Dashboard Admin Page Filter
 *
 * For HTML dashboard pages that require ADMIN role. Redirects to /login if not logged in,
 * or to /dashboard with error flash if not admin.
 */
class DashboardAdminPageFilter implements \CodeIgniter\Filters\FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $authService = new AuthService();
        $user       = $authService->currentUser();

        if ($user === null) {
            return redirect()->to('/login')->with('redirect', uri_string());
        }

        $roles = $user['roles'] ?? [];
        $codes = array_column($roles, 'role_code');
        if (!in_array(Role::CODE_ADMIN, $codes, true)) {
            return redirect()->to('/dashboard')->with('error', 'Akses hanya untuk Admin.');
        }

        return null;
    }

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