<?php
declare(strict_types=1);

namespace App\Core\Registries;

final class MenuRegistry
{
    private static array $items = [];

    public static function register(string $key, array $definition): void
    {
        self::$items[$key] = $definition;
    }

    public static function get(string $key): ?array
    {
        return self::$items[$key] ?? null;
    }

    public static function getAll(): array
    {
        $items = self::$items;
        uasort($items, fn($a, $b) => ($a['order'] ?? 999) <=> ($b['order'] ?? 999));
        return $items;
    }

    public static function getVisible(array $userPermissions): array
    {
        $visible = [];
        foreach (self::getAll() as $key => $item) {
            $perm = $item['permission'] ?? null;
            if ($perm === null || in_array($perm, $userPermissions) || in_array('*', $userPermissions)) {
                $filtered = $item;
                if (!empty($item['children'])) {
                    $filtered['children'] = array_filter($item['children'], function ($child) use ($userPermissions) {
                        $cp = $child['permission'] ?? null;
                        return $cp === null || in_array($cp, $userPermissions) || in_array('*', $userPermissions);
                    });
                    usort($filtered['children'], fn($a, $b) => ($a['order'] ?? 999) <=> ($b['order'] ?? 999));
                }
                $visible[$key] = $filtered;
            }
        }
        return $visible;
    }

    public static function has(string $key): bool
    {
        return isset(self::$items[$key]);
    }
}