<?php
require_once(__DIR__.SLASH.'action.php');

//Déclaration d'un item de menu dans le menu principal
function navigation_menu(){
	require_once(__DIR__.SLASH.'MenuItem.class.php');
	global $myUser,$conf,$myFirm,$menu;


	$menu = MenuItem::bySlug(array('footer-menu','main-menu'),'',array($myFirm->id,0));

?>
	<ul class="navbar-nav navigation-menu">
		<?php foreach($menu['main-menu'] as $item):
			navigation_item_template($item);
		endforeach; ?>
	</ul>

	<?php if($conf->get("navigation_allow_custom_menu")==0) return; ?>
	<ul class="navbar-nav navigation-shortcut-menu">
	<?php if ($myUser->connected()):
		foreach(MenuItem::bySlug('shortcut-menu',$myUser->login,array($myFirm->id,0)) as $item):
			navigation_item_template($item);
		endforeach;
	endif; ?>
	</ul>
	<?php
}

function navigation_menu_footer(&$items){
	global $menu;
	require_once(__DIR__.SLASH.'MenuItem.class.php');
	$items = $menu['footer-menu'];
	//$items = array_merge($items,MenuItem::bySlug('footer-menu'));
}

function navigation_item_template($item){
	global $myUser,$conf;
	require_once(__DIR__.SLASH.'MenuItem.class.php');
	$page = basename($_SERVER['REQUEST_URI']);

	$id = !empty($item['id']) ? $item['id'] : '';
	$target = !empty($item['target']) ? $item['target'] : '';
	$url = !empty($item['url']) ? $item['url'] : '';
	$label = !empty($item['label']) ? $item['label'] : '';
	$html = !empty($item['html']) ? $item['html'] : '';

	if(!empty($item['label']) && $item['label'] == 'Réglages') $page = basename($_SERVER['PHP_SELF']);
	$classes = !empty($item['classes']) ? $item['classes'] : '';

	$linkClasses = array('nav-link');
	if(!empty($item['childs'])){

		if(count($item['childs'])!=0){
			$classes .= ' dropdown';
			$url = '';
			$linkClasses[] = ' dropdown-toggle';
		}
		$mustShow = false;
		foreach($item['childs'] as $child) {
			//Vérification des droits de visibilité sur le menu
			$childObject = new MenuItem();
			$childObject->fromArray($child);
			if($childObject->visibleFor($myUser)){
				$mustShow = true;
				break;
			}
		}
		if(!$mustShow && empty($item['url'])) return;
	}
	if(!empty($item['parent'])){
		//On supprime la 1ère classe "nav-link" car c'est un sous-item
		unset($linkClasses[0]);
		$linkClasses[] = ' dropdown-item';
	}

	$url = navigation_meta_link($url);
	$label = navigation_meta_link($label);
	$html = navigation_meta_link($html);
	$icon = !empty($item['icon']) ? '<i class="'.$item['icon'].'"></i> ' : '';

	if($target=='iframe'){
		$target = '';
		$url = 'index.php?module=navigation&page=iframe&url='.base64_encode($url);
	}
	if($target=='redirect') $target = '';

	//Highlight du menu sélectionné

	if((!empty($url) && ((preg_match('|'.preg_quote($url).'[&\?]|i',$page,$match) && $url != 'index.php') || $page == $url)))
		$classes .= ' active';

	//Vérification des droits de visibilité sur le menu
	$itemObject = new MenuItem();
	$itemObject->fromArray($item);
	if(!$itemObject->visibleFor($myUser)) return;

	//Si les logs sont activés, on désactive le direct link pour passer par la surcouche de logs
	if($conf->get('navigation_enable_log')) if(!empty($url)) $url = 'action.php?action=navigation_redirect&url='.base64_encode($url);
	?>

	<li data-id="<?php echo $id; ?>" class="nav-item <?php echo $classes; ?>">
		<a class="<?php echo implode(' ', $linkClasses); ?>"
			<?php echo isset($item['childs']) && count($item['childs'])!=0? 'data-toggle="dropdown"':''; ?>
			title="<?php echo isset($item['title'])?$item['title']:''; ?>"
			target="<?php echo $target; ?>"
			onclick="<?php echo isset($item['onclick'])?$item['onclick']:''; ?>"
			href="<?php echo $url; ?>">
			<?php echo $icon; ?><?php echo $label; ?>
			<?php echo $html; ?>
		</a>
		<?php if(isset($item['childs'])): ?>
		<ul class="dropdown-menu py-1" aria-labelledby="navbarDropdown">
		 	<?php foreach($item['childs'] as $child)
		 		navigation_item_template($child);
		 	?>
	    </ul>
	    <?php endif; ?>
	</li>

	<?php
}

//Application des données de templates sur l'url, libellé...
function navigation_meta_link($string){
	global $myUser;
	$data = array('user'=>$myUser->toArray());
	$data['user']['meta'] = $myUser->meta;
	unset($data['password']);
	return template($string,$data);
}

//Cette fonction va generer une page quand on clique sur navigation dans menu
function navigation_page(){
	global $_;
	if(!isset($_['module']) || $_['module'] !='navigation') return;
	$page = !isset($_['page']) ? 'list' : $_['page'];
	$file = __DIR__.SLASH.'page.'.$page.'.php';
	if(!file_exists($file)) throw new Exception("Page ".$page." inexistante");

	require_once($file);
}

//Fonction executée lors de l'activation du plugin
function navigation_install($id){
	if($id != 'fr.core.navigation') return;
	Entity::install(__DIR__);
	require_once(__DIR__.SLASH.'MenuItem.class.php');

	$mainMenu = new MenuItem();
	$mainMenu->label = 'Menu principal';
	$mainMenu->slug = 'main-menu';
	$mainMenu->user = '';
	$mainMenu->menu = 0;
	$mainMenu->editable = 0;
	$mainMenu->save();


	$pages = array();
	Plugin::callHook("menu_main", array(&$pages));
	uasort ($pages , function($a,$b){return $a['sort']>$b['sort']?1:-1;});

	foreach($pages as $i=>$page):
		$icon = isset($page['icon'])? $page['icon'] : 'far fa-bookmark';

		$menuItem = new MenuItem();
		$menuItem->label = $page['label'];
		$menuItem->icon = $icon;
		$menuItem->url = $page['url'];
		$menuItem->user = '';
		$menuItem->menu = 0;
		$menuItem->sort = $i;
		$menuItem->slug = $mainMenu->slug.'_'.slugify($menuItem->label);
		$menuItem->menu = $mainMenu->id;
		$menuItem->save();
	endforeach;

	$mainMenu = new MenuItem();
	$mainMenu->label = 'Menu pied de page';
	$mainMenu->slug = 'footer-menu';
	$mainMenu->user = '';
	$mainMenu->menu = 0;
	$mainMenu->editable = 0;
	$mainMenu->save();
}

//Fonction executée lors de la désactivation du plugin
function navigation_uninstall($id){
	if($id != 'fr.core.navigation') return;
	Entity::uninstall(__DIR__);
}

//Déclaration des sections de droits du plugin
//Déclaration des sections de droits du plugin
Right::register('navigation',array('label'=>'Gestion des droits sur le plugin navigation'));


//Déclaration du menu de réglages
function navigation_menu_setting(&$settingMenu){
	global $myUser;

	if(!$myUser->can('navigation','configure')) return;
	$settingMenu[]= array(
		'sort' =>1,
		'url' => 'setting.php?section=global.navigation',
		'icon' => 'fas fa-angle-right',
		'label' => 'Menu & Navigation'
	);
}

//Déclaration des pages de réglages
function navigation_content_setting(){
	global $_;
	if(file_exists(__DIR__.SLASH.'setting.'.$_['section'].'.php'))
		require_once(__DIR__.SLASH.'setting.'.$_['section'].'.php');
}

//Déclaration des settings de base
//Types possibles : text,select ( + "values"=> array('1'=>'Val 1'),password,checkbox. Un simple string définit une catégorie.
Configuration::setting('navigation',array(
    "Général",
    'navigation_allow_custom_menu' => array("label"=>"Autoriser la création de menu personnalisés","legend"=>"Autorise aux utilisateurs la création de raccourcis dans la barre principale","type"=>"boolean"),
    'navigation_enable_log' => array("label"=>"Activer les logs au clic sur un menu","legend"=>"Cette option peut considérablement augmenter la taille de la base de données","type"=>"boolean"),
    'default_menu_visibility' => array(
    	"label"=>"Visibilité par défaut des nouveaux menus",
    	"legend"=>"Laisser vide pour ne rien appliquer par défaut aux nouveaux menus",
    	"type"=>"user",
    	"placeholder"=>"eg. Administrateur",
    	"attributes"=>array(
    		"data-multiple"=>true,
    		"data-types"=>"user,rank"
    	)
    ),
));

//Déclation des assets
Plugin::addCss("/css/main.css");
Plugin::addJs("/js/main.js");

Plugin::addHook("menu_user", function(&$userMenu){
	global $conf, $myUser;
	if($conf->get("navigation_allow_custom_menu")==0 && !$myUser->superadmin) return;
	$userMenu[]= array(
		'sort' => 0.5,
		'label' => 'Mes raccourcis',
		'icon' => 'far fa-star',
		'url' => 'setting.php?section=global.navigation&menu=mine'
	);
});



function navigation_widget(&$widgets){
	global $myUser;
	require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');

	$modelWidget = new DashboardWidget();
	$modelWidget->model = 'menu';
	$modelWidget->title = 'Menu';
	$modelWidget->icon = 'far fa-compass';
	$modelWidget->background = '#130f40';
	$modelWidget->load = 'action.php?action=navigation_widget_load';
	$modelWidget->js = [Plugin::url().'/js/widget.js?v=0'];
	$modelWidget->css = [Plugin::url().'/css/widget.css?v=0'];
	$modelWidget->configure = 'action.php?action=navigation_widget_configure';
	$modelWidget->configure_callback = 'navigation_widget_configure_save';
	$modelWidget->configure_init = 'navigation_widget_configure_init';
	$modelWidget->description = "Affiche un menu sélectionné";
	$widgets[] = $modelWidget;
}


//Mapping hook / fonctions
Plugin::addHook("widget", "navigation_widget");
Plugin::addHook("install", "navigation_install");
Plugin::addHook("uninstall", "navigation_uninstall");


Plugin::addHook("header", "navigation_menu");
Plugin::addHook("page", "navigation_page");
Plugin::addHook("menu_setting", "navigation_menu_setting");
Plugin::addHook("content_setting", "navigation_content_setting");
Plugin::addHook("content_setting", "navigation_content_setting");

Plugin::addHook("menu_footer", "navigation_menu_footer");

?>