<?php

declare(strict_types=1);

use Config\AdminAccess;

if (! function_exists('admin_ion_roles')) {
    /**
     * Nama grup Ion dari sesi (sudah dinormalisasi string).
     *
     * @return list<string>
     */
    function admin_ion_roles(): array
    {
        $raw = session()->get('admin_ion_groups');
        if (! is_array($raw)) {
            return [];
        }

        $out = [];
        foreach ($raw as $g) {
            $s = strtolower(trim((string) $g));
            if ($s !== '') {
                $out[] = $s;
            }
        }

        return array_values(array_unique($out));
    }
}

if (! function_exists('rbac_enforce_ion')) {
    /**
     * Grup Ion hanya relevan bila login dari tabel admin_users (Ion Auth).
     * Login `pegawai` saja (tanpa admin terhubung) memakai {@see AdminAccess::$pegawaiPanelFeatures}.
     */
    function rbac_enforce_ion(): bool
    {
        return session()->get('admin_auth_source') === 'admin_users';
    }
}

if (! function_exists('hasRole')) {
    function hasRole(string $role): bool
    {
        $want = strtolower(trim($role));
        if ($want === '') {
            return false;
        }

        foreach (admin_ion_roles() as $g) {
            if ($g === $want) {
                return true;
            }
        }

        return false;
    }
}

if (! function_exists('hasAnyRole')) {
    /**
     * @param list<string>|array<int, string> $roles
     */
    function hasAnyRole(array $roles): bool
    {
        foreach ($roles as $r) {
            if (hasRole((string) $r)) {
                return true;
            }
        }

        return false;
    }
}

if (! function_exists('canAccess')) {
    /**
     * Cek akses fitur berdasarkan `Config\AdminAccess::$features`.
     */
    function canAccess(string $feature): bool
    {
        /** @var AdminAccess $cfg */
        $cfg = config('AdminAccess');
        if (! isset($cfg->features[$feature])) {
            return false;
        }

        if (! rbac_enforce_ion()) {
            return in_array($feature, $cfg->pegawaiPanelFeatures, true);
        }

        $required = $cfg->features[$feature];
        if ($required === []) {
            return true;
        }

        if (admin_ion_roles() === []) {
            return false;
        }

        return hasAnyRole($required);
    }
}
