<?php

namespace Ignite\Core\Models\Menu;

use Ignite\Core\Contracts\CanDisplayInMenu;
use Ignite\Core\Events\Menus\UserMenuPreCompile;
use Illuminate\Support\Str;
use Spatie\Menu\Laravel\Facades\Menu;
use Spatie\Menu\Laravel\Menu as SpatieMenu;

class UserNavigationMenu extends NavigationMenu
{
    /**
     * Add a link to the menu.
     *
     * @param CanDisplayInMenu $item
     * @param SpatieMenu $menu
     */
    public function addLink(CanDisplayInMenu|array $item, $menu)
    {
        $link = $menu->link($item->getUrl(), $this->buildLabel($item));
        $link->addItemParentClass('user-menu-item');
        $link->setActive(function ($link) use ($item) {
            if ($link->url() === url()->current()) {
                return true;
            }

            if (Str::contains(url()->current(), $link->url()) && url($link->url()) !== url('/')) {
                return true;
            }

            return false;
        });
    }

    /**
     * Build the menu.
     *
     * @param  \Illuminate\Support\Collection|array $links
     * @return SpatieMenu
     */
    public function buildMenu($links): SpatieMenu
    {
        return Menu::build($links->toArray(), function ($menu, $item) {
            if (is_array($item)) {
                $item = new Item($item['url'], $item['label'], $item['position'], $item['allow'], $item['children'], $item['icon'], $item['badge']);
            }

            if (! $item->hasChildren()) {
                $this->addLink($item, $menu);
            } else {
                $menu->submenu(
                    $this->addSubmenuLink($item),
                    $this->buildMenu($item->getChildren())
                         ->addClass('dropdown-menu page-nav-dropdown')
                         ->addParentClass('user-nav-item user-nav-item--has-dropdown dropdown')
                );
            }
        });
    }

    /**
     * Render the menu.
     */
    public function render(): string
    {
        event(new UserMenuPreCompile($this));

        $this->menu = $this->buildMenu($this->getItems())->addClass('nav nav-pills nav-stacked');

        return $this->menu->render();
    }
}
