<?php
global $_,$conf;
switch($_['action']){
	
	//permet le log/surcouhe d'une redirection de navigation
	case 'navigation_redirect':
		$url = base64_decode($_['url']);
		Log::put("Ouverture de l'url: ".$url,'navigation');
		Plugin::callHook('navigation_redirect',array($url));
		header('location: '.$url);
	break;


	//Récuperation d'une liste de menuitem
	case 'navigation_tree_search':
		Action::write(function(&$response){
			global $myUser,$_;
			if (!$myUser->connected()) return;
			require_once(__DIR__.SLASH.'MenuItem.class.php');
			
			if(!isset($_['menu']) || !is_numeric($_['menu'])) throw new Exception("Menu non spécifié");

			$response['rows'] = array();
			$filters = array('menu'=>$_['menu']);
			if(!$myUser->can('navigation','configure')) $filters['user'] = $myUser->login;
			$items = array();

			//recup des catégories principales
			foreach(MenuItem::loadAll($filters,array('sort')) as $item){
				$row = $item->toArray();
				$row['class'] = $item->parent!=''  ? 'navigation-line-child' : '';
				if(!$row['editable']) $row['class'] .= ' not-editable';
				$row['target'] = MenuItem::target($item->target); 
				$items[$row['id']] = $row;
				if(empty($row['parent']))
					$response['rows'][$row['id']] = $row;
			}

			//Classement pas catégories
			foreach ($items as $k=>$item) {
				if(empty($item['parent'])) continue;
				if(!isset($response['rows'][$item['parent']]['childs'])) $response['rows'][$item['parent']]['childs'] = array();
				$response['rows'][$item['parent']]['childs'][] = $item;
			}

			//Tri des sous catégories par ordre de sort
			foreach ($response['rows'] as $key=>$parent) {
				if(!isset($response['rows'][$key]['childs'])) continue;
				usort($response['rows'][$key]['childs'],function($a,$b){
					if($a['sort'] > $b['sort']) return 1;
					if($a['sort'] < $b['sort']) return -1;
					if($a['sort'] == $b['sort']) return 0;
				});
			}
			//le array value permet la réinitialisation des clés qui impactent sur l'ordre final
			$response['rows'] = array_values($response['rows']);
			

			
		});
	break;

	//Sauvegarde des configurations de navigation
	case 'navigation_setting_save':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			require_once(__DIR__.SLASH.'MenuItem.class.php');

			if($conf->get("navigation_allow_custom_menu")==0 && !$myUser->can('navigation','configure')) throw new Exception("Error Processing Request", 403);

			
			if(!isset($_['menu']) || !is_numeric($_['menu'])) throw new Exception("Menu non spécifié");
			
			foreach(Configuration::setting('navigation') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}
			foreach ($_['fields'] as $key => $value)
				if(in_array($key, $allowed)) $conf->put($key,$value);
			

			$filters = array('menu'=>$_['menu']);


			if(!$myUser->can('navigation','configure')) $filters['user']=$myUser->login;
			

			if(!$myUser->superadmin) $filters['editable'] = '1';
			MenuItem::delete($filters);

			if(isset($_['items'])){
				foreach ($_['items'] as $i => $item){
					$menuItem = new MenuItem();

					$menuItem->menu = $_['menu'];
					$menuItem->icon = $item['icon'];
					$menuItem->label = $item['label'];
					if(isset($item['url'])) $menuItem->url = str_replace(ROOT_URL.'/','',$item['url']);
					if(isset($item['target'])) $menuItem->target = $item['target'];
					if(isset($item['visibility'])) $menuItem->visibility = $item['visibility'];
					$menuItem->user = $myUser->can('navigation','configure') ? '' : $myUser->login;
					$menuItem->slug = slugify($menuItem->label);
					$menuItem->sort = $i;
					if(MenuItem::rowCount(array('slug'=>$menuItem->slug)) <0 )
						$item->slug .='_'.time();

					$menuItem->save();

					if(isset($item['childs'])){
						foreach($item['childs'] as $u=>$subItem){

							$menuSubItem = new MenuItem();
							$menuSubItem->menu = $_['menu'];
							$menuSubItem->icon = $subItem['icon'];
							$menuSubItem->label = $subItem['label'];
							if(isset($subItem['url'])) $menuSubItem->url = str_replace(ROOT_URL.'/','',$subItem['url']);
							if(isset($subItem['target'])) $menuSubItem->target = $subItem['target'];
							if(isset($subItem['visibility'])) $menuSubItem->visibility = $subItem['visibility'];
							$menuSubItem->user = $myUser->can('navigation','configure') ? '' : $myUser->login;
							$menuSubItem->sort = $u;
							$menuSubItem->slug = $menuItem->slug.'_'.slugify($menuItem->label);

							if(MenuItem::rowCount(array('slug'=>$menuSubItem->slug)) <0 )
								$menuSubItem->slug .='_'.time();

							$menuSubItem->parent = $menuItem->id;
							$menuSubItem->save();
						}
					}
				}
			}
				

		});
			
	break;
	case 'navigation_widget_load':
		global $myUser;
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		if( $widget->data('title') == ""){
			$widget->title =  'Bloc Menu';
		}else{
			$widget->title =  '';
			$widget->icon = '';
		}
		
		if($widget->data('color') != "") $widget->background = $widget->data('color');
		ob_start();
		require_once(__DIR__.SLASH.'widget.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
	break;

	case 'navigation_widget_configure_save':
		Action::write(function(&$response){
		global $myUser,$_;
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::getById($_['id']);

		$url =  str_replace(ROOT_URL.'/','',$_['widget-url']);
		$widget->data('icon',$_['widget-icon']);
		$widget->data('title',$_['widget-title']);
		$widget->data('color',$_['widget-color']);
		$widget->data('url',$url);
		$widget->save();
	});
	break;

	case 'navigation_widget_configure':
		global $myUser;
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.configure.php');
		$content = ob_get_clean();
		echo $content ;
	break;

	case 'navigation_widget_configure_autocomplete':
		Action::write(function(&$response){
		global $myUser,$_;
		require_once(__DIR__.SLASH.'MenuItem.class.php');
		if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
		$rows = array();
		if($_['keyword'] == '') return;

		
		foreach(MenuItem::staticQuery('SELECT item.* FROM {{table}} item LEFT JOIN {{table}} menu ON item.menu=menu.id  WHERE item.label LIKE ? AND item.menu!=0 AND menu.user=?',array('%'.$_['keyword'].'%',$myUser->login),true) as $menu){
			$row = $menu->toArray();
			$row['name'] = $row['label'];
			$rows[] = $row;
		}

		Plugin::callHook("menu_main", array(&$pages));
		
		
		foreach($pages as $page){
			
			if( strpos(slugify($page['label']), slugify($_["keyword"])) === false ) continue;
			$icon = isset($page['icon'])? $page['icon'] : 'far fa-bookmark';
			$row =  $page;
			$row['name'] = $page['label'];
			$rows[] = $row;
		}

		usort ($rows , function($a,$b){return $a['sort']>$b['sort']?-1:1;});

		$response['rows'] = $rows;
	});
	break;
}
?>