<?php



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

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

	$dictionary = new Dictionary();
    	$dictionary->slug = 'example_contact_vehicle';
    	if(Dictionary::rowCount(array('slug'=>$dictionary->slug)) ==0){
	    	$dictionary->label = 'ContactExample : Véhicule';
	    	$dictionary->parent = 0;
	    	$dictionary->state = Dictionary::ACTIVE;
	    	$dictionary->save();

	    	foreach(array(
	    		'renaud'=>'Renaud',
	    		'dacia'=>'Dacia',
	    		'tesla'=>'Tesla'

	    	) as $key=>$value){
		    	$item = new Dictionary();
				$item->slug = 'example_contact_vehicle_'.$key;
				$item->label = $value;
				$item->parent = $dictionary->id;
				$item->state = Dictionary::ACTIVE;
				$item->save();
			}
	    }

	$subitem = new Dictionary();
    $subitem->slug = 'example_contact_vehicle_dacia_logan';
    $subitem->label = 'Logan';
    $subitem->parent = $item->id;
    $subitem->state = Dictionary::ACTIVE;
    $subitem->save();

    $dictionary = new Dictionary();
	$dictionary->slug = 'example_contact_handicap';
	if(Dictionary::rowCount(array('slug'=>$dictionary->slug)) ==0){
    	$dictionary->label = 'Example : Handicaps';
    	$dictionary->parent = 0;
    	$dictionary->state = Dictionary::ACTIVE;
    	$dictionary->save();

    	foreach(array(
    		'none'=>'Aucun(e)',
    		'death'=>'Sourd(e)',
    		'blind'=>'Aveugle',
    	) as $key=>$value){
	    	$item = new Dictionary();
			$item->slug = 'example_contact_handicap_'.$key;
			$item->label = $value;
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();
		}
    }

}

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

	Dictionary::remove('example_contact_vehicle');
	Dictionary::remove('example_contact_handicap');

}

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

//Droits ciblés sur les widgets
Right::register('example_contact',array(
		'label'=>'Gestion des droits sur le plugin exemple ciblé sur les contacts',
		'global'=> false,
		'check' => function($action,$right){
			global $myUser;
			if($right->uid <= 0) throw new Exception('Id widget non spécifié');
			require_once(__DIR__.SLASH.'ContactExample.class.php');
			$contact = ContactExample::getById($right->uid);
			if($myUser->login != $contact->creator) throw new Exception('Seul le créateur de ce contact ('.$contact->creator.') peut définir des droits pour celui-çi');
		}
));


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

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

function example_menu_account(&$accountMenu){
	global $_, $myUser;
	if(!$myUser->can('example', 'read')) return;
	$accountMenu[]= array(
		'sort' =>0,
		'url' => 'account.php?section=example',
		'icon' => 'fas fa-angle-right',
		'label' => 'Example',
	);
	$accountMenu[]= array(
		'sort' =>0,
		'url' => 'account.php?section=example.contact',
		'icon' => 'fas fa-angle-right',
		'label' => 'Example ContactExample',
	);
}

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


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






//Affichage du/des widget(s)
function example_widget(&$widgets){

	require_once(PLUGIN_PATH.'dashboard'.SLASH.'DashboardWidget.class.php');
	$modelWidget = new DashboardWidget();
	$modelWidget->model = 'example';
	$modelWidget->title = 'Example';
	$modelWidget->icon = 'fas fa-question';
	$modelWidget->background = '#273c75';
	$modelWidget->load = 'action.php?action=example_widget_load';
	$modelWidget->js = [Plugin::url().'/js/widget.js'];
	$modelWidget->css = [Plugin::url().'/css/widget.css'];
	$modelWidget->description = "Contient les différents outils créés et la structure de fichier attendue dans les plugins.";
	$widgets[] = $modelWidget;
}

function example_document_setting(){
	$documents = array();
	foreach(glob(__ROOT__.FILE_PATH.'contact'.SLASH.'documents'.SLASH.'settings'.SLASH.'*.*') as $file){
		if(get_OS() === 'WIN') $file = utf8_encode($file);
		$documents[] = array(
			'path' => 'contact'.SLASH.'documents'.SLASH.'settings'.SLASH.basename($file),
			'url' => 'action.php?action=contact_download_document&path=settings'.SLASH.rawurlencode(basename($file)),
			'name' => basename($file),
			'icon' => getExtIcon(getExt($file))
		);
	}
	return $documents;
}


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

Configuration::setting('example',array(
    "Général",
    'example_dropzone' => array("label"=>"Dropzone de fichiers","type"=>"dropzone","legend"=>"la légende","attributes"=>array(
    	"data-allowed" => "docx,pdf,txt,jpg,bmp,gif,xlsx,png,iso",
    	"data-label" => "Faites glisser vos documents",
    	"data-delete" => "contact_delete_document",
    	"documents" => json_encode(example_document_setting())
    )),
    'example_dictionary' => array("label"=>"Liste de véhicules","type"=>"dictionary","legend"=>"la légende","attributes"=>array(
    	"data-slug" => "invoice-payment-mode"
    )),
));


$api = new Api("example", "Api de gestion des exemples");
$api->route('contact/search','retourne un contact et ses informations correspondantes','GET',function($request,&$response){
	global $myUser,$_;
	$_ = $request['parameters'];
	$_['export'] = false;
	if(!$myUser->connected()) throw new Exception("Credentials are missing",401);
	Action::run('example_contact_search',$response);

});
$api->register();


global $myFirm;
if($myFirm->has_plugin('fr.core.export')){
	require_once(__ROOT__.PLUGIN_PATH.'export'.SLASH.'ExportModel.class.php');

	ExportModel::add('example','contact-sheet', 'Fiche contact', function($parameters){
		global $myUser;

		require_once(__DIR__.SLASH.'ContactExample.class.php');

		$contact = new ContactExample();

		if(isset($parameters['description']) && $parameters['description']!=true && !empty($parameters['id']))
			$contact =  ContactExample::getById($parameters['id']);


		$data['contact'] = array('label'=>'ContactExample', 'type'=>'object','value' => array());
		$data['contact']['value']['libellé'] = array('label' => 'Libellé du contact','value' => $contact->label);
		$data['contact']['value']['téléphone'] = array('label' => 'N° de téléphone du contact','value' => $contact->phone);
		$data['contact']['value']['anniversaire'] = array('label' => 'Date de naissance/d\'anniversaire du contact','value' => date('d/m/Y',$contact->birth));
		$data['contact']['value']['identifiant'] = array('label' => 'Identifiant du contact','value'=>$contact->login);
		$data['contact']['value']['photo'] = array(
			'label'=>'Image de profil du contact',
			'type'=>'image',
			'value' => file_get_contents($contact->get_image('path'))
		);
		return $data;
	});

	ExportModel::add('example','contact-list','Liste de contacts',function($parameters){
		global $myUser;
		require_once(__DIR__.SLASH.'ContactExample.class.php');

		$contacts = array(new ContactExample());
		if(isset($parameters['description']) && $parameters['description']!=true) $contacts = ContactExample::loadAll();

		$data['contacts'] = array('label'=>'Boucle sur les contacts', 'type'=>'list','value' => array());
		$data['contacts']['nombre'] = array('label' => 'Nombre de contacts au total', 'value' => count($contacts));
		foreach($contacts as $contact){

		$data['contacts']['value'][] = array(
				'libellé' => array('label' => 'Libellé du contact' , 'value' => $contact->label ),
				'téléphone' => array('label' => 'N° de téléphone du contact' , 'value' => $contact->phone ),
				'anniversaire' => array('label' => 'Date de naissance/d\'anniversaire du contact' , 'value' => $contact->birth ),
				'identifiant' => array('label' => 'Identifiant du contact' , 'value' => $contact->login ),
				'photo' => array(
					'label' => 'Image de profil du contact',
					'type'=>'image' ,
					'value' => file_get_contents($contact->get_image('path'))
				),
			);
		}

		return $data;
	});
}

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

//Mapping hook / fonctions

Plugin::addHook("install", "example_install");
Plugin::addHook("uninstall", "example_uninstall");

Plugin::addHook("menu_main", "example_menu");
Plugin::addHook("page", "example_page");

Plugin::addHook("menu_account", "example_menu_account");
Plugin::addHook("content_account", "example_content_account");

Plugin::addHook("menu_setting", "example_menu_setting");
Plugin::addHook("content_setting", "example_content_setting");

Plugin::addHook("widget", "example_widget");


//Declaration des évenements et entités workflow
Plugin::addHook("workflow_event", function(&$events){
	Plugin::need('workflow/WorkflowEvent');
	//Evenement entité
	$events[] = WorkflowEvent::registerEntity(__DIR__.SLASH.'ContactExample.class.php');
	//Evenement liste d'entité
	$events[] = WorkflowEvent::registerList(__DIR__.SLASH.'ContactExample.class.php',array(
		'events' => array('example-contact-cron' => 'Toutes les minutes'),
	));
});

//Lancement de l'evenement liste entité toutes les minutes
Plugin::addHook("cron", function(){
	Plugin::need('example/ContactExample');
	Plugin::need('workflow/WorkflowEvent');
	WorkflowEvent::trigger('example-contact-cron',array());
});
?>