<?php



//Déclaration d'un item de menu dans le menu principal
function import_menu(&$menuItems){
	global $myUser;
	if(!$myUser->can('import','read')) return;
	$menuItems[] = array(
		'sort'=>3,
		'url'=>'index.php?module=import',
		'label'=>'Import',
		'icon'=> 'fas fa-file-import',
		'color'=> '#2ecc71'
	);
}

//Cette fonction va generer une page quand on clique sur Import dans menu
function import_page(){
	global $_;
	if(!isset($_['module']) || $_['module'] !='import') return;
	$page = !isset($_['page']) ? 'list.import' : $_['page'];
	$page = str_replace('..','',$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 import_install($id){
	if($id != 'fr.core.import') return;
	Entity::install(__DIR__);


}

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

}

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


//cette fonction comprends toutes les actions du plugin qui ne nécessitent pas de vue html
function import_action(){
	require_once(__DIR__.SLASH.'action.php');
}
//Déclaration du menu de réglages
function import_menu_setting(&$settingMenu){
	global $myUser;

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

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

//Récupere la lettre excel (ou le groupe de lettres) en fonction du numéro de colonne
function import_column_letter($columnNumber){
	$alphabet = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
	$multiplicator = floor($columnNumber / 26);
	$columnNumber = $columnNumber - ($multiplicator*26);
	$parentLetter = ($multiplicator!=0) ? import_column_letter($multiplicator-1) :'';
	return $parentLetter.$alphabet[$columnNumber];
}

function import_report_line(&$response,$context,$type,$typeLabel,$message){

	if(!isset($response['lines'][$context['lineNumber']])) $response['lines'][$context['lineNumber']] = array('state'=>ImportMapping::UNIQUE_SKIP,'columns'=>array());

	foreach($context['columns'] as $i=>$columnLetter){
		if(!isset($response['lines'][$context['lineNumber']])) $response['lines'][$context['lineNumber']] = array('columns'=>array());
		if(!isset($context['line'][$i])) $context['line'][$i] = array('value'=>'');
		$response['lines'][$context['lineNumber']]['columns'][$i] = array('value'=>$context['line'][$i]['value']);
	}

	$response['lines'][$context['lineNumber']]['columns'][$context['columnNumber']]['state'] = $type ;
	$response['lines'][$context['lineNumber']]['columns'][$context['columnNumber']]['stateLabel'] = $typeLabel ;
	$response['lines'][$context['lineNumber']]['columns'][$context['columnNumber']]['message'] = $message;



}

function import_import_macros(&$macros){
	$macros = array(
			'dictionary' => array(
				'slug'=>'dictionary',
				'label'=>'Convertir en liste configurable',
				'description'=>'Convertis les valeurs en dictionnaire (liste configurable)',
				'mutator'=> function($value,$context = array()){
					if(!isset($context['dictionnaries'])) $context['dictionnaries'] = array();
					$parentSlug = slugify($context['plugin']).'_'.slugify($context['entity']).'_'.$context['entityField']['column'];

					//récuperation du dico racine / construition si inexistant
					if(!isset($context['dictionnaries'][$parentSlug])){
						$parent = Dictionary::bySlug($parentSlug);
						if(!$parent){
							$parent = new Dictionary();
							$parent->slug = $parentSlug;
							$parent->label = $context['entityLabel'].' : '.$context['entityField']['label'];
							$parent->parent = 0;
							$parent->state = Dictionary::ACTIVE;
							$parent->save();
						}
						$context['dictionnaries'][$parentSlug] = array('id'=>$parent->id,'childs'=>array());
					}

					$valueSlug = $parentSlug.'_'.slugify($value);
					if(!isset($context['dictionnaries'][$parentSlug]['childs'][$valueSlug])){

						$item = Dictionary::bySlug($valueSlug);
						if(!$item){
							$item = new Dictionary();
							$item->slug = $valueSlug;
							$item->label = $value;
							$item->parent = $context['dictionnaries'][$parentSlug]['id'];
							$item->state = Dictionary::ACTIVE;
							$item->save();
						}

						$context['dictionnaries'][$parentSlug]['childs'][$valueSlug] = $item->id;
					}

					return $context['dictionnaries'][$parentSlug]['childs'][$valueSlug];
			}),
			'firm' => array(
				'slug'=>'firm',
				'label'=>'Convertir en établissement ERP',
				'description'=>'Convertis les textes en établissement ERP (si existants)',
				'mutator'=> function($value,&$context = array()){
					if(!isset($context['firms'])){
						$context['firms'] = array();
						foreach(Firm::loadAll() as $firm){
							$context['firms'][slugify($firm->label)] = $firm;
						}
					}
					//var_dump($value,slugify($value),$context['firms']);
					if(!isset($context['firms'][slugify($value)])) return '';
					return $context['firms'][slugify($value)]->id;
			}),
			'price' => array(
				'slug'=>'price',
				'label'=>'Convertir en prix € ERP',
				'description'=>'Convertis les textes en prix € ERP',
				'mutator'=> function($value,&$context = array()){
					$value = str_replace(',','.',$value);
					$value = preg_replace('/[^0-9\.]/i','',$value);
					return $value;
			}),
			'breakline' => array(
				'slug'=>'breakline',
				'label'=>'Convertir les sauts de lignes',
				'description'=>'Convertir les sauts de lignes HTML en saut de lignes classiques',
				'mutator'=> function($value,&$context = array()){
					$value = str_replace('<br>',"\n",$value);
					return $value;
			}),
			'boolean' => array(
				'slug'=>'boolean',
				'label'=>'Convertir en vrai/faux ERP',
				'description'=>'Convertis les oui/non O/N en vrai/faux ERP',
				'mutator'=> function($value,&$context = array()){

					$value = str_replace(array(' ',"\r","\n","\t"),'',mb_strtolower($value));

					switch($value){
						case 'o':
						case 'oui':
						case 'x':
						case 'yes':
						case 'ok':
						case 'vrai':
						case '1':
							$value = 1;
						break;
						case 'n':
						case 'non':
						case 'no':
						case 'ko':
						case 'faux':
						case '0':
							$value = 0;
						break;
						default:
							$value = '';
						break;
					}

					return $value;
			}),
			'date' => array(
				'slug' => 'date',
				'label'=>'Convertir en date ERP',
				'description'=>'Convertis la date excel en date ERP (timestamp)',
				'mutator'=> function($value,&$context = array()){
					$value = trim($value);
					if(empty($value)) return '';

					$date = explode('/',str_replace(array('-',' '), '/', $value));

					if(count($date)<3) return 0;


					if(strlen($date[2]) == 4){
						$year = $date[2];
						$month = $date[1];
						$day = $date[0];
					}else if(strlen($date[0]) == 4){
						$year = $date[0];
						$month = $date[1];
						$day = $date[2];
					}else{
						return 0;
					}

					if(!is_numeric($month)){
						$numericMonth = false;
						$longNames = array('janvier','fevrier','mars','avril','mai','juin','juillet','aout','septembre','octobre','novembre','decembre');
						$shortNames = array('jan','fev','mar','avr','mai','juin','juil','aout','sept','oct','nov','dec');
						if(isset( $longNames[slugify($month)] ))$numericMonth = $longNames[slugify($month)];
						if(isset( $shortNames[slugify($month)] ))$numericMonth = $shortNames[slugify($month)];
						$month = $numericMonth;
						if(!$month) return 0;
					}

					$m = 0;
					$h = 0;
					if(isset($date[3])){
						list($h,$m) = explode(':',$date[3]);
					}

					if(!is_numeric($day) || !is_numeric($month) || !is_numeric($year)) return 0;

					return mktime($h,$m,0,$month,$day,$year);
				}
			),
			'empty-breakline' => array(
				'slug'=>'empty-breakline',
				'label'=>'Supprimer les sauts de lignes',
				'description'=>'Supprimer les sauts de lignes (texte et html)',
				'mutator'=> function($value,&$context = array()){
					$value = str_replace(array('<br>',"\n","\r"),"",$value);
					return $value;
			})
		);
}

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


//Déclaration des settings de base
//Types possibles : voir FieldType.class.php. Un simple string définit une catégorie.
Configuration::setting('import',array(
    "Général",
    //'import_enable' => array("label"=>"Activer","type"=>"boolean"),
));


/*

*/

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

Plugin::addCss("/css/component.css");
Plugin::addJs("/js/component.js");

//Mapping hook / fonctions
Plugin::addHook("install", "import_install");
Plugin::addHook("uninstall", "import_uninstall");
Plugin::addHook("menu_main", "import_menu");
Plugin::addHook("page", "import_page");
Plugin::addHook("menu_setting", "import_menu_setting");
Plugin::addHook("content_setting", "import_content_setting");
Plugin::addHook("import_macros","import_import_macros");
?>