<?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 navigation menu item's URL, including nested menu items.
     *
     * The default theme can be installed before Ignite Core's navigation
     * services are registered. Returning null keeps the login page usable
     * and simply hides the optional contact link in that situation.
     *
     * @param string $url
     * @return string|null
     */
    function _menu_item_url($url)
    {
        if (! class_exists(NavigationMenu::class) || ! interface_exists(PageRepository::class)) {
            return null;
        }

        $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 and use a literal fallback when the key is unavailable.
     *
     * @param string $key
     * @param string $fallback
     * @param array $replace
     * @param string|null $locale
     * @return string
     */
    function _trans($key, $fallback, array $replace = [], ?string $locale = null)
    {
        return Lang::has($key, $locale) ? trans($key, $replace, $locale) : $fallback;
    }
}

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