<?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's URL, including items nested beneath a menu parent.
     *
     * @param  string  $url
     * @return string|null
     */
    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's header composer 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 fall back to a literal string when the key is missing.
     *
     * @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) ? 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);
    }
}
