<?php


//Déclaration d'un item de menu dans le menu principal
function factory_menu(&$menuItems){
	global $_,$myUser;
	if(!$myUser->can('factory','read')) return;
	$menuItems[] = array(
		'sort'=>100,
		'url'=>'index.php?module=factory',
		'label'=>'Factory',
		'icon'=> 'fas fa-cube',
		'color'=> '#ef1e4e'
	);
}



//Cette fonction va generer une page quand on clique sur Modele dans menu
function factory_page(){
	global $_,$myUser;
	if(!isset($_['module']) || $_['module'] !='factory') return;
	$page = !isset($_['page']) ? 'factory' : $_['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 factory_install($id){
	if($id != 'fr.idleman.factory') return;
	Entity::install(__DIR__);

}

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


//cette fonction comprends toutes les actions du plugin qui ne nécessitent pas de vue html
function factory_action(){
	require_once(__DIR__.SLASH.'action.php');
}

function factory_sanitize($text, $tableName=false,$allowChars='_'){
	$returned = '';
	foreach (explode(' ',trim($text)) as $word) {
		$returned .= $tableName ? mb_strtolower($word).'_' : ucfirst(mb_strtolower($word));
	}
	if($tableName) $returned = rtrim($returned, '_');

	$unwanted = array( 'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
		'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
		'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
		'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
		'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );

	$returned = strtr($returned, $unwanted);
	return preg_replace('|[^a-z0-9'.preg_quote($allowChars).']|i','',$returned);
}

function factory_render($sql,$data=array()){


	//filters
	$sql = preg_replace_callback('/{{~(!)?([^}]*)}}(.*?){{\/~}}/is',function($matches) use ($data) {
		$key = trim($matches[2]);
		$sql = $matches[3];
		$not = $matches[1];
		if($not=='!'){
			return isset($data['filters']) && in_array($key, $data['filters']) ?'':$sql;
		}else{
			return !isset($data['filters']) || !in_array($key, $data['filters']) ?'':$sql;
		}
		
	},$sql);

	//loop
	$sql = preg_replace_callback('/{{\:([^\/\:\?}]*)}}(.*?){{\/\:[^\/\:\?}]*}}/s',function($matches) use ($data) {

		$key = $matches[1];
		$sqlTpl = $matches[2];
	 //print_r('LOOP ON '.$key.PHP_EOL);
		$sql = '';
		if(isset($data[$key])){

			$i = 0;
			$values = $data[$key];

			foreach($values as $key=>$value){
				$i++;
				$last = $i == count($values);
				
				$occurence = str_replace(array('{{key}}'),array($key),$sqlTpl); 
				if(is_array($value)){
					foreach ($value as $key2 => $value2) 
						$occurence = str_replace(array('{{value.'.$key2.'}}'),array($value2),$occurence); 
				}else{
					$occurence = str_replace(array('{{value}}'),array($value),$occurence); 
				}

				$occurence = preg_replace_callback('/{{\;}}(.*?){{\/\;}}/',function($matches) use ($last){
					return $last? '': $matches[1];
				},$occurence);
				$sql.= $occurence;

			}
			return $sql;
		}
		return '';
	},$sql); 



	//conditions
	$sql = preg_replace_callback('/{{\?([^\/\:\?}]*)}}(.*?){{\/\?[^\/\:\?}]*}}/s',function($matches) use ($data) {
		$key = $matches[1];
		$sql = $matches[2];
		return !isset($data[$key]) || (is_array($data[$key]) && count($data[$key])==0) ?'':$sql;
	},$sql);


	//simple vars
	$sql = preg_replace_callback('/{{([^\/\:\;\?}]*)}}/',function($matches) use ($data) {
		$key = $matches[1];
		return isset($data[$key])?$data[$key]:$matches[0];
	},$sql); 

	return $sql;
}

//Déclaration des sections de droits du plugin
function factory_section(&$sections){
	$sections['factory'] = "Gestion des droits sur le plugin Factory";
}

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

//Mapping hook / fonctions
Plugin::addHook("install", "factory_install");
Plugin::addHook("uninstall", "factory_uninstall");
Plugin::addHook("section", "factory_section");
Plugin::addHook("menu_main", "factory_menu"); 
Plugin::addHook("page", "factory_page");  
Plugin::addHook("action", "factory_action");   


?>