<?php


	/** SMS **/
	//Sauvegarde des configurations de sms
	Action::register('sms_setting_save',function(&$response){
		global $myUser,$_,$conf;
		User::check_access('sms','configure');
		foreach(Configuration::setting('sms') as $key=>$value){
			if(!is_array($value)) continue;
			$allowed[] = $key;
		}
		foreach ($_['fields'] as $key => $value) {
			if(in_array($key, $allowed))
				$conf->put($key,$value);
		}
	});

	//Ajout ou modification d'élément sms
	Action::register('sms_send',function(&$response){
		global $myUser,$_,$conf;
		User::check_access('sms','edit');

		Plugin::callHook('sms_send',array($_['phone'],html_entity_decode($_['message'])));

		$history = new History();
		$history->scope = 'sms';
		$history->uid = $_['phone'];
		$history->comment = '';
		$history->type = 'send';

		$history->save();
	});

	/** HISTORY **/
	//Récuperation d'une liste de history
	Action::register('sms_histories_search',function(&$response){

		global $myUser,$_;
		User::check_access('sms','read');


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

		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('uid','creator','created'),$query,$data);


		$query.=' ORDER BY id DESC';

		//Pagination
		$response['pagination'] = History::paginate(20,(!empty($_['page'])?$_['page']:0),$query,$data);

		$historys = History::staticQuery($query,$data,true,0);

		foreach($historys as $history){
			$row = $history->toArray();
			$row['phone'] = $row['uid'];
			$row['createdReadable'] = complete_date($row['created']).' à '.date('H:i:s',$row['created']);
			$row['created'] = date('d/m/Y H:i:s',$row['created']);
			$row['fullname'] = User::byLogin($row['creator'])->fullName();
			$response['rows'][] = $row;
		}
	});

?>