<?php


	Action::register('notification_send',function(&$response){

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Notification.class.php');
			User::check_access('notification','configure');

			if(!isset($_['label']) || empty($_['label'])) throw new Exception("Merci de spécifier le sujet de la notification");
			if(!isset($_['type']) || empty($_['type'])) throw new Exception("Merci de spécifier le type de la notification");
			if(!isset($_['recipients'])) $_['recipients'] = '';
			$recipients = explode(',',$_['recipients']);

			if($_['recipients']==''){
				$recipients = array();
				foreach (User::getAll(array('right'=>false)) as $user)
					$recipients[] = $user->login;
			}

			$start = isset($_['start']) && $_['start']!='' ? timestamp_date($_['start']) : mktime(0,0,0) ;
			$end = isset($_['end']) && $_['end']!='' ? timestamp_date($_['end']) : strtotime('+3month',mktime(0,0,0));
			if($start>$end) throw new Exception("Dates de lancement et d'expiration incohérentes");

			Notification::emit(array(
				'label' => $_['label'],
				'html' => wysiwyg_filter(html_entity_decode($_['html'])),
				'pinned' => $_['pinned'],
				'type' => $_['type'],
				'start' => $start,
				'end' => $end,
				'recipients' => $recipients
			));

	});

		//Récuperation d'une liste de notification
	Action::register('notification_search',function(&$response){

			global $myUser,$_;
			User::check_access('notification','read');
			require_once(__DIR__.SLASH.'Notification.class.php');

			// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
			$query = 'SELECT * FROM {{table}} WHERE pinned=? ';
			$data = array(1);

			//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','start','end','type'),$query,$data);

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

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

			$notifications = Notification::staticQuery($query,$data,true);
			foreach($notifications as $notification){
				$row = $notification->toArray();
				$row['start'] = date('d/m/Y',$row['start']);
				$row['end'] = date('d/m/Y',$row['end']);
				$row['type'] = Notification::types($row['type']);
				$response['rows'][] = $row;
			}

	});

	//Suppression d'élement notification et de ses user notifications associés
	Action::register('notification_delete',function(&$response){

			global $myUser,$_;
			require_once(__DIR__.SLASH.'UserNotification.class.php');
			require_once(__DIR__.SLASH.'Notification.class.php');

			User::check_access('notification','configure');

			UserNotification::delete(array('notification'=>$_['id']));
			Notification::deleteById($_['id']);

	});

	Action::register('notification_widget_load',function(&$response){
		global $myUser;
		User::check_access('notification','read');
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		$widget->title = 'Dernières alertes';
		ob_start();
		require_once(__DIR__.SLASH.'widget.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
	});

	Action::register('notification_widget_configure_save',function(&$response){

			global $myUser,$_;
			User::check_access('notification','read');
			require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
			$widget = DashboardWidget::getById($_['id']);

			if(!isset($_['types'])) throw new Exception("Au moins un type de notification à afficher est requis");
			if(!isset($_['notification-number'])) $_['notification-number'] = 5;
			if(!isset($_['notification-length'])) $_['notification-length'] = 150;

			$widget->data('types',$_['types']);
			$widget->data('notification-number',$_['notification-number']);
			$widget->data('notification-length',$_['notification-length']);
			$widget->save();

	});

	Action::register('notification_widget_configure',function(&$response){
		global $myUser;
		User::check_access('notification','read');
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		ob_start();
		require_once(__DIR__.SLASH.'widget.configure.php');
		$content = ob_get_clean();
		echo $content ;
	});

	//Récuperation d'une liste de notification
	Action::register('notification_user_notification_search',function(&$response){

			global $myUser,$_;
			if(!$myUser->connected()) return;
			if(!$myUser->can('notification','read')) return;
			require_once(__DIR__.SLASH.'UserNotification.class.php');
			require_once(__DIR__.SLASH.'Notification.class.php');
			$response['unread'] = 0;

			$unreads = UserNotification::byUser($myUser,array(
				'limit' => isset($_['excerpt']) ? 5 : 100,
				'unread' => isset($_['unread']) ? filter_var($_['unread'], FILTER_VALIDATE_BOOLEAN) : false,
			))->fetchAll();
			$response['unread'] = 0;
			foreach ($unreads as $row) {
				$row['html'] = isset($_['excerpt']) ? truncate(str_replace('"', "'", html_entity_decode($row['html'])), 150, array('keepTags'=>false)) : $row['html'];
				$row['class'] = 'read';
				$row['readState'] = 'non lu';
				if($row['read']==0){
					$row['class'] = 'unread';
					$response['unread']++;
					$row['readState'] = 'lu';
				}

				if($row['pinned']==1) $row['class'] .=' pinned';
				$row['created-relative'] = isset($_['excerpt']) ? relative_time($row['created'], null, 7) : relative_time($row['created'], null, 7, true);
				$meta = json_decode($row['meta']);
				$row['link'] = isset($meta->link) ? $meta->link : 'index.php?module=notification#'.$row['id'];
				$response['rows'][] = $row;
			}


			$response['unread'] = $response['unread'] > 5 ? '5+' : $response['unread'];

	});

		//Active/Désactive l'état lu
	Action::register('notification_usernotification_toggle_read',function(&$response){

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

			require_once(__DIR__.SLASH.'UserNotification.class.php');
			$item = UserNotification::getById($_['id']);
			if($myUser->login != $item->user) throw new Exception("Permissions insuffisantes",403);
			$item->read = $item->read == true ? false : true;
			$item->save();

			$response['read'] = $item->read;
			$response['unread'] = UserNotification::get_unreads_count($myUser,'detailled');

	});

	Action::register('notification_user_notification_read_all',function(&$response){

			global $myUser,$_;
			User::check_access('notification','read');
			require_once(__DIR__.SLASH.'UserNotification.class.php');
			foreach (json_decode($_['id']) as $id) {
				$item = UserNotification::getById($id);
				if($myUser->login != $item->user) throw new Exception("Permissions insuffisantes",403);
				$item->read = true;
				$item->save();
				$response['read'][$id] = $item->read;
			}
			$response['unread'] = UserNotification::get_unreads_count($myUser,'detailled');

	});

	//Suppression d'élement usernotification
	Action::register('notification_usernotification_delete',function(&$response){

			global $myUser,$_;
			User::check_access('notification','delete');
			require_once(__DIR__.SLASH.'UserNotification.class.php');
			if(!$notification = UserNotification::getById($_['id'])) return;
			if($myUser->login != $notification->user) throw new Exception("Permissions insuffisantes",403);
			UserNotification::deleteById($_['id']);

	});

	Action::register('notification_usernotifications_delete',function(&$response){

			global $myUser,$_;
			User::check_access('notification','delete');
			require_once(__DIR__.SLASH.'UserNotification.class.php');
			foreach (json_decode($_['id']) as $id) {
				$notification = UserNotification::getById($id);
				if($myUser->login != $notification->user) throw new Exception("Permissions insuffisantes",403);
				UserNotification::deleteById($id);
			}

	});

	//Sauvegarde des préférences de notifications
	Action::register('notification_user_save_preference',function(&$response){

			global $myUser,$_;
			require_once(__DIR__.SLASH.'Notification.class.php');

			if(!$myUser->connected()) throw new Exception("Vous devez être connecté pour enregistrer vos préférences", 401);
			foreach ($_['preferences'] as $method => $pref) {
				foreach ($pref as $key => $value){
					$_['preferences'][$method][$key] = ($value == 'true') ? true : false;
				}
			}
			$preferences = Notification::settingPreferences($myUser->login, $_['preferences']);
			$myUser->preference('notification_categories',json_encode($preferences));


	});


	//Sauvegarde des configurations de
	Action::register('notification_setting_save',function(&$response){

			global $myUser,$_,$conf;
			User::check_access('notification','configure');
			foreach(Configuration::setting('notification') as $key=>$value){
				if(!is_array($value)) continue;
				$allowed[] = $key;
			}

			foreach ($_['fields'] as $key => $value){
				if(!in_array($key, $allowed)) continue;

				$value = html_entity_decode($value);
				if($key=='notification_mail_reply' && !check_mail($value) && !empty($value)) throw new Exception("Email invalide :".$value);

				$conf->put($key,$value);
			}

			foreach ($_['followings'] as $key => $value)
				$conf->put($key,$value);

	});




?>
