<?php
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
require_once (JPATH_ADMINISTRATOR . '/templates/'. _ADMIN_TPL . '/helper.php');
JLoader::register('JAModMenuHelper', JPATH_ADMINISTRATOR . '/templates/'. _ADMIN_TPL . '/html/mod_menu/helper.php');
// Get all User Groups
JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_users/models', 'UsersModel');
$model = JModelLegacy::getInstance('Groups', 'UsersModel', array('ignore_request' => true));
$groups = $model->getItems();
if (count($groups)) {
	foreach ($groups as $key => $group) {
		if(!JAccess::checkGroup($group->id, 'core.login.admin') && $group->id != '8') {
			unset($groups[$key]);
		}
	}
}

$app = JFactory::getApplication();
$input = $app->input;
$action = $input->getCmd('action');
$path = JPATH_ROOT . '/media/'._ADMIN_TPL.'/';
$qlPath = JPATH_ADMINISTRATOR . '/templates/' . _ADMIN_TPL . '/admin/assets/links/quicklinks.json';

// Load language
$lang = JFactory::getLanguage();
$lang->load('tpl_'._ADMIN_TPL, JPATH_ADMINISTRATOR, $lang->getTag(), true);

$helper = new BKTMPHelper();

$lang = JFactory::getLanguage();
$base_dir = JPATH_ADMINISTRATOR;
$language_tag = 'en-GB';
$reload = true;
//Load templates language
$lang->load('TPL_ADMIN', $base_dir, $language_tag, $reload);

switch ($action) {
	case 'addlink':
		$params = $_POST;
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		$params['timeStamp'] = $timestamp;
		$customPath = $path . 'links/customlinks.json';
		
		$quicklinks = array();
		$customLinks = array();
		$link = array();
		foreach ($params as $key => $value) {
				$link[$key] = $value;
		}
		
		//Get access group
		$url = (isset($link['link'])) ? $link['link'] : $link['url'];
		$link['acl'] = array();
		if (preg_match('/(option=)(com_[a-z0-9]+)/', $url)) {
			preg_match_all('/(option=)(com_[a-z0-9]+)/', $url, $matches);
			$asset = $matches[2][0];
			switch ($asset) {
				case 'com_cpanel' :
					break;
				case 'com_config' :
				case 'com_admin' :
					foreach ($groups as $gr) {
						if (JAccess::checkGroup((int) $gr->id, 'core.admin', $asset) || $gr->id == '8') {
							$link['acl'][] = $gr->id;
						}
					}
					break;
				default :
					if ($asset == 'com_categories') {
						if (preg_match('/(&extension=)(.+)/', $url)) {
							preg_match_all('/(&extension=)(.+)/', $url, $matches);
							$asset = $matches[2][0];
						}
					}
					foreach ($groups as $gr) {
						if (JAccess::checkGroup((int) $gr->id, 'core.manage', $asset) || $gr->id == '8') {
							if (preg_match('/(edit)(&.+)?/', $url)) {
								if (JAccess::checkGroup((int) $gr->id, 'core.edit', $asset) || $gr->id == '8') {
									$link['acl'][] = $gr['id'];
								}
							} else if (preg_match('/(\.add)$/', $url) || preg_match('/(\.add&)(.+)?/', $url)) {
								if (JAccess::checkGroup((int) $gr->id, 'core.create', $asset) || $gr->id == '8') {
									$link['acl'][] = $gr->id;
								}
							} else if (preg_match('/(\.delete&?)/', $url)) {
								if (JAccess::checkGroup((int) $gr->id, 'core.delete', $asset) || $gr->id == '8') {
									$link['acl'][] = $gr->id;
								}
							}
						}
					}
					break;
			}
		} else {
			$link['acl'] = array();
			foreach ($groups as $gr) {
				$link['acl'][] = $gr->id;
			}
		}
		if (count($link['acl']) > 1) {
			array_unshift($link['acl'], 'all');
		}
		
		if (JFile::exists($qlPath)) {
			$quicklinks = json_decode(file_get_contents($qlPath), true);
			$quicklinks['customlinks'][] = $link;
		}
		if (JFile::exists($customPath)) {
			$customlinks = json_decode(file_get_contents($customPath), true);
			$customLinks[] = $link;
		} else {
			JFile::makeSafe($customPath);
			$customLinks[] = $link;
		}
		$buffer1 = json_encode($quicklinks);
		$buffer2 = json_encode($customLinks);
		if (JFile::write($customPath, $buffer2) && JFile::write($qlPath, $buffer1)) {
			echo JLayoutHelper::render('this_template.dashboard.customlink', array('link' => $link, 'userGroups' => $groups));
		}
		break;
	case 'editlink':
		$params = $_POST;
		$params['access_group'] = array();
		if (is_array($params['acl']) && count($params['acl'])) {
			if (in_array('all', $params['acl'])) {
				$item = array();
				$item['id'] = 'all';
				$item['name'] = 'all';
				$params['access_group'][] = $item;
			} else {
				foreach ($params['acl'] as $acl) {
					foreach ($groups as $gr) {
						if ($acl == $gr->id) {
							$item = array();
							$item['id'] = $acl;
							$item['name'] = $gr->title;
							$params['access_group'][] = $item;
						}
					}
				}
			}
		}
		
		$links = json_decode(file_get_contents($qlPath), true);
		
		// Get custom links which optimized by user to system links
		$components = $helper->getComponents();
		$cusLinks = $helper->getComponentLinks($components, $links);
		$links['systemlinks'] = array_merge($links['systemlinks'], $cusLinks);
		$links = array_merge($links['systemlinks'], $links['customlinks']);
		
		// Get configs
		$configsFile = $path. '/configs.json';
		if (JFile::exists($configsFile)) {
			$configs = json_decode(@file_get_contents($configsFile), true);
		}
		
		$fileToSave = $path . 'links/customlinks.json';
		$qlToSave = array();
		$arr = array(); 
		if (!JFile::exists($fileToSave)) {
			JFile::makeSafe($fileToSave);
		} else {
			$qlToSave = json_decode(file_get_contents($fileToSave), true);
			foreach ($qlToSave as $ql) {
				$arr[] = $ql['timeStamp'];
			}
		}
		if (count($arr) > 0 ) {
			if (in_array($params['timeStamp'], $arr)) {
				foreach ($qlToSave as $k => $ql) {
					if ($ql['timeStamp'] == $params['timeStamp']) {
						$qlToSave[$k]['title'] = $params['title'];
						if (isset($ql['link'])) {
							$qlToSave[$k]['link'] = $params['url'];
						} else {
							$qlToSave[$k]['url'] = $params['url'];
						}
						$qlToSave[$k]['icon'] = $params['icon'];
						$qlToSave[$k]['image'] = $params['image'];
					}
				}
			} else {
				foreach ($links as $link) {
					if ($link['timeStamp'] == $params['timeStamp']) {
						$item = array();
						$item['timeStamp'] = $params['timeStamp'];
						$item['title'] = $params['title'];
						if (isset($link['link'])) {
							$item['link'] = $link['link'];
						} else {
							$item['url'] = $params['url'];
						}
						$item['icon'] = $params['icon'];
						$item['image'] = $params['image'];
						$qlToSave[] = $item;
					}
				}
			}
		} else {
			foreach ($links as $link) {
				if ($link['timeStamp'] == $params['timeStamp']) {
					$item = array();
					$item['timeStamp'] = $params['timeStamp'];
					$item['title'] = $params['title'];
					if (isset($link['link'])) {
						$item['link'] = $link['link'];
					} else {
						$item['url'] = $params['url'];
					}
					$item['icon'] = $params['icon'];
					$item['image'] = $params['image'];
					$qlToSave[] = $item;
				}
			}
		}
		$buffer = json_encode($qlToSave);

		if (JFile::write($fileToSave, $buffer)) {
			echo json_encode($params);
		}
		break;
	case 'deletequicklink':
		$timeStamp = $_POST['linkid'];
		$links = json_decode(file_get_contents($qlPath), true);
		if (count($links['customlinks'])) {
			foreach ($links['customlinks'] as $key => $customLink) {
				if ($customLink['timeStamp'] == $timeStamp) {
					unset($links['customlinks'][$key]);
					$buffer = json_encode($links);
					if (JFile::write($qlPath, $buffer)) {
						echo $timeStamp;
					}
					break;
				}
			}
		}
		break;
	case 'addgroup':
		$file = $path . '/configs.json';
		$configs = array();
		if (!JFile::exists($file)){
			JFile::makeSafe($file);
		} else {
			$configs = json_decode(@file_get_contents($file), true);
		}
		if (!isset($configs['quicklinks'])){
			$configs['quicklinks'] = array();
		}
		
		$groupName = $_POST['groupname'];
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		
		$configs['quicklinks'][$groupName] = array();
		$configs['quicklinks'][$groupName]['id'] = $timestamp;
		$configs['quicklinks'][$groupName]['items'] = array();
		
		echo JLayoutHelper::render('this_template.dashboard.newgroup', array('groupId'=> $timestamp, 'groupname' => $groupName));
		break;
	case 'editgroup' :
		$newGroupName = $_POST['name'];
		$groupId = $_POST['id'];
		
		$file = $path . '/configs.json';
		if (JFile::exists($file)) {
			$configs = json_decode(@file_get_contents($file), true);
		}
		
		if ($configs['quicklinks']) {
			foreach ($configs['quicklinks'] as $group => $grlinks) {
				if ($groupId == $grlinks['id']) {
					$configs['quicklinks'][$newGroupName] = array();
					$configs['quicklinks'][$newGroupName] = $grlinks;
					unset($configs['quicklinks'][$group]);
					break;
				}
			}
		}
		$buffer = json_encode($configs);
		if (JFile::write($file, $buffer)) {
			echo 'success';
		} else {
			echo 'fail';
		}
		break;
	case 'deletegroup' :
		$groupId = $_POST['groupId'];
		$file = $path . '/configs.json';
		if (JFile::exists($file)) {
			$configs = json_decode(@file_get_contents($file), true);
		}
		if ($configs['quicklinks'] && count($configs['quicklinks'])) {
			foreach ($configs['quicklinks'] as $group => $grlinks) {
				if ($groupId == $grlinks['id']) {
					unset($configs['quicklinks'][$group]);
				}
			}
			$buffer = json_encode($configs);
			if (JFile::write($file, $buffer)) {
				echo 'success';
			} else {
				echo 'fail';
			}
		} else {
			echo 'success';
		}
		break;
	case 'loadconfigs':
		$file = $path.'/configs.json';
		if (JFile::exists($file)){
			$configs = @file_get_contents($file);
		}
		if (isset($configs)) {
			echo $configs;
		} else {
			echo '';
		}
		break;
	case 'loadmenuitems':
		echo JLayoutHelper::render('this_template.dashboard.menuitems', array());
		break;
	case 'addmenuitem' :
		$params = $_POST['params'];
		$params['type'] = 'custom';
		
		$date = new DateTime();
		$timestamp = $date->getTimestamp();
		
		$menufile = JPATH_ADMINISTRATOR . '/templates/'._ADMIN_TPL.'/admin/assets/links/menus.json';
		$custom_menu_file = JPATH_ROOT . '/media/' . _ADMIN_TPL. '/links/custommenus.json';
		
		$customMenus = array();
		
		if (JFile::exists($menufile)) {
			$menus = json_decode(@file_get_contents($menufile), true);
		}
		
		if (count($menus)) {
			// Get MenuTypes
			require JPATH_ADMINISTRATOR .'/modules/mod_menu/helper.php';
			$menuTypes = JAModMenuHelper::getMenus();
			if (count($menuTypes)) {
				foreach ($menuTypes as $menuType) {
					$item = array();
					$item['timestamp'] = 'mnt-'.$menuType->id;
					$item['title'] = $menuType->title;
					$item['url'] = 'index.php?option=com_menus&view=items&menutype=' . $menuType->menutype;
					$item['icon'] = '';
					$item['parent'] = 'menus';
					$item['level'] = 2;
					$menus['menus']['items'][] = $item;
					
					//Add new menu item
					$itemAdd = array();
					$itemAdd['timestamp'] = 'mnt-'.$menuType->id.'-add';
					$itemAdd['title'] = JText::_('MOD_MENU_MENU_MANAGER_NEW_MENU_ITEM');
					$itemAdd['url'] = 'index.php?option=com_menus&view=item&layout=edit&menutype=' . $menuType->menutype;
					$itemAdd['icon'] = '';
					$itemAdd['parent'] = 'mnt-'.$menuType->id;
					$itemAdd['level'] = $item['level'] + 1;
					$menus['menus']['items'][] = $itemAdd;
				}
			}

			// Get Component Menu Items
			$components = JAModMenuHelper::getComponents(true);
			if (count($components)) {
				$menus['components']['items'] = array();
				foreach ($components as $component) {
					$item = array();
					$item['timestamp'] = 'cpn-'.$component->id;
					$item['title'] = $component->title;
					$item['url'] = $component->link;
					$item['parent'] = 'components';
					$item['level'] = 2;
					$menus['components']['items'][] = $item;
					if (count($component->submenu) > 0) {
						foreach($component->submenu as $sub) {
							$item = array();
							$item['timestamp'] = 'cpn-'.$sub->id;
							$item['title'] = $sub->title;
							$item['url'] = $sub->link;
							$item['parent'] = 'cpn-'.$sub->parent_id;
							$item['level'] = 3;
							$menus['components']['items'][] = $item;
						}
					}
				}
			}
			
			if (!JFile::exists($custom_menu_file)) {
				JFile::makeSafe($custom_menu_file);
			} else {
				$customMenus = json_decode(@file_get_contents($custom_menu_file), true);
				if (count($customMenus)) {
					foreach ($customMenus as $ct) {
						$ct['timestamp'] = isset($ct['id']) ? $ct['id'] : $ct['timestamp'];
						if ($ct['parent'] == 'root') {
							$menu_name = preg_replace('/\s+/','', $ct['title']);
							$menus[$menu_name] = array();
							$menus[$menu_name]['id'] = $ct['timestamp'];
							$menus[$menu_name]['title'] = $ct['title'];
							$menus[$menu_name]['image'] = $ct['image'];
							$menus[$menu_name]['icon'] = $ct['icon'];
							$menus[$menu_name]['level'] = 1;
							$menus[$menu_name]['type'] = 'custom';
							$menus[$menu_name]['items'] = array();
						} else {
							foreach ($menus as $group => $menuitem) {
								if ($ct['parent'] == $group) {
									$menus[$group]['items'][] = $ct;
								} else {
									foreach ($menus[$group]['items'] as $item) {
										if ($ct['parent'] == $item['timestamp']) {
											$menus[$group]['items'][] = $ct;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		if ($params['parent'] == 'root') {
			$params['level'] = 1;
			$params['id'] = $timestamp;
			$customMenus[] = $params;
			$buffer = json_encode($customMenus);
			if (JFile::write($custom_menu_file, $buffer)) {
				echo JLayoutHelper::render('this_template.dashboard.newmenuitem', $params);
			}
		} else {
			if (count($menus)) {
				foreach ($menus as $group => $menu) {
					if ($group.'-'.$menu['id'] == $params['parent']) {
						$params['level'] = $menu['level'] + 1;
						$params['id'] = $timestamp;
						$params['parent'] = $group;
						$customMenus[] = $params;
						$buffer = json_encode($customMenus);
						if (JFile::write($custom_menu_file, $buffer)) {
              $parents = $group;
              $level = $params['level'];
              do {
                foreach($menu['items'] as $mn) {
                  if ($mn['timestamp'] == $params['parent']) {
                    $parents .= ' '.$mn['parent'];
                    $level = $mn['level'];
                  }
                }
              } while ($level > 2);
              $params['parents'] = $parents;
							echo JLayoutHelper::render('this_template.dashboard.newmenuitem', $params);
						}
					} else {
						if (count($menu['items'])) {
							foreach ($menu['items'] as $item) {
								if ($item['timestamp'] == $params['parent']) {
									$params['level'] = $item['level'] + 1;
									$params['timestamp'] = $timestamp;
									$customMenus[] = $params;
									$buffer = json_encode($customMenus);
									if (JFile::write($custom_menu_file, $buffer)) {
                    $parents = $params['parent'];
                    $level = $params['level'];
                    do {
                      foreach ($menu['items'] as $mn) {
                        if ($mn['timestamp'] == $params['parent']) {
                          $parents .= ' '.$mn['parent'];
                          $level--;
                        }
                      }
                    } while ($level > 2);
                    $params['parents'] = $parents;
										echo JLayoutHelper::render('this_template.dashboard.newmenuitem', $params);
									}
								}
							}
						}
					}
				}
			}
		}
		break;
	case 'editmenugroup' :
		$params = $_POST['data'];
		$custom_menu_file = JPATH_ROOT . '/media/' . _ADMIN_TPL. '/links/custommenus.json';
		$customMenus = array();
		if (JFile::exists($custom_menu_file)) {
			$customMenus = json_decode(@file_get_contents($custom_menu_file), true);
		}
		if (count($customMenus)) {
			foreach ($customMenus as $key => $menu) {
				if (isset($menu['id']) && $menu['id'] == $params['id']) {
					$customMenus[$key]['title'] = $params['menu-title'];
					$customMenus[$key]['icon'] = $params['menu-icon'];
					$customMenus[$key]['image'] = $params['menu-image'];
				}
			}
		}
		$buffer = json_encode($customMenus);
		if (JFile::write($custom_menu_file, $buffer)) {
			echo json_encode($params);
		}
		break;
	case 'editmenuitem' :
		$params = $_POST['data'];
		$custom_menu_file = JPATH_ROOT . '/media/' . _ADMIN_TPL. '/links/custommenus.json';
		$customMenus = array();
		if (JFile::exists($custom_menu_file)) {
			$customMenus = json_decode(@file_get_contents($custom_menu_file), true);
		}
		if (count($customMenus)) {
			foreach ($customMenus as $key => $menu) {
				if ((isset($menu['id']) && $menu['id'] == $params['id']) || (isset($menu['timestamp']) && $menu['timestamp'] == $params['id'])) {
					$customMenus[$key]['title'] = $params['menu-title'];
					$customMenus[$key]['url'] = $params['menu-url'];
					$customMenus[$key]['icon'] = $params['menu-icon'];
					$customMenus[$key]['image'] = $params['menu-image'];
				}
			}
		}
		$buffer = json_encode($customMenus);
		if (JFile::write($custom_menu_file, $buffer)) {
			echo json_encode($params);
		}
		break;
	case 'loadquicklinks' :
		$groupslinks = $_POST['groups'];
		echo JLayoutHelper::render('this_template.dashboard.quicklinks', array('groups' => $groupslinks));
		break;
	case 'saveconfigs':
		$params = $_POST;
		$file = JPATH_ROOT . '/media/' . _ADMIN_TPL . '/configs.json';
		
		if (!isset($params['quicklinks'])) {
			$params['quicklinks'] = array();
		}
		if (!isset($params['menus'])) {
			$params['menus'] = array();
		}
		$groupmenus = array();
		$items = array();
		if (count($params['menus'])) {
			foreach ($params['menus'] as $gr => $mn) {
				$groupmenus[] = $mn['id'];
				if (isset($mn['items']) && count($mn['items'])) {
					foreach ($mn['items'] as $it) {
						$items[] = $it['id'];
					}
				}
			}
		}
		
		/*
		* Get custom menu group and custom menu item
		* Only save the menu group and menu item if it in the configs
		*/
		$custom_menu_file = JPATH_ROOT . '/media/' . _ADMIN_TPL. '/links/custommenus.json';
		$customMenus = array();
		if (JFile::exists($custom_menu_file)) {
			$customMenus = json_decode(@file_get_contents($custom_menu_file), true);
			if (count($customMenus)) {
				foreach ($customMenus as $key => $custom_menu) {
					if ($custom_menu['level'] == 1) {
						if (!in_array($custom_menu['id'], $groupmenus)) {
							unset($customMenus[$key]);
						}
					} else {
						if ((isset($custom_menu['timestamp']) && !in_array($custom_menu['timestamp'], $items)) || (isset($custom_menu['id']) && !in_array($custom_menu['id'], $items))) {
							unset($customMenus[$key]);
						}
					}
				}
			}
			$buffer_custom_menu = json_encode($customMenus);
			JFile::write($custom_menu_file, $buffer_custom_menu);
		}
		
		// Save configs
		if (!JFile::exists($file)) {
			JFile::makeSafe($file);
		}
		foreach ($params['menus'] as $group => $menus) {
			if ($menus['acl'] == '') {
				$params[$group]['acl'] = array();
			}
			if (isset($menus['items']) && count($menus['items'])) {
				foreach ($menus['items'] as $k => $item) {
					if ($item['acl'] == '') {
						$params['menus'][$group]['items'][$k]['acl'] = array();
					}
				}
			}
		}
		
		
		$buffer = json_encode($params);
		if (JFile::write($file, $buffer)) {
			$html = '<span class="message-success" style="color: green;">'.JText::_('SAVE_PROFILE_SUCCESS').'</span>';
		} else {
			$html = '<span class="message-fail" style="red;">'.JText::_('SAVE_PROFILE_FAIL').'</span>';
		}
		echo $html;
		break;
	default:
		echo JLayoutHelper::render ('this_template.dashboard.manage', array());
		break;
}