<?php

use Illuminate\Support\Facades\Lang;
use Ignite\Core\Contracts\Repositories\PageRepository;
use Ignite\Core\Models\Menu\NavigationMenu;

if (! function_exists('_menu_item_url')) {
    /** Get a menu item URL, including nested menu items. */
    function _menu_item_url($url)
    {
        $findMenuItem = function ($items) use (&$findMenuItem, $url) {
            foreach ($items as $item) {
                if ($item->getMenuKey() === $url) {
                    return $item;
                }

                if ($item->hasChildren() && ($match = $findMenuItem($item->getChildren()))) {
                    return $match;
                }
            }

            return null;
        };

        $menu = app(NavigationMenu::class);

        // Login content is evaluated before the layout builds the navigation menu.
        if ($menu->getItems()->isEmpty()) {
            $menu->merge(app(PageRepository::class)->findForNavigation());
        }

        $menuItem = $findMenuItem($menu->getItems());

        return $menuItem ? $menuItem->getUrl() : null;
    }
}

if (! function_exists('_trans')) {
    /** Translate a key, falling back to the supplied literal when it is absent. */
    function _trans($key, $fallback, array $replace = [], ?string $locale = null)
    {
        return Lang::has($key) ? trans($key, $replace, $locale) : $fallback;
    }
}

if (! function_exists('___')) {
    /** Alias for _trans(). */
    function ___($key, $fallback, array $replace = [], ?string $locale = null)
    {
        return _trans($key, $fallback, $replace, $locale);
    }
}
