<?php
if (!defined("__ADVDIR__"))
  exit();

// if not loaded load directly
include_once __ADVDIR__ . "/classes/menu/menu.class.php";

class MenuCategory extends Menu
{
  public $last_menu;

  public $key;
  public $childmenu;
  public $selected;

  public function __construct($key, $mid, $name, $url, $display = true, $order = 0, $icon = '', $gnb_grp_div = 0)
  {
    $this->key = $key;
    $this->selected = false;
    $this->childmenu = [];
    parent::__construct($mid, $name, $url, $display, $order, $icon, $gnb_grp_div);
  }

  public function addChild($childMenu)
  {
    $this->last_menu = $childMenu;
    $this->childmenu[] = $childMenu;
    $this->orderMenu();
  }

  public function addChildMenu($mid, $name, $url, $display = true, $order = 0, $icon = '', $gnb_grp_div = 0)
  {
    $menuitem = new Menu($mid, $name, $url, $display, $order, $icon, $gnb_grp_div);
    $this->last_menu = $menuitem;
    $this->childmenu[] = $menuitem;
    $this->orderMenu();
  }

  public function orderMenu()
  {
    usort($this->childmenu, function ($a, $b) {
      return $a->order - $b->order;
    });
  }

  public function getLastAddedMenu()
  {
    return $this->last_menu;
  }
  public function buildHtml()
  {
    global $is_admin;

    $sub_menu = preg_replace('/^.*\/([^\/]+\.php)$/', '/$1', str_replace([G5_ADMIN_URL, '/adm'], ['', ''], $_SERVER['SCRIPT_NAME']));

    $str = '';
    $gnb_grp_style = false;

    foreach ($this->childmenu as $menu) {
      if ($is_admin != 'super' || !$menu->display) {
        continue;
      }

      $gnb_grp_div = (($menu->gnb_grp_div == 1 && !$gnb_grp_style) || ($menu->gnb_grp_div != 1 && $gnb_grp_style)) ? 'gnb_grp_div' : '';
      $gnb_grp_style = $menu->gnb_grp_div == 1 ? 'gnb_grp_style' : '';

      $menu_url = preg_replace('/^.*\/([^\/]+\.php)$/', '/$1', str_replace([G5_ADMIN_URL, '/adm'], ['', ''], $menu->url));
      $check_gnb_grp_style = '';

      if (
        $menu_url == $sub_menu || in_array($sub_menu, array_map(function ($url) {
          return preg_replace('/^.*\/([^\/]+\.php)$/', '/$1', str_replace([G5_ADMIN_URL, '/adm'], ['', ''], $url));
        }, $menu->suburl))
      ) {
        $check_gnb_grp_style = 'check';
        $this->selected = true;
      }

      $str .= sprintf(
        '<li class="gnb_2dli %s"><a href="%s" class="gnb_2da %s %s" data-text="%s" style="--icon:\'%s\'">%s</a></li>',
        $check_gnb_grp_style,
        $menu->url,
        $gnb_grp_style,
        $gnb_grp_div,
        $menu->name,
        $menu->icon,
        $menu->name
      );
    }

    $ul_class = $this->selected ? 'gnb_2dul" style="display: block"' : 'gnb_2dul"';
    return "<ul class=\"{$ul_class}\">{$str}</ul>";
  }
}
