<?php
	/** EMPLOYEE / FICHE EMPLOYé **/
	//Récuperation d'une liste de fiche employé
	Action::register('employee_search',function(&$response){
		global $_,$myUser;
		User::check_access('employee','read');
		require_once(__DIR__.SLASH.'Employee.class.php');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		require_once(__DIR__.SLASH.'EmployeeContract.class.php');



		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT main.*, '.Employee::joinString('man').'
		FROM '.Employee::tableName().' main
		LEFT JOIN '.Employee::tableName().' man ON man.id = main.manager  WHERE 1';

		$data = array();
		//Recherche simple
		if(!empty($_['filters']['keyword'])){
			$query .= ' AND (main.name LIKE ? OR main.birthname LIKE ?  OR main.firstname LIKE ?)';
			$data[] = '%'.$_['filters']['keyword'].'%';
			$data[] = '%'.$_['filters']['keyword'].'%';
			$data[] = '%'.$_['filters']['keyword'].'%';
		}

		$query .= ' AND main.state = ?';
		$data[] = Employee::ACTIVE;

		//Droits de visibilité sur la fiche :
		// - L'admin configure dans tous les cas
		// - Le créateur de la fiche si pas de manager renseigné
		// - Le manager si renseigné
		if(!$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			$hierarchy = array();
			foreach(Employee::subordinates($myEmployee) as $subordinate){
				$hierarchy[] = $subordinate->id;
				$data[] = $subordinate->id;
			}
			$hierarchy[] = $myEmployee->id;
			$data[] = $myEmployee->id;

			if(empty($hierarchy)) $hierarchy[] = 0;
			$query .= ' AND (main.manager IN ('.implode(',',array_fill(0,count($hierarchy),'?')).') OR (main.manager IN (NULL,"") AND main.creator=?))';

			$data[] = $myUser->login;
		}


		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.photo','main.birthName','main.name','main.firstname','main.job','main.jobDescription','man.account','main.workplace','main.hardware','main.date'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.birthName','main.name','main.firstname','main.job','main.jobDescription','main.manager','main.workplace','main.hardware','main.date'),$query,$data);

		//Pagination
		$itemPerPage = 20;
		if($_['export'] == 'true') $itemPerPage = 5000;
		$response['pagination'] = Employee::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		$employees = Employee::staticQuery($query,$data,true,1);

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

		$jobs = Dictionary::slugToArray('employee_employee_job',true);

		$response['rows'] = array();


		foreach($employees as $employee){
			$row = $employee->toArray();

			$row['photo'] = $employee->photo();
			$row['jobDescription'] = html_entity_decode($row['jobDescription']);
			$row['comment'] = html_entity_decode($row['comment']);

			$row['hardware'] = array();
			$employeeHardwares = json_decode($employee->hardware,true);
			if(is_array($employeeHardwares)){
				foreach($employeeHardwares as $id){
					if(isset($hardwares[$id])) $row['hardware'][] =  $hardwares[$id]->label;
				}
			}
			$row['hardware'] = implode(', ',$row['hardware']);

			if(!empty($row['manager'])){
				$manager = $employee->join('manager');
				$row['manager'] = $manager->toArray();
				$row['manager']['photo'] = $manager->photo();
			}


			$user = User::byLogin($row['account']);
			$row['account'] = $user->toArray();
			$row['account']['fullname'] = $user->fullname();
			$row['account']['avatar'] = $user->getAvatar();

			$row['job']= !empty($row['job']) && isset($jobs[$row['job']]) ? $jobs[$row['job']] : new Dictionary();

			if($_['export'] == 'true'){
				$row['created'] = date('d-m-Y',$row['created']);
				$row['updated'] = date('d-m-Y',$row['updated']);

				$row['jobDescription'] = strip_tags(str_replace(array('<br>','<br/>','<p>'),PHP_EOL,$row['jobDescription']));
				$row['comment'] = strip_tags(str_replace(array('<br>','<br/>','<p>'),PHP_EOL,$row['comment']));
				$row['job'] = $row['job']->label;

			}


			if($row['birthName'] == $row['name']) unset($row['birthName']);

			$response['rows'][] = $row;
		}

		if($_['export'] == 'true'){
			if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
			$fieldsMapping = array();
			foreach (Employee::fields(false) as $key => $value)
				$fieldsMapping[$value['label']] = $key;
			$stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
			File::downloadStream($stream,'export-employes-'.date('d-m-Y').'.xlsx');
			exit();
		}



	});


	//Ajout ou modification d'élément fiche employé
	Action::register('employee_save',function(&$response){
		global $_,$conf,$myUser;
		User::check_access('employee','edit');
		require_once(__DIR__.SLASH.'Employee.class.php');
		$item = Employee::provide();

		if($item->id!=0 && !$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			if(!$myEmployee->can($item,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer cette fiche');
		}

		$item->birthName = mb_strtoupper($_['birthName']);
		$item->name = mb_strtoupper($_['name']);
		$item->firstname = ucfirst(mb_strtolower($_['firstname']));
		if(!empty($_['job']) && is_numeric($_['job'])) $item->job = $_['job'];
		$item->jobDescription = $_['jobDescription'];
		if(!empty($_['statute']) && is_numeric($_['statute'])) $item->statute = $_['statute'];
		$item->manager = $_['manager'];
		$item->workplace = $_['workplace'];
		if(!empty($_['account'])) $item->account = $_['account'];
		if(isset($_['hardware'])) $item->hardware = json_encode($_['hardware']);
		$item->date = timestamp_date($_['date']);
		$item->comment = $_['comment'];
		$item->state = Employee::ACTIVE;
		$item->save();
		//Ajout upload Photo
		if(!empty($_['photo']))
			File::save_component('photo', 'employee/employee/'.$item->id.'/photo.{{extension}}');
		//Ajout upload Pièces jointes
		if(!empty($_['attachments']))
			File::save_component('attachments', 'employee/employee/'.$item->id.'/attachments/{{label}}');
		$response = $item->toArray();

		//Envois d'une notification si la fiche vient d'être créée
		if($_['id']==''){
			$recipients = explode(',',$conf->get('employee_save_recipients'));
			if($recipients && !empty($recipients)){
				Plugin::callHook('emit_notification',array(array(
					'label' => 'Une fiche employé à été créé par '.$myUser->fullname().' pour '.$item->firstname.' '.$item->name,
					'html' => 'Une fiche employé à été créé par '.$myUser->fullname().' pour '.$item->firstname.' '.$item->name.', cliquez <a href="'.ROOT_URL.'index.php?module=employee&page=sheet.employee&id='.$item->id.'">ici pour en savoir plus</a>',
					'meta' => array('link' => ROOT_URL.'index.php?module=employee&page=sheet.employee&id='.$item->id),
					'type' => 'employee',
					'recipients' => $recipients //contient logins
				)));
			}
		}

	});

	//Suppression d'élement fiche employé
	Action::register('employee_delete',function(&$response){
		global $_,$myUser;
		User::check_access('employee','delete');
		require_once(__DIR__.SLASH.'Employee.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");

		$item = Employee::provide();
		if($item->id==0) return $response;

		if(!$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			if(!$myEmployee->can($item,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer cette fiche');
		}

		$item->state = Employee::INACTIVE;
		$item->save();
	});

	//Employee : Gestion upload Photo
	Action::register('employee_employee_photo',function(&$response){
			File::handle_component(array(
				'namespace' => 'employee', //stockés dans file/employee/*.*
				'access' => 'employee', // crud sur employee,
				'extension' => 'jpg,png,bmp,gif,jpeg', // extensions
				'size' => '10000000', // taille max
				'limit' => '1', // nb max de fichiers
				'storage' => 'employee/employee/{{data.id}}/photo.*' //chemin complet vers le fichier stocké
			),$response);
	});

	//Employee : Gestion upload Pièces jointes
	Action::register('employee_employee_attachments',function(&$response){

			File::handle_component(array(
				'namespace' => 'employee', //stockés dans file/employee/*.*
				'access' => 'employee', // crud sur employee,
				'extension' => 'pdf,docx,doc,xlsx,xls,msg,vcard,vcf,png,jpg,jpeg,bmp,gif,ppt,pptx,txt,eml', // extensions
				'size' => '1000000000', // taille max
				'storage' => 'employee/employee/{{data.id}}/attachments/*' //chemin complet vers le fichier stocké
			),$response);
	});

	//Sauvegarde des configurations de Fiche employé
	Action::register('employee_setting_save',function(&$response){
		global $_,$conf;
		User::check_access('employee','configure');
		//Si input file "multiple", possibilité de normaliser le
		//tableau $_FILES récupéré avec la fonction => normalize_php_files();
		foreach(Configuration::setting('employee') as $key=>$value){
			if(!is_array($value)) continue;
			$allowed[] = $key;
		}
		foreach ($_['fields'] as $key => $value) {
			if(in_array($key, $allowed))
				$conf->put($key,$value);
		}
	});

	/* COMPOSANT*/
	//recherche autocomplete
	Action::register('employee_autocomplete',function(&$response){
        	global $myUser,$_;
    		require_once(__DIR__.SLASH.'Employee.class.php');
    		if (!$myUser->connected()) throw new Exception("Vous devez être connecté", 401);
    		$response['rows'] = array();
			$data = array("%".$_['keyword']."%","%".$_['keyword']."%");

			//retourne en priorité les matchs à 100%, pour les match keyword%, puis les autres
			$query = 'SELECT c.* FROM '.Employee::tableName().' c WHERE (c.name LIKE ? OR c.firstname LIKE ?) ';
			$query .= ' LIMIT 10';


        	$devices = Employee::staticQuery($query,$data,true);
        	foreach($devices as $item){
                $response['rows'][] = array(
                	'label'=>html_entity_decode($item->fullname(), ENT_QUOTES),
					'id'=>$item->id,
				);
        	}
        });


	//Récuperation valeur composant depuis l'uid
    Action::register('employee_by_uid',function(&$response){
        global $myUser,$_;
    	if (!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
    	require_once(__DIR__.SLASH.'Employee.class.php');

    	$response['items'] = array();

    	$query = 'SELECT main.* FROM '.Employee::tableName().' main  WHERE main.id IN(';
    	$query .= implode(',', array_fill(0, count($_['items']), '?'));
    	$query .= ')';

	    foreach(Employee::staticQuery($query,$_['items'],true) as  $item) {
	       $row = array(); //on ne met pas toArray car certaines infos sont confidentielles
    	   $row['label'] =  html_entity_decode($item->fullname(), ENT_QUOTES);
    	   $row['id'] =  $item->id;
    	   $row['job'] =  $item->id;
    	   $response['items'][$row['id']] = $row;
	    }

    });


	/** EMPLOYEEWORKTIME / TEMPS DE TRAVAIL EMPOYé **/
	//Récuperation d'une liste de temps de travail empoyé
	Action::register('employee_employee_work_time_search',function(&$response){
		global $_;
		User::check_access('employee','read');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');

		$employeeworktimes = EmployeeWorkTime::loadAll();
		$response['rows'] = array();
		foreach($employeeworktimes as $employeeworktime){
			$row = $employeeworktime->toArray();
			$row['recovertype'] = EmployeeWorkTime::recovertypes($row['recovertype']);

			$hourByDay = json_decode($row['hourByDay']);
			$row['hourByDay'] = array();
			for($i=1;$i<8;$i++){
				$row['hourByDay'][] = array('day'=>day_name($i),'hours'=>isset($hourByDay[$i])? $hourByDay[$i-1] :0 );
			}
			$response['rows'][] = $row;
		}

	});


	//Ajout ou modification d'élément temps de travail empoyé
	Action::register('employee_employee_work_time_save',function(&$response){
		global $_;
		User::check_access('employee','configure');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		$item = EmployeeWorkTime::provide();
		$item->label = $_['label'];
		$item->hourByWeek = $_['hourByWeek'];
		$item->dayByYear = $_['dayByYear'];
		$item->hourByDay = $_['hourByDay'];
		$item->recovertype = $_['recovertype'];
		$item->save();

		$response = $item->toArray();
	});

	//Récuperation ou edition d'élément temps de travail empoyé
	Action::register('employee_employee_work_time_edit',function(&$response){
		global $_;
		User::check_access('employee','configure');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		$response = EmployeeWorkTime::getById($_['id'],0)->toArray();
	});


	//Suppression d'élement temps de travail empoyé
	Action::register('employee_employee_work_time_delete',function(&$response){
		global $_;
		User::check_access('employee','configure');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		EmployeeWorkTime::deleteById($_['id']);
	});


	/** EMPLOYEECONTRACT / CONTRAT EMPLOYé **/
	//Récuperation d'une liste de contrat employé
	Action::register('employee_employee_contract_search',function(&$response){
		global $_,$myUser;
		User::check_access('employee','read');


		if(!isset($_['employee'])) throw new Exception('Identifiant employé manquant');

		require_once(__DIR__.SLASH.'EmployeeContract.class.php');
		require_once(__ROOT__.SLASH.'plugin/employee/Employee.class.php');
		require_once(__ROOT__.SLASH.'plugin/employee/EmployeeWorkTime.class.php');

		$employee = Employee::getById($_['employee']);
		if(!$employee) throw new Exception('Employé inexistant');

		if(!$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de consulter des contrats pour cette fiche');
		}


		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT main.*,main.id as id, '.Employee::joinString('Employee').', '.EmployeeWorkTime::joinString('EmployeeWorkTime').' FROM '.EmployeeContract::tableName().' main  LEFT JOIN '.Employee::tableName().' Employee ON main.employee=Employee.id  LEFT JOIN '.EmployeeWorkTime::tableName().' EmployeeWorkTime ON main.worktime=EmployeeWorkTime.id  WHERE 1';
		$data = array();
		//Recherche simple

		$query .= ' AND main.employee = ?';
		$data[] = $employee->id;


		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.employee','main.start','main.end','main.type','main.statute','main.salary','main.worktime','main.comment'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.employee','main.start','main.end','main.type','main.statute','main.salary','main.worktime','main.comment'),$query,$data);

		$query .= '  ORDER BY main.start DESC,main.end DESC' ;

		//Pagination
		//Par défaut pour une recherche, 20 items, pour un export 5000 max
		$itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
		//force le nombre de page max a 50 coté serveur
		$itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;

		$response['pagination'] = EmployeeContract::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		$employeecontracts = EmployeeContract::staticQuery($query,$data,true,1);


		$typeList = Dictionary::slugToArray('employee_employeecontract_type',true);
		$statuteList = Dictionary::slugToArray('employee_employeecontract_statute',true);

		$response['rows'] = array();
		foreach($employeecontracts as $employeecontract){
			$row = $employeecontract->toArray();
			$row['employee'] = $employeecontract->join('employee')->toArray();
			$row['worktime'] = $employeecontract->join('worktime')->toArray();
			$row['start-readable'] = date('d/m/Y',$row['start']);
			if(!empty($row['end'])) $row['end-readable'] = date('d/m/Y',$row['end']);

			$row['type'] = isset($typeList[$row['type']]) ? $typeList[$row['type']] : new Dictionary();
			$row['statute'] = isset($statuteList[$row['statute']]) ? $statuteList[$row['statute']] : new Dictionary();
			$row['comment'] = html_entity_decode($row['comment']);
			$response['rows'][] = $row;
		}



	});


	//Ajout ou modification d'élément contrat employé
	Action::register('employee_employee_contract_save',function(&$response){
		global $_,$myUser;
		User::check_access('employee','edit');
		require_once(__DIR__.SLASH.'EmployeeContract.class.php');
		require_once(__DIR__.SLASH.'Employee.class.php');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		$item = EmployeeContract::provide('id',1);
		$employee = $item->join('employee');

		if($item->id!=0 && !$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer des contrats pour cette fiche');
		}


		$item->employee = $_['employee'];
		$item->start = timestamp_date($_['start']);
		$item->end = timestamp_date($_['end']);

		if(!empty($item->start) && !empty($item->end) && $item->start>$item->end) throw new Exception("La date de départ ne peut pas être inférieure à la date d'arrivée");

		//Vérification qu'aucun autre contrat n'est actif si celui si est le "en cours"
		if(empty($item->end) || $item->end > time() ){
			$currentContract = Employee::getById($_['employee'])->currentContract();

			if($currentContract->id!=0 && $currentContract->id!=$item->id ) throw new Exception('Vous ne pouvez enregistrer deux contrats actifs en même temps, veuillez vérifier les dates de départ et d\'arrivée');
		}


		if(!empty($_['type']) && is_numeric($_['type'])) $item->type = $_['type'];
		if(!empty($_['statute']) && is_numeric($_['statute'])) $item->statute = $_['statute'];
		$item->salary = $_['salary'];
		$item->worktime = $_['worktime'];
		$item->comment = $_['comment'];
		$item->save();

		$response = $item->toArray();
	});



	//Edition d'élément contrat employé
	Action::register('employee_employee_contract_edit',function(&$response){
		global $_,$myUser;
		User::check_access('employee','read');
		require_once(__DIR__.SLASH.'Employee.class.php');
		require_once(__DIR__.SLASH.'EmployeeContract.class.php');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		$item = EmployeeContract::provide('id',1);
		$employee = $item->join('employee');

		if($item->id!=0 && !$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de consulter les contrats pour cette fiche');
		}

		if($item->id==0){
			$item->start = time();
			$item->end = '';
		}

		$row = $item->toArray();
		$row['start'] = date('d/m/Y',$row['start']);

		if(!empty($row['end'])) {
			$row['end'] = date('d/m/Y',$row['end']);
		}else{
			$row['end'] = '';
		}

		$response = $row;
	});

	//Suppression d'élement contrat employé
	Action::register('employee_employee_contract_delete',function(&$response){
		global $_,$myUser;
		User::check_access('employee','delete');
		require_once(__DIR__.SLASH.'Employee.class.php');
		require_once(__DIR__.SLASH.'EmployeeContract.class.php');
		require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");

		$item = EmployeeContract::provide('id',1);
		$employee = $item->join('employee');
		if($item->id!=0 && !$myUser->can('employee','configure')){
			$myEmployee = Employee::load(array('account'=>$myUser->login));
			if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de supprimer cette fiche');
		}

		EmployeeContract::deleteById($item->id);
	});

?>