<?php
function ph_module_registry(): array {
    static $registry = null;
    if ($registry !== null) return $registry;
    $file = ROOT_PATH . '/app/module_registry.json';
    $json = is_file($file) ? file_get_contents($file) : '{}';
    $registry = json_decode($json, true) ?: [];
    return $registry;
}
function ph_admin_groups(): array { return ph_module_registry()['admin_groups'] ?? []; }
function ph_admin_modules(): array { return ph_module_registry()['admin_modules'] ?? []; }
function ph_admin_module(string $key): ?array {
    foreach (ph_admin_modules() as $module) if (($module['key'] ?? '') === $key) return $module;
    return null;
}
function ph_panel_groups(string $panel): array { return ph_module_registry()[$panel . '_groups'] ?? []; }
function ph_module_slug(string $title): string { return strtolower(trim(preg_replace('/[^a-z0-9]+/i','-', $title), '-')); }

function ph_admin_module_by_file(string $file): ?array {
    $file = basename($file);
    foreach (ph_admin_modules() as $module) {
        if (($module['file'] ?? '') === $file) return $module;
    }
    return null;
}

function ph_admin_module_key_by_file(string $file): string {
    $module = ph_admin_module_by_file($file);
    if ($module) return (string)($module['key'] ?? '');
    $key = basename($file, '.php');
    return $key === 'index' ? 'dashboard' : ph_module_slug($key);
}

function ph_visible_admin_groups(): array {
    $groups = ph_admin_groups();
    if (App\Core\Auth::role() === 'admin') return $groups;
    $visible = [];
    foreach ($groups as $group => $items) {
        foreach ($items as $item) {
            $key = (string)($item[0] ?? ph_admin_module_key_by_file((string)($item[2] ?? '')));
            if (App\Core\Auth::canAdminModule($key)) $visible[$group][] = $item;
        }
    }
    return $visible;
}
