<?php



//Déclaration d'un item de menu dans le menu principal
function employee_menu(&$menuItems){
	global $myUser;
	if(!$myUser->can('employee','read')) return;
	$menuItems[] = array(
		'sort'=>3,
		'url'=>'index.php?module=employee',
		'label'=>'Fiche employé',
		'icon'=> 'fas fa-user-tie',
		'color'=> '#1abc9c'
	);
}

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

	$dictionary = new Dictionary();
    	$dictionary->slug = 'employee_employee_job';
    	if(Dictionary::rowCount(array('slug'=>$dictionary->slug)) ==0){
	    	$dictionary->label = 'Fiche employé : Poste';
	    	$dictionary->parent = 0;
	    	$dictionary->state = Dictionary::ACTIVE;
	    	$dictionary->save();

	    	$item = new Dictionary();
			$item->slug = 'employee_employee_job_comercial';
			$item->label = 'Commercial';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_job_devloper';
			$item->label = 'Analyste Développeur';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_job_pdg';
			$item->label = 'Président Directeur général';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_job_dg';
			$item->label = 'Directeur général';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_job_hotline';
			$item->label = 'Technicien Support';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_job_technician';
			$item->label = 'Technicien réseau système';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_job_daf';
			$item->label = 'Directeur administratif et financier';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();


	    }
   		$dictionary = new Dictionary();
    	$dictionary->slug = 'employee_employee_statute';
    	if(Dictionary::rowCount(array('slug'=>$dictionary->slug)) ==0){
	    	$dictionary->label = 'Fiche employé : Statut';
	    	$dictionary->parent = 0;
	    	$dictionary->state = Dictionary::ACTIVE;
	    	$dictionary->save();

	    	$item = new Dictionary();
			$item->slug = 'employee_employee_statute_employee';
			$item->label = 'Salarié non cadre';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_statute_cadre';
			$item->label = 'Salarié Cadre';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();
	    }
		$dictionary = new Dictionary();
    	$dictionary->slug = 'employee_employee_contractType';
    	if(Dictionary::rowCount(array('slug'=>$dictionary->slug)) ==0){
	    	$dictionary->label = 'Fiche employé : Type de contrat';
	    	$dictionary->parent = 0;
	    	$dictionary->state = Dictionary::ACTIVE;
	    	$dictionary->save();

	    	$item = new Dictionary();
			$item->slug = 'employee_employee_contractType_cdd';
			$item->label = 'CDD';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_contractType_cdi';
			$item->label = 'CDI';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_contractType_apprentissage';
			$item->label = 'Contrat d\'apprentissage (alternance)';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_contractType_professionalisation';
			$item->label = 'Contrat de professionnalisation (alternance)';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();


	    }

    $dictionary = new Dictionary();
    	$dictionary->slug = 'employee_employee_hardware';
    	if(Dictionary::rowCount(array('slug'=>$dictionary->slug)) ==0){
	    	$dictionary->label = 'Fiche employé : Mise a disposition de matériel';
	    	$dictionary->parent = 0;
	    	$dictionary->state = Dictionary::ACTIVE;
	    	$dictionary->save();

	    	$item = new Dictionary();
			$item->slug = 'employee_employee_hardware_pc';
			$item->label = 'Ordinateur portable';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_hardware_phone';
			$item->label = 'Téléphone portable';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_hardware_car';
			$item->label = 'Voiture de fonction';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();

			$item = new Dictionary();
			$item->slug = 'employee_employee_hardware_car_service';
			$item->label = 'Voiture de service';
			$item->parent = $dictionary->id;
			$item->state = Dictionary::ACTIVE;
			$item->save();
	    }

}

//Fonction executée lors de la désactivation du plugin
function employee_uninstall($id){
	if($id != 'fr.core.employee') return;
	Entity::uninstall(__DIR__);
	$dictionary = Dictionary::bySlug('employee_employee_job');
    	if($dictionary!= false && $dictionary->id!=0){
    		Dictionary::delete(array('parent'=>$dictionary->id));
    		Dictionary::delete(array('id'=>$dictionary->id));
    	}
    $dictionary = Dictionary::bySlug('employee_employee_statute');
    	if($dictionary!= false && $dictionary->id!=0){
    		Dictionary::delete(array('parent'=>$dictionary->id));
    		Dictionary::delete(array('id'=>$dictionary->id));
    	}
    $dictionary = Dictionary::bySlug('employee_employee_contractType');
    	if($dictionary!= false && $dictionary->id!=0){
    		Dictionary::delete(array('parent'=>$dictionary->id));
    		Dictionary::delete(array('id'=>$dictionary->id));
    	}

    $dictionary = Dictionary::bySlug('employee_employee_hardware');
    	if($dictionary!= false && $dictionary->id!=0){
    		Dictionary::delete(array('parent'=>$dictionary->id));
    		Dictionary::delete(array('id'=>$dictionary->id));
    	}

}


	Right::register("employee",array('label'=>"Gestion des droits sur le plugin Fiche employé"));


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

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

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


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('employee',array(
    "Général",
    'employee_default_worktime' => array("label"=>"Heures hebdomadaires de travail par défaut","placeholder"=>"ex: 39","type"=>"number"),
    'employee_save_recipients' => array("label"=>"Destinataires des notifications de creation de fiche","placeholder"=>"", "type"=>"user", "attributes"=>
    	array(
    		"data-multiple"=>true,
    		"data-types"=>"user,rank"
    	)
    )
));


Right::register('employee',array('label'=>'Permissions sur les employés'));


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


	ExportModel::add('employee','employee-sheet', 'Fiche employé', function($parameters){
		global $myUser;

		require_once(__DIR__.SLASH.'Employee.class.php');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		require_once(__DIR__.SLASH.'EmployeeContract.class.php');

		$employee = new Employee();
		$contract = new EmployeeContract();
		$workTime = new EmployeeWorkTime();

		if(!empty($parameters['id'])){
			$employee =  Employee::getById($parameters['id']);
			$contracts = EmployeeContract::staticQuery('SELECT main.*,'.EmployeeWorkTime::joinString('wt').' FROM {{table}} main LEFT JOIN '.EmployeeWorkTime::tableName().' wt ON main.worktime = wt.id WHERE (main.`end` IS NULL OR main.`end` = "" OR  main.`end` > ?) AND main.employee=? LIMIT 1',array(time(),$employee->id),true,1);


			if(isset($contracts[0])) $contract= $contracts[0];
			$workTime = $contract->join('worktime');
		}


		$job = Dictionary::getById($employee->job);
		$statute = Dictionary::getById($contract->statute);
		$contractType = Dictionary::getById($contract->type);


		$job = !$job ? new Dictionary() : $job ;
		$statute = !$statute ? new Dictionary() : $statute ;
		$contractType = !$contractType ? new Dictionary() : $contractType ;
		$workTime = !$workTime ? new EmployeeWorkTime() : $workTime ;

		$hardwareTypes = Dictionary::slugToArray('employee_employee_hardware',true);

		$hardwares = array();
		$employee->hardware = json_decode($employee->hardware,true);
		if(is_array($employee->hardware)){
			foreach ($employee->hardware as $value) {
				$hardwares[] = $hardwareTypes[$value]->label;
			}
		}

		$manager = $employee->manager !=0 ? Employee::getById($employee->manager) : new Employee();


		$employee->jobDescription = strip_tags(str_replace(array('<br>','<br/>','<p>'),PHP_EOL,html_entity_decode($employee->jobDescription)));
		$employee->comment = strip_tags(str_replace(array('<br>','<br/>','<p>'),PHP_EOL,html_entity_decode($employee->comment)));


		$data['employe'] = array('label'=>'Employé', 'type'=>'object','value' => array());
		$data['employe']['value']['nom'] = array('label' => 'Nom de l\'employé','value' => $employee->name);
		$data['employe']['value']['nom-naissance'] = array('label' => 'Nom de naissance de l\'employé','value' => $employee->birthName);

		$data['employe']['value']['prenom'] = array('label' => 'Prénom l\'employé','value' =>$employee->firstname);
		$data['employe']['value']['poste'] = array('label' => 'Poste de l\'employé','value' =>$job->label);
		$data['employe']['value']['role'] = array('label' => 'Rôle/Missions','value' => WordExport::convert_text_format(html_entity_decode($employee->jobDescription)) );
		$data['employe']['value']['status'] = array('label' => 'Status','value' =>$statute->label);
		$data['employe']['value']['manager'] = array('label' => 'Responsable','value' =>$manager->fullName());
		$data['employe']['value']['lieu-travail'] = array('label' => 'Lieu de travail','value' =>$employee->workplace);
		$data['employe']['value']['debut-contrat'] = array('label' => 'Date de début de contrat','value' =>date('d/m/Y',$contract->start));
		$data['employe']['value']['type-contrat'] = array('label' => 'Type de contrat','value' =>$contractType->label);
		$data['employe']['value']['motif-cdd'] = array('label' => 'Motif contrat','value' =>$contract->comment);
		$data['employe']['value']['fin-contrat'] = array('label' => 'Date de fin CDD','value' =>date('d/m/Y',$contract->end));
		$data['employe']['value']['temps-travail'] = array('label' => 'Temps de travail','value' =>$workTime->label);
		$data['employe']['value']['heures-semaine'] = array('label' => 'Heures par semaines','value' =>$workTime->hourByWeek);
		$data['employe']['value']['jours-an'] = array('label' => 'Jours par an','value' =>$workTime->dayByYear);
		$data['employe']['value']['materiel'] = array('label' => 'Matériel alloué','value' =>  WordExport::convert_text_format(implode(', ',$hardwares)) );
		$data['employe']['value']['date'] = array('label' => 'Date','value' => date('d/m/Y',$contract->start));

		$path = $employee->picture();
		$stream = file_exists($path) ? file_get_contents($path) : '';

		$data['employe']['value']['photo'] = array(
				'label'=>'Photo de l\'employé',
				'type'=>'image',
				'value' => $stream
		);

		return $data;
	});


}

function employee_notification_type(&$types){
	global $conf;
	$types['employee'] = array(
		'category' =>'RH',
		'label' =>'Fiche employé',
		'color' =>'#dc3545',
		'icon'  =>'fas fa-user-tie',
		'description' => "Notification lorsqu'une fiche emoployé est créée",
		'default_methods' => array(
			'interface' => !empty($conf->get('employee_interface')) ? $conf->get('employee_interface') : true,
			'mail' => !empty($conf->get('employee_mail')) ? $conf->get('employee_mail') : true
		)
	);
}

//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", "employee_install");
Plugin::addHook("uninstall", "employee_uninstall");

Plugin::addHook("menu_main", "employee_menu");
Plugin::addHook("page", "employee_page");
Plugin::addHook("menu_setting", "employee_menu_setting");
Plugin::addHook("content_setting", "employee_content_setting");
Plugin::addHook("notification_type", "employee_notification_type");
?>