<?php
global $_,$conf;
switch($_['action']){
	
	case 'notification_send':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'Notification.class.php');

			User::check_access('notification','configure');
			
			if(!isset($_['label'])) throw new Exception("Merci de spécifier le sujet de la notification");
			

			if(!isset($_['recipients'])) $_['recipients'] = '';
			$recipients =  explode(',',$_['recipients']);

			if($_['recipients']==''){
				foreach (User::getAll() 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));

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

		//Récuperation d'une liste de notification
	case 'notification_search':
		Action::write(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 '.Notification::tableName().' WHERE pinned=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','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,0);
			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;
			}
		});
	break;

	//Suppression d'élement notification et de ses user notifications associés
	case 'notification_delete':
		Action::write(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']);
		});
	break;

	case 'notification_widget_load':
		global $myUser;
		require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
		$widget = DashboardWidget::current();
		$widget->title = 'Mes dernières alertes';
		ob_start();
		require_once(__DIR__.SLASH.'widget.php');
		$widget->content = ob_get_clean();
		echo json_encode($widget);
	break;

	case 'notification_widget_configure_save':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');
			$widget = DashboardWidget::getById($_['id']);
			
			$widget->data('types',$_['types']);
			$widget->data('notification-number',$_['notification-number']);
			$widget->data('notification-length',$_['notification-length']);
			$widget->save();
		});
	break;

	case 'notification_widget_configure':
		global $myUser;
		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 ;
	break;

	//Récuperation d'une liste de notification
	case 'notification_user_notification_search':
		Action::write(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($_['synthesis']) ? 5 : 100,
				'unread' =>isset($_['unread'])  ? $_['unread'] : false,  
			));

			
			foreach ($unreads as $row) {
				$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($_['synthesis']) ? 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'] = UserNotification::get_unreads_count($myUser,'compact');
		});
	break;

		//Active/Désactive l'état lu
	case 'notification_usernotification_toggle_read':
		Action::write(function(&$response){
			global $myUser,$_;
			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');
		});
	break;

	case 'notification_user_notification_read_all':
		Action::write(function(&$response){
			global $myUser,$_;
			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');
		});
	break;

	//Suppression d'élement usernotification
	case 'notification_usernotification_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			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']);
		});
	break;

	case 'notification_usernotifications_delete':
		Action::write(function(&$response){
			global $myUser,$_;
			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);
			}
		});
	break;

	//Sauvegarde des préférences de notifications
	case 'notification_user_save_preference':
		Action::write(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));
		});
	break;
}


?>