	<?php
/**
 *---------------------------------------------------------------------------------------
 * @package       VirtuePlanet Framework for Joomla!
 *---------------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       Abhishek Das
 * @email         info@virtueplanet.com
 * @link          https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
 */
defined('_JEXEC') or die;

class VPFrameworkMenu
{
	public static function getList(&$params)
	{
		$app  = JFactory::getApplication();
		$menu = $app->getMenu();

		// Get active menu item
		$base   = self::getBase($params);
		$user   = JFactory::getUser();
		$levels = $user->getAuthorisedViewLevels();
		
		asort($levels);
		
		$key   = 'megamenu_items' . $params->toString() . implode(',', $levels) . '.' . $base->id;
		$cache = JFactory::getCache('vp_framework', '');
		$items = $cache->get($key);
		
		if (!$items)
		{
			$path           = $base->tree;
			$start          = (int) $params->get('startLevel');
			$end            = (int) $params->get('endLevel');
			$showAll        = $params->get('showAllChildren');
			$items          = $menu->getItems('menutype', $params->get('menutype'));
			$modParents     = array();
			$hidden_parents = array();
			
			$menus = array();
			$lastitem = 0;
			
			if ($items)
			{
				foreach ($items as $item)
				{
					if (($start && $start > $item->level)
						|| ($end && $item->level > $end)
						|| (!$showAll && $item->level > 1 && !in_array($item->parent_id, $path))
						|| (isset($modParents[$item->parent_id]))
						|| ($start > 1 && !in_array($item->tree[$start - 2], $path)))
					{
						continue;
					}
					
					// Exclude item with menu item option set to exclude from menu modules
					if (($item->params->get('menu_show', 1) == 0) || in_array($item->parent_id, $hidden_parents))
					{
						$hidden_parents[] = $item->id;
						unset($items[$i]);
						continue;
					}
					
					$menus[] = $item;
					
					if(in_array($item->params->get('mega_subcontent'), array('mod', 'pos')))
					{
						$item->parent = true;
						$item->deeper = true;
						$modParents[$item->id] = $item;
						
						$menuI               = new stdClass;
						$menuI->id           = '';
						$menuI->type         = 'module';
						$menuI->link         = '';
						$menuI->title        = '';
						$menuI->params       = new JRegistry;
						$menuI->mega_class   = htmlspecialchars($item->params->get('mega_class', ''), ENT_COMPAT, 'UTF-8', false);
						$menuI->content      = $item->params->get('mega_subcontent', null);
						$menuI->modules      = (array) $item->params->get('modules', array());
						$menuI->modules      = array_filter($menuI->modules);
						$menuI->position     = (string) $item->params->get('mod_position', null);
						$menuI->parent       = false;
						$menuI->parent_id    = $item->id;
						$menuI->anchor_css   = '';
						$menuI->anchor_title = '';
						$menuI->level        = $item->level + 1;
						
						$menus[] = $menuI;
					}
				}
				
				if($params->get('merge_vm_category_menu', 0) == 'start')
				{
					$categories = VPFrameworkVM::getCategories($params);
					
					if(!empty($categories))
					{
						$menus = array_merge($categories, $menus);
					}
				}
				elseif($params->get('merge_vm_category_menu', 0) == 'end')
				{
					$categories = VPFrameworkVM::getCategories($params);
					
					if(!empty($categories))
					{
						$menus = array_merge($menus, $categories);
					}
				}
			}

			if ($menus)
			{
				$subWidths = array();
				
				foreach ($menus as $i => $item)
				{
					$item->deeper     = false;
					$item->shallower  = false;
					$item->level_diff = 0;

					if (isset($menus[$lastitem]))
					{
						$menus[$lastitem]->deeper     = ($item->level > $menus[$lastitem]->level);
						$menus[$lastitem]->shallower  = ($item->level < $menus[$lastitem]->level);
						$menus[$lastitem]->level_diff = ($menus[$lastitem]->level - $item->level);
					}
					
					if($item->type != 'vmcategory')
					{
						$submenus = $menu->getItems('parent_id', (int) $item->id, false);
						$item->parent = (boolean) (!empty($submenus) || isset($modParents[$item->id]));
					}
					
					$item->hasModule = (boolean) isset($modParents[$item->id]);

					$lastitem     = $i;
					$item->active = isset($item->active) ? $item->active : false;
					$item->flink  = $item->link;

					// Reverted back for CMS version 2.5.6
					switch ($item->type)
					{
						case 'separator':
						case 'heading':
						case 'module':
						case 'vmcategory':
							// No further action needed.
							break;

						case 'url':
							if ((strpos($item->link, 'index.php?') === 0) && (strpos($item->link, 'Itemid=') === false))
							{
								// If this is an internal Joomla link, ensure the Itemid is set.
								$item->flink = $item->link . '&Itemid=' . $item->id;
							}
							break;

						case 'alias':
							// If this is an alias use the item id stored in the parameters to make the link.
							$item->flink = 'index.php?Itemid=' . $item->params->get('aliasoptions');
							break;

						default:
							$router = $app::getRouter();

							if ($router->getMode() == JROUTER_MODE_SEF)
							{
								$item->flink = 'index.php?Itemid=' . $item->id;

								if (isset($item->query['format']) && $app->get('sef_suffix'))
								{
									$item->flink .= '&format=' . $item->query['format'];
								}
							}
							else
							{
								$item->flink .= '&Itemid=' . $item->id;
							}
							break;
					}

					if (strcasecmp(substr($item->flink, 0, 4), 'http') && (strpos($item->flink, 'index.php?') !== false))
					{
						$item->flink = JRoute::_($item->flink, true, $item->params->get('secure'));
					}
					else
					{
						$item->flink = JRoute::_($item->flink);
					}

					// We prevent the double encoding because for some reason the $item is shared for menu modules and we get double encoding
					// when the cause of that is found the argument should be removed
					$item->title        = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8', false);
					$item->description	= htmlspecialchars($item->params->get('mega_desc'), ENT_COMPAT, 'UTF-8', false);
					
					if($item->type != 'vmcategory')
					{
						$item->cols  = (int) $item->params->get('mega_cols', 1);
						$item->group = ($item->level) > 1 ? $item->params->get('mega_group', 0) : 0;
						
						$item->width = strtolower(trim($item->params->get('mega_width', 0)));
						if(!in_array($item->width, array('auto', 'justify')))
						{
							$item->width = (float) $item->width;
						}
						$item->width = !empty($item->width) ? $item->width : ($item->cols == 1 ? 'auto' : 'justify');
						
						$item->colw = $item->params->get('mega_colw', '');
						$item->colw = trim($item->colw);
						
						$reset = false;
						
						if($item->cols > 1)
						{
							if(!empty($item->colw) && strstr($item->colw, PHP_EOL))
							{
								$item->colw = explode(PHP_EOL, $item->colw);
								$item->colw = array_map('intval', $item->colw);
								
								if((array_sum($item->colw) != 12) || (count($item->colw) != $item->cols))
								{
									$reset = true;
								}
							}
							else
							{
								$reset = true;
							}
						}
						else
						{
							$item->colw = array(12);
						}

						if($reset)
						{
							$width = floor(12 / $item->cols);
							$item->colw = array();
							
							for ($i = 1; $i <= $item->cols; $i++) 
							{
								$item->colw[] = $width;
							}
						}

						if(!empty($submenus))
						{
							$pos = 0;
							
							foreach($submenus as $k => $submenu)
							{
								$pos = ($k >= count($item->colw)) ? 0 : $pos;
								$subWidths[$submenu->id] = isset($item->colw[$pos]) ? $item->colw[$pos] : 12;
								$pos++;
							}
						}
						
						if(isset($subWidths[$item->id]))
						{
							$item->subwidth = $subWidths[$item->id];
						}
					}
					
					if($item->type != 'module' && $item->type != 'vmcategory')
					{
						$item->mega_class  = htmlspecialchars($item->params->get('mega_class', ''), ENT_COMPAT, 'UTF-8', false);
						$item->content     = $item->params->get('mega_subcontent', null);
						$item->modules     = (array) $item->params->get('modules', array());
						$item->modules     = array_filter($item->modules);
						$item->position    = (string) $item->params->get('mod_position', null);
					}
					elseif($item->type != 'vmcategory')
					{
						$item->contents = array();

						if(isset($modParents[$item->parent_id]))
						{
							$parentItem = $modParents[$item->parent_id];
							$cols = $parentItem->cols;
							$colw = $parentItem->colw;
							
							if($item->content == 'mod' && !empty($item->modules))
							{
								$pos = 0;
								foreach($item->modules as $key => $module_id)
								{
									$pos = ($key >= count($colw)) ? 0 : $pos;
									$module = VPFrameworkModule::get($module_id);
									
									if(empty($module))
									{
										continue;
									}
									
									$content = new stdClass;
									$content->html = JModuleHelper::renderModule($module, array('style' => 'MegaHTML'));
									
									if($cols == 1)
									{
										$content->subwidth = 12;
									}
									else
									{
										$content->subwidth = isset($colw[$pos]) ? $colw[$pos] : 12;
									}
									
									$item->contents[] = $content;
									$pos++;
								}
							}
							elseif($item->content == 'pos' && !empty($item->position))
							{
								$modules = VPFrameworkModule::getPosition($item->position);
								
								if(!empty($modules))
								{
									$pos = 0;
									foreach($modules as $key => $module)
									{
										$pos = ($key >= count($colw)) ? 0 : $pos;
										$content = new stdClass;
										$module->params = new JRegistry($module->params);
										$module->params->set('class_sfx', ($module->params->get('class_sfx') . ' vpf-mega-mod'));
										$module->params->set('moduleclass_sfx', ($module->params->get('moduleclass_sfx') . ' vpf-mega-mod'));
										$content->html = JModuleHelper::renderModule($module, array('style' => 'MegaHTML'));
										
										if($cols == 1)
										{
											$content->subwidth = 12;
										}
										else
										{
											$content->subwidth = isset($colw[$pos]) ? $colw[$pos] : 12;
										}
										
										$item->contents[] = $content;
										$pos++;
									}
								}
							}
						}
					}
					
					$item->anchor_css   = htmlspecialchars($item->params->get('menu-anchor_css', ''), ENT_COMPAT, 'UTF-8', false);
					$item->anchor_title = htmlspecialchars($item->params->get('menu-anchor_title', ''), ENT_COMPAT, 'UTF-8', false);
					$item->menu_image   = $item->params->get('menu_image', '') ?
						htmlspecialchars($item->params->get('menu_image', ''), ENT_COMPAT, 'UTF-8', false) : '';
				}

				if (isset($menus[$lastitem]))
				{
					$menus[$lastitem]->deeper     = (($start?$start:1) > $menus[$lastitem]->level);
					$menus[$lastitem]->shallower  = (($start?$start:1) < $menus[$lastitem]->level);
					$menus[$lastitem]->level_diff = ($menus[$lastitem]->level - ($start?$start:1));
				}
			}

			$cache->store($menus, $key);
		}
		else
		{
			$menus = $items;
		}

		return $menus;
	}

	public static function getOffCanvasMenu(&$params)
	{
		$app = JFactory::getApplication();
		$menu = $app->getMenu();

		// Get active menu item
		$base = self::getBase($params, 'offcanvas_');
		$user = JFactory::getUser();
		$levels = $user->getAuthorisedViewLevels();
		asort($levels);
		$key = 'offcanvas_menu_items' . $params->toString() . implode(',', $levels) . '.' . $base->id;
		$cache = JFactory::getCache('vp_framework', '');

		if (!($items = $cache->get($key)))
		{
			$path    = $base->tree;
			$start   = (int) $params->get('offcanvas_startLevel');
			$end     = (int) $params->get('offcanvas_endLevel');
			$showAll = $params->get('offcanvas_showAllChildren');
			$items   = $menu->getItems('menutype', $params->get('offcanvas_menutype'));

			$lastitem = 0;

			if($params->get('offcanvas_merge_vm_category_menu', 0) == 'start')
			{
				$categories = VPFrameworkVM::getCategories($params, 'offcanvas_');
				
				if(!empty($categories))
				{
					$items = array_merge($categories, $items);
				}
			}
			elseif($params->get('offcanvas_merge_vm_category_menu', 0) == 'end')
			{
				$categories = VPFrameworkVM::getCategories($params, 'offcanvas_');
				
				if(!empty($categories))
				{
					$items = array_merge($items, $categories);
				}
			}

			if ($items)
			{
				foreach ($items as $i => $item)
				{
					if (($start && $start > $item->level)
						|| ($end && $item->level > $end)
						|| (!$showAll && $item->level > 1 && !in_array($item->parent_id, $path))
						|| ($start > 1 && !in_array($item->tree[$start - 2], $path)))
					{
						unset($items[$i]);
						continue;
					}
					
					if($item->type == 'separator' && $item->params->get('mega_subcontent', ''))
					{
						// Do not show separator type parent item for mega menu in off canvas menu
						unset($items[$i]);
						continue;
					}

					$item->deeper     = false;
					$item->shallower  = false;
					$item->level_diff = 0;

					if (isset($items[$lastitem]))
					{
						$items[$lastitem]->deeper     = ($item->level > $items[$lastitem]->level);
						$items[$lastitem]->shallower  = ($item->level < $items[$lastitem]->level);
						$items[$lastitem]->level_diff = ($items[$lastitem]->level - $item->level);
					}

					$item->parent = (boolean) $menu->getItems('parent_id', (int) $item->id, true);

					$lastitem     = $i;
					$item->active = isset($item->active) ? $item->active : false;
					$item->flink  = $item->link;

					// Reverted back for CMS version 2.5.6
					switch ($item->type)
					{
						case 'separator':
						case 'heading':
							// No further action needed.
							break;

						case 'url':
							if ((strpos($item->link, 'index.php?') === 0) && (strpos($item->link, 'Itemid=') === false))
							{
								// If this is an internal Joomla link, ensure the Itemid is set.
								$item->flink = $item->link . '&Itemid=' . $item->id;
							}
							break;

						case 'alias':
							// If this is an alias use the item id stored in the parameters to make the link.
							$item->flink = 'index.php?Itemid=' . $item->params->get('aliasoptions');
							break;

						default:
							$router = $app::getRouter();

							if ($router->getMode() == JROUTER_MODE_SEF)
							{
								$item->flink = 'index.php?Itemid=' . $item->id;

								if (isset($item->query['format']) && $app->get('sef_suffix'))
								{
									$item->flink .= '&format=' . $item->query['format'];
								}
							}
							else
							{
								$item->flink .= '&Itemid=' . $item->id;
							}
							break;
					}

					if (strcasecmp(substr($item->flink, 0, 4), 'http') && (strpos($item->flink, 'index.php?') !== false))
					{
						$item->flink = JRoute::_($item->flink, true, $item->params->get('secure'));
					}
					else
					{
						$item->flink = JRoute::_($item->flink);
					}

					// We prevent the double encoding because for some reason the $item is shared for menu modules and we get double encoding
					// when the cause of that is found the argument should be removed
					$item->title        = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8', false);
					$item->anchor_css   = htmlspecialchars($item->params->get('menu-anchor_css', ''), ENT_COMPAT, 'UTF-8', false);
					$item->anchor_title = htmlspecialchars($item->params->get('menu-anchor_title', ''), ENT_COMPAT, 'UTF-8', false);
					$item->icon_class		= $item->params->get('offcanvas_icon_class', '') ?
						htmlspecialchars(trim($item->params->get('offcanvas_icon_class', '')), ENT_COMPAT, 'UTF-8', false) : '';
					$item->menu_image   = $item->params->get('offcanvas_menu_image', '') ?
						htmlspecialchars($item->params->get('offcanvas_menu_image', ''), ENT_COMPAT, 'UTF-8', false) : '';
				}

				if (isset($items[$lastitem]))
				{
					$items[$lastitem]->deeper     = (($start?$start:1) > $items[$lastitem]->level);
					$items[$lastitem]->shallower  = (($start?$start:1) < $items[$lastitem]->level);
					$items[$lastitem]->level_diff = ($items[$lastitem]->level - ($start?$start:1));
				}
			}

			$cache->store($items, $key);
		}

		return $items;
	}	
	/**
	 * Get base menu item.
	 *
	 * @param   JRegistry  &$params  The module options.
	 *
	 * @return   object
	 *
	 * @since	3.0.2
	 */
	public static function getBase(&$params, $prefix = '')
	{
		// Get base menu item from parameters
		if ($params->get($prefix . 'base'))
		{
			$base = JFactory::getApplication()->getMenu()->getItem($params->get($prefix . 'base'));
		}
		else
		{
			$base = false;
		}

		// Use active menu item if no base found
		if (!$base)
		{
			$base = self::getActive($params);
		}

		return $base;
	}

	/**
	 * Get active menu item.
	 *
	 * @param   JRegistry  &$params  The module options.
	 *
	 * @return  object
	 *
	 * @since	3.0.2
	 */
	public static function getActive(&$params)
	{
		$menu = JFactory::getApplication()->getMenu();

		return $menu->getActive() ? $menu->getActive() : $menu->getDefault();
	}
}
