<?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 $g5, $is_admin, $auth, $menu, $auth_menu;
    $sub_menu = str_replace([G5_ADMIN_URL, "/adm"], ["", ""], $_SERVER["SCRIPT_NAME"]);

    $str = "<ul class=\"gnb_2dul\">";
    foreach($this->childmenu as $key => $menu) {
      if ($is_admin != 'super')
        continue;

      if (!$menu->display) continue;
  
      if (($menu->gnb_grp_div == 1 && $gnb_grp_style == false) || ($menu->gnb_grp_div != 1 && $gnb_grp_style == true))
        $gnb_grp_div = 'gnb_grp_div';
      else
        $gnb_grp_div = '';
  
      if ($menu->gnb_grp_div == 1)
        $gnb_grp_style = 'gnb_grp_style';
      else
        $gnb_grp_style = '';
  
      $check_gnb_grp_style = "";
      if (str_replace([G5_ADMIN_URL, "/adm"], ["", ""], $menu->url) == $sub_menu || in_array($sub_menu, $menu->suburl)) {
        $check_gnb_grp_style = "check";
        $this->selected = true;
      }
  
      $str .= '<li class="gnb_2dli ' . $check_gnb_grp_style . '"><a href="' . $menu->url . '" class="gnb_2da ' . $gnb_grp_style . ' ' . $gnb_grp_div . '" data-text="' . $menu->name . '" style="--icon:\'' . $menu->icon . '\'">' . $menu->name . '</a></li>';
    }
    $str .= "</ul>";
  
    return $str;
  }
}
