<?php

use YOOtheme\Util\Collection;

defined('_JEXEC') or die;

$theme = JHtml::_('theme');
$attrs = ['role' => 'menu', 'class' => []]; $parents = [];

foreach ($list as $i => &$item) {

    // set active state
    if ($item->id == $active_id || ($item->type == 'alias' && $item->params->get('aliasoptions') == $active_id)) {
        $item->active = true;
    }

    if (in_array($item->id, $path)) {
        $item->active = true;
    } elseif ($item->type == 'alias') {

        $aliasToId = $item->params->get('aliasoptions');

        if (count($path) > 0 && $aliasToId == $path[count($path) - 1]) {
            $item->active = true;
        } elseif (in_array($aliasToId, $path)) {
            $item->active = true;
        }
    }

    // standardise values
    $item->url = $item->flink;
    $item->target = $item->browserNav == 1 ? '_blank' : '';
    $item->active = $item->active ?: false;
    $item->divider = $item->type === 'separator';
    $item->type = in_array($item->type, ['heading', 'separator']) ? 'header' : $item->type;

    // add to parent
    if (count($parents)) {
        $parents[count($parents) - 1]->children[] = $item;
        unset($list[$i]);
    }

    // set/remove parent
    if ($item->deeper) {
        $item->children = [];
        $parents[] = $item;
    } else if ($item->shallower) {
        array_splice($parents, -$item->level_diff);
    }

    // set menu config
    $item->config = new Collection($theme->get("menu.items.{$item->id}"));
    $item->config['icon'] = $item->params->get('menu_image');
    $item->config['icon-only'] = $item->params->get('menu_text');
}

echo JHtml::_('render', 'menu/menu', ['items' => $list, 'params' => $params, 'position' => $module->position]);
