<?php
	/** CONTACTPERSON / CONTACT **/
	//Récuperation d'une liste de contact
	Action::register('contact_contact_person_search',function(&$response){
		global $_;
		User::check_access('contact','read');


		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT * FROM '.ContactPerson::tableName().' WHERE 1';
		$data = array();
		//Recherche simple
		if(!empty($_['filters']['keyword'])){
			$query .= ' AND (name LIKE ? OR firstname LIKE ?)';
			$data[] = '%'.$_['filters']['keyword'].'%';
			$data[] = '%'.$_['filters']['keyword'].'%';
		}

		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('name','firstname','job','civility','state','phone','mail','scope','uid','comment','tag'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('name','firstname','job','civility','state','phone','mail','scope','uid','tag'),$query,$data);

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

		$contactpersons = ContactPerson::staticQuery($query,$data,true,0);

		$ids = array();
		foreach($contactpersons as $contactperson)
			$ids[] = $contactperson->id;

		$contactInfos = array();

		if(!empty($ids)){
			foreach (Contact::loadAll(array('scope'=>'contact_person','uid:IN'=>$ids)) as $contact) {
				if(empty($contactInfos[$contact->uid])) $contactInfos[$contact->uid] = array();
				$contactInfos[$contact->uid][] = $contact;
			}
		}

		$response['rows'] = array();
		foreach($contactpersons as $contactperson){
			$row = $contactperson->toArray();
			$row['civility'] = ContactPerson::civilities($row['civility']);
			$row['fullname'] = $contactperson->fullName();
			$row['phones'] = array();
			$row['mails'] = array();
			$row['tag'] = $contactperson->getTags();
			$row['hasTag'] = !empty($row['tag']);
			$row['rawphones'] = array();
			$row['rawmails'] = array();
			if(!empty($contactInfos[$contactperson->id])){
				foreach ($contactInfos[$contactperson->id] as $key => $contact) {
					if(in_array($contact->type ,array(Contact::PHONE,Contact::MOBILE))){
						$row['phones'][] = $contact->toArray();
						$row['rawphones'][] = $contact->value;
					}else if(in_array($contact->type ,array(Contact::PERSONAL_MAIL,Contact::PROFESSIONAL_MAIL))){
						$row['mails'][] = $contact->toArray();
						$row['rawmails'][] = $contact->value;
					}
				}

			}

			if($_['export'] == 'true'){
				$row['rawphones'] = implode(', ',$row['rawphones']);
				$row['rawmails'] = implode(', ',$row['rawmails']);
				$row['created'] = date('d-m-Y',$row['created']);
				$row['updated'] = date('d-m-Y',$row['updated']);
				$row['name'] = html_entity_decode($row['name']);
				$row['firstname'] = html_entity_decode($row['firstname']);
				$row['job'] = html_entity_decode($row['job']);
				$row['tag'] = implode(',',$row['tag']);
				$row['comment'] = html_entity_decode($row['comment']);
			}

			$row['avatar'] = $row['avatar'] = 'action.php?action=contact_avatar_load&path='.base64_encode($contactperson->avatar());
			$response['rows'][] = $row;
		}

		/* Mode export */
		if($_['export'] == 'true'){

			$fieldsMapping = array();
			foreach (ContactPerson::fields(false) as $key => $value)
				$fieldsMapping[$value['label']] = $key;

			$fieldsMapping['Téléphones'] = 'rawphones';
			$fieldsMapping['E-mails'] = 'rawmails';

			$stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
			File::downloadStream($stream,'export-contacts-'.date('d-m-Y').'.xlsx');
			exit();
		}

	});

	Action::register('contact_contact_search',function(&$response){
		global $_;
		User::check_access('contact','read');

		$response['rows'] = array();
		foreach (Contact::loadAll(array('scope'=>$_['scope'],'uid'=>$_['uid'])) as $key => $contact) {
			$response['rows'][] = $contact->toArray();
		}
	});


	//Ajout ou modification d'élément contact
	Action::register('contact_contact_person_save',function(&$response){
		global $_,$myFirm;
		User::check_access('contact','edit');

		$item = ContactPerson::provide();
		$oldItem = clone $item;
		$item->name = $_['name'];
		$item->firstname = $_['firstname'];
		$item->job = $_['job'];
		$item->civility = $_['civility'];
		$item->setTags($_['tag']);

		$item->state = ContactPerson::ACTIVE;
		//$item->phone = $_['phone'];
		//$item->mail = $_['mail'];
		$item->scope = $_['scope'];
		$item->uid = $_['uid'];
		$item->save();

		History::entityChange('contactperson',$oldItem,$item);

		if(empty($item->uid)){
			$item->uid = $item->id;
			$item->save();
		}
		//Gestion des champs dynamiques
		if($myFirm->has_plugin('fr.core.dynamicform')){
			Plugin::need('dynamicform/DynamicForm');
			Dynamicform::record('contact-form',array(
				'scope'=>'contact_person',
				'uid'=>$item->id
			),$_);
		}

		Contact::delete(array('scope'=>$item->scope,'uid'=>$item->uid));
		if(!empty($_['contacts'])){
			$contacts = json_decode(base64_decode($_['contacts']),true);
			foreach ($contacts as $line) {
				$contact = new Contact();
				$contact->scope = 'contact_person';
				$contact->uid = $item->id;

				$contact->type = $line["type"];
				$contact->value = $line["value"];

				$contact->save();
			}

		}


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


	Action::register('contact_avatar_load',function(&$response){
			global $myUser,$_;
			User::check_access('contact','read');

			$_['path'] = str_replace("..", "", base64_decode($_['path']));


			File::downloadFile($_['path']);
	});



	//Suppression d'élement contact
	Action::register('contact_contact_person_delete',function(&$response){
		global $_;
		User::check_access('contact','delete');

		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		ContactPerson::deleteById($_['id']);
	});



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





?>