<?php
global $_,$conf;
switch($_['action']){

	//GESTIONS DES CONTACTS
	
	//Enregistrement (ajout/modification)
	case 'contact_save':
		Action::write(function(&$response){
			global $myUser,$_;
			User::check_access('example','edit');
			require_once(__DIR__.SLASH.'Contact.class.php');
			require_once(PLUGIN_PATH.'notification'.SLASH.'Notification.class.php');

			$contact = Contact::provide();
			//on garde l'ancien objet a l'instant t pour le log comparatif (voir en fin d'action)
			$oldcontact = clone $contact;
			

			$title = isset($contact->id) ? 'Édition d\'un contact' : 'Création d\'un contact';
			$msg = isset($contact->id) ? 'Le contact '.$contact->label.' a été édité' : 'Création du contact '.$contact->label;

			$contact->fromArray($_);
			$contact->birth = timestamp_date($contact->birth);
			$contact->hour = timestamp_hour($contact->hour);
			$contact->save();

			//Ajout des fichiers joints
			if(!empty($_['document_temporary'])){
				$files = json_decode($_['document_temporary'],true);
				foreach($files as $file){
					$from = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? File::temp().utf8_decode($file['path']) : File::temp().$file['path'];
					$to = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($file['name']) : $file['name'];
					File::move($from, 'contact'.SLASH.'documents'.SLASH.$contact->id.SLASH.$to);
				}
			}
		
			//Ajout de l'avatar a la base de media 
			if(!empty($_FILES['avatar']) &&  $_FILES['avatar']['size']!=0 ){
				
				$logo = File::upload('avatar','contact'.SLASH.$contact->id.'.{{ext}}',1048576,array('jpg','png','jpeg'));
				Image::resize($logo['absolute'],200,200);
				Image::toJpg($logo['absolute']);
			}

			// GESTION ENVOI NOTIFICATION
			Plugin::callHook('emit_notification',array(array(
					'label' => $title,
					'html' => $msg,
					'type' => "notice",
					'meta' => array('link' => ROOT_URL.'/index.php?module=example&page=sheet&id='.$contact->id),
					'recipients' => array($myUser->login) // recipients contient login
				)
			));

			$response['id'] = $contact->id;
			$response['contact'] = $contact->label;
			
			//Exemple de mise en place de logs comparatif
			Log::compare($oldcontact,$contact,function(&$log){
				//ajout d'une info supplémentaire sur le log comparatif
				$log->label['meta_info'] =  "example";
			});
		});
	break;

	//Recherche d'une liste
	case 'contact_search':

	Action::write(function(&$response){
		global $myUser,$_;
		User::check_access('example','read');
		require_once(__DIR__.SLASH.'Contact.class.php');

		$query = 'SELECT * FROM {{table}} WHERE 1';
		$data = array();



		//Recherche simple
		if(!empty($_['filters']['keyword'])){
			$query .= ' AND label LIKE ?';
			$data[] = '%'.$_['filters']['keyword'].'%';
		}

		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label','phone','birth','author','vehicle', 'mycheckbox1'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('label','phone'),$query,$data);

		//Pagination
		$response['pagination'] = Contact::paginate(20,(!empty($_['page'])?$_['page']:0),$query,$data);
		
		//Mise en forme des résultats
		foreach (Contact::staticQuery($query,$data,true) as $contact) {
			$row = $contact->toArray(true);
			$row['created'] = date('d/m/Y H:i',$contact->created);
			$row['updated'] = date('d/m/Y H:i',$contact->updated);
			

			$row['author'] = array();
			foreach (explode(',',$contact->author) as $login) {
				if(is_numeric($login)){
					//rank
					$item = Rank::getById($login);
					$item = !$item ? new Rank(): $item;
					$row['author'][] =$item->label;
				}else{
					//user
					$row['author'][] = User::byLogin($login)->fullName();
				}
				
			}
			$row['author'] = implode(',',$row['author']);

			$row['birth'] = date('d/m/Y',$contact->birth);			
			$row['picture'] = $contact->picture().'&v='.time();
			$response['rows'][] = $row;
		}

		/* Mode export */
		if($_['export'] == 'true'){
		    $stream = Excel::exportArray($response['rows'],null,'Export');
		    File::downloadStream($stream,'export-'.date('d-m-Y').'.xlsx');
		    exit();
		}
	});
	break;

	//Suppression par id
	case 'contact_delete':
	Action::write(function(&$response){
		global $myUser,$_;
		User::check_access('example','delete');
		require_once(__DIR__.SLASH.'Contact.class.php');
		if(!isset($_['id']) || !is_numeric($_['id'])) throw new Exception("Id non spécifié ou non numerique");
		
		//Exemple de mise en place de logs comparatif
		Log::compare(Contact::getById($_['id']),false);
		//suppression 
		Contact::deleteById($_['id']);
	});
	break;

	//Suppression document
	case 'contact_delete_document':
	Action::write(function(&$response){
		global $myUser,$_;
		User::check_access('example','delete');
		require_once(__DIR__.SLASH.'Contact.class.php');
		if(!isset($_['path']) ) throw new Exception("Chemin non spécifié ou non numerique");
		//Le premier argument est un namspace de sécurité 
		//et assure que le fichier sera toujours cloisoné dans un contexte file/contact/documents
		$path = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($_['path']) : $_['path'];
		File::delete('contact'.SLASH.'documents',$path);
	});
	break;

	case 'contact_add_document':
	Action::write(function(&$response){
		global $myUser,$_;
		User::check_access('example','edit');
		require_once(__DIR__.SLASH.'Contact.class.php');

		$contact = Contact::provide();
		$contact->save();

		foreach ($_['files'] as $file) {
			$name = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($file['name']) : $file['name'];
			$row = File::move(File::temp().$file['path'],'contact'.SLASH.'documents'.SLASH.$contact->id.SLASH.$name);
			$row['url'] = 'action.php?action=contact_download_document&path='.SLASH.$contact->id.SLASH.rawurlencode($file['name']);
			$row['oldPath'] = $file['path'];
			$response['files'][] = $row;
		}
		$response['id'] = $contact->id;
	});
	break;

	//Téléchargement des documents
	case 'contact_download_document':
		global $myUser,$_;
		User::check_access('example','read');
		$path = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_decode($_['path']) : $_['path'];
		File::downloadFile(File::dir().'contact'.SLASH.'documents'.SLASH.$path);
	break;

	//Affichage de l'avatar
	case 'contact_download_picture':
		global $myUser,$_;
		User::check_access('example','read');
		try{
			File::downloadFile(File::dir().'contact'.SLASH.$_['contact'].'.'.$_['extension']);
		} catch(Exception $e){
			File::downloadFile('img'.SLASH.'default-avatar.png');
		}
	break;

	//Suppression image contact
	case 'contact_avatar_delete':
	    Action::write(function(&$response){
	        global $myUser,$_;
	        User::check_access('example','edit');
			require_once(__DIR__.SLASH.'Contact.class.php');
	        $item = Contact::provide();
	        if(!$item) throw new Exception("Aucun contact ne correspond en base");

	        foreach (glob(__ROOT__.FILE_PATH.'contact'.SLASH.$item->id.".*") as $filename)
	            unlink($filename);

	        if(!file_exists(__ROOT__.FILE_PATH.'contact'.SLASH.'.thumbnails')) return;
	        foreach (glob(__ROOT__.FILE_PATH.'contact'.SLASH.'.thumbnails'.SLASH.$item->id.".*") as $filename) {
	            unlink($filename);
	        }
	    });
	break;

	//Récupération card d'un contact
	case 'example_contact_card':
		Action::write(function(&$response){
			global $myUser,$myFirm,$_;
			User::check_access('example','read');
			require_once(__DIR__.SLASH.'Contact.class.php');

			$contact = Contact::provide();

			ob_start();
			require_once(__DIR__.SLASH.'card.example.contact.php');
			$stream = ob_get_clean();
			$response['content'] = $stream;
		});
	break;
	
	default : 
		global $myFirm;
		if($myFirm->has_plugin('fr.idleman.stripe') && $_['action']=='example_stripe_pay'){
			Action::write(function(&$response){
				global $_;
				//paye la somme de 20 €
				$response = stripe_payment($_['token'],22.5,'Description paiement','Description acheteur');
	        });
		}
	break;
}


?>