<?php
//Permet le log/surcouhe d'une redirection de navigation
Action::register('navigation_redirect',function(&$response){
	global $_;
	$url = base64_decode($_['url']);
	Log::put("Ouverture de l'url: ".$url,'Navigation');

	Plugin::callHook('navigation_redirect',array($url));
	header('location: '.$url);
});

//Récuperation d'une liste de menuitem
Action::register('navigation_tree_search',function(&$response){
	global $myUser,$_,$myFirm;
	if (!$myUser->connected()) return;
	require_once(__DIR__.SLASH.'MenuItem.class.php');

	if(!isset($_['menu']) || !is_numeric($_['menu'])) throw new Exception("Menu non spécifié");
	if(!$menu = MenuItem::getById($_['menu'])) throw new Exception("Aucun menu ne correspond en base");

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

	//affichage des menu de la firm ou des menu inter firm (0)
	if(isset($_['firm'])){
		if(!$myUser->superadmin && !$myUser->haveFirm($_['firm'])) throw new Exception('Vous ne pouvez pas modifier le menu d\'un établissement auquel vous n\'avez pas accès');
		$filters['firm'] = $_['firm'];
	}else{
		$filters['firm:IN'] = array($myFirm->id,0);
	}
	//Récupération 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(!empty($item->target)?$item->target:'redirect');
		$row['shortcut'] = ($menu->slug == MenuItem::MENU_SHORTCUT && !empty($menu->user)) ? true : false;
		$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){
			return $a['sort'] - $b['sort'];
		});
	}

	//Le array_values permet la réinitialisation des clés qui impactent sur l'ordre final
	$response['rows'] = array_values($response['rows']);
});

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

	if($conf->get("navigation_allow_custom_menu")==0 && !$myUser->can('navigation','configure')) throw new Exception("Permissions insuffisantes", 403);
	if(!isset($_['menu']) || !is_numeric($_['menu'])) throw new Exception("Menu non spécifié");

	if(isset($_['fields'])){
		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'],'firm'=>$_['firm']);
	if(!$myUser->can('navigation','configure')) $filters['user'] = $myUser->login;
	if(!$myUser->superadmin) $filters['editable'] = '1';

	if(!$myUser->superadmin && $_['firm']==0) throw new Exception('Seul un superadmin peut définir un menu pour tous les établissements');
	if(!$myUser->superadmin && !$myUser->haveFirm($_['firm'])) throw new Exception('Vous ne pouvez pas modifier le menu d\'un établissement auquel vous n\'avez pas accès');

	$menuItems = array();
	$parameters = array('menu'=>$_['menu'],'firm'=>$_['firm']);
	if(!empty($_['items'])){
		foreach($_['items'] as $i => $item){
			$menuItem = !empty($item['id']) ? MenuItem::getById($item['id']) : new MenuItem();
			$menuItem->menu = $_['menu'];
			$menuItem->firm = $_['firm'];
			$menuItem->icon = $item['icon'];
			$menuItem->label = $item['label'];
			if(isset($item['url'])) $menuItem->url = str_replace(ROOT_URL.'/','',$item['url']);
			$menuItem->target = isset($item['target']) && !empty($item['target']) ? $item['target'] : 'redirect';
			if(isset($item['visibility'])) $menuItem->visibility = $item['visibility'];
			$menuItem->user = $myUser->can('navigation','configure') ? '' : $myUser->login;
			$menuItem->sort = $i;
			$menuItem->parent = NULL;

			$menuItem->slug = slugify($menuItem->label);
			if(MenuItem::rowCount(array('slug'=>$menuItem->slug)) < 0)
				$item->slug .='_'.time();

			$menuItem->save();
			$menuItems[] = $menuItem->id;

			if(!empty($item['childs'])){
				foreach($item['childs'] as $j => $subItem){
					$menuSubItem = !empty($subItem['id']) ? MenuItem::getById($subItem['id']) : new MenuItem();
					$menuSubItem->menu = $_['menu'];
					$menuSubItem->firm = $_['firm'];
					$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 = $j;
					$menuSubItem->parent = $menuItem->id;

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

					$menuSubItem->save();
					$menuItems[] = $menuSubItem->id;
				}
			} else {
				MenuItem::change(array('parent'=>NULL), array('parent'=>$item['id']));
			}
		}
		if(!empty($menuItems)) $parameters['id:NOT IN'] = implode(',', $menuItems);
	}
	MenuItem::delete($parameters);
});

Action::register('navigation_widget_load',function(&$response){
	global $myUser;
	User::check_access('navigation','read');
	Plugin::need('dashboard/DashboardWidget');
	$widget = DashboardWidget::current();

	if(empty($widget->data('title'))){
		$widget->title =  'Bloc Menu';
	}else{
		$widget->title =  '';
		$widget->icon = '';
	}

	if(!empty($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);
	exit;
});

Action::register('navigation_widget_configure_save',function(&$response){
	global $myUser,$_;
	User::check_access('navigation','read');
	Plugin::need('dashboard/DashboardWidget');
	$widget = DashboardWidget::getById($_['id']);

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

Action::register('navigation_widget_configure',function(&$response){
	global $myUser;
	User::check_access('navigation','read');
	Plugin::need('dashboard/DashboardWidget');
	$widget = DashboardWidget::current();

	ob_start();
	require_once(__DIR__.SLASH.'widget.configure.php');
	$content = ob_get_clean();

	echo $content;
	exit;
});

Action::register('navigation_widget_configure_autocomplete',function(&$response){
	global $myUser,$_;
	User::check_access('navigation','read');
	require_once(__DIR__.SLASH.'MenuItem.class.php');
	if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
	if(empty($_['keyword'])) return;

	$rows = array();
	foreach(MenuItem::staticQuery('SELECT item.* FROM {{table}} item LEFT JOIN {{table}} menu ON item.menu=menu.id  WHERE item.label LIKE ? AND item.menu!=? AND menu.user=?',array('%'.$_['keyword'].'%',0,$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;
});
