<?php
/**
 * Define a menuitem.
 * @author Valentin CARRUESCO
 * @category Plugin
 * @license copyright
 */
class MenuItem extends Entity{
	public $id,$icon,$label,$url,$classes,$sort,$parent,$user,$target,$editable,$slug,$childs,$visibility,$menu;
	public $TABLE_NAME = 'menuitem';
	public $fields =
	array(
		'id' => 'key',
		'icon' => 'string',
		'label' => 'string',
		'slug' => 'string',
		'url' => 'longstring',
		'visibility' => 'longstring',
		'classes' => 'string',
		'sort' => 'int',
		'user' => 'string',
		'target' => 'string',
		'editable' => 'int',
		'parent' => 'int',
		'menu' => 'int'
	);

	public $indexes = array('slug','menu');

	function __construct(){
		parent::__construct();
		$this->editable = true;
		$this->menu = 0;
		$this->user = '';
	}

	public static function target($slug=null){
		$targets = array(
			'redirect' => array('label'=>'Redirection','slug'=>'redirect','icon'=>'fas fa-link'),
			'_blank' => array('label'=>'Redirection  (nouvel onglet)','slug'=>'_blank','icon'=>'fas fa-link'),
			'iframe' => array('label'=>'IFrame','slug'=>'iframe','icon'=>'fas fa-crop'),
		);

		$undefined = array('label'=>'Non définis','slug'=>'','icon'=>'');

		if(!isset($slug)) return $targets;

		return isset($targets[$slug]) ? $targets[$slug] : $undefined;
	}

	public function visibleFor($user){
		if(!isset($this->visibility) || $this->visibility=='' || $user->superadmin) return true;
		$visibility =  explode(',', $this->visibility);
		
		foreach($visibility as $entity){
			if(is_numeric($entity)){
				if($user->hasRank($entity)) return true;
			}else{
				if($user->login==$entity) return true;
			}
		}
		return false;
		
	}

	public static function bySlug($menuSlug,$user=''){
		$menuItems = array();

		$mainMenu = array();
		foreach(self::staticQuery('SELECT it.* FROM {{table}} it LEFT JOIN {{table}} me ON it.menu=me.id WHERE me.slug=? and me.user=? ORDER BY sort',array($menuSlug,$user),true) as $dbItem){
			$mainMenu[] = $dbItem->toArray(); 
		}

		uasort ($mainMenu , function($a,$b){return $a['sort']>$b['sort']?1:-1;});
		foreach ($mainMenu as $i=>$item) {
			if(isset($item['parent'])) continue;
			$menuItems[$item['id']] = $item;
			$menuItems[$item['id']]['childs'] = array();
			unset($mainMenu[$i]);
		}

		foreach ($mainMenu as $item) {
			$menuItems[$item['parent']]['childs'][] = $item;
		}

		
		return $menuItems;
	}


}
?>