<?php
//Déclaration d'un item de menu dans le menu principal
function notification_menu(){
	global $_,$myUser;
	if(!$myUser->can('notification','read')) return;
	
	?>
	<div class="dropdown notification_menu ml-auto">
	  <button class="btn btn-dark dropdown-toggle" type="button" id="dropdownNotification" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
	  	<span class="badge badge-pill badge-danger notification-number hidden">-</span>
	    <i class="fas fa-bell"></i>	
	  </button>
	  <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownNotification"></div>
	</div>

	<div class="notification-template">
	    <div data-id="{{id}}" class="dropdown-item notification-{{class}} notification-item" onclick="notification_user_notification_toggle_read(this,event,'.dropdown-item'); window.location='{{link}}';">
	    	<ul class="notification-item-options">
	    		<li onclick="notification_user_notification_toggle_read(this,event,'.dropdown-item')" title="Marquer comme lu" class="notification-read"><i class="fas fa-eye"></i></li>
	    		<li onclick="notification_user_notification_delete(this,event,'.dropdown-item')" title="Supprimer la notification" class="notification-delete btn-delete"><i class="fas fa-times"></i></li>
	    	</ul>
	    	<small>{{created-relative}}</small>
	    	<strong class="mt-2">{{label}}</strong>
	    	<p>{{{html}}}</p>
		</div>
		<div class="dropdown-divider" data-notification="{{id}}"></div>
	</div>

	<?php
}

//Cette fonction va generer une page quand on clique sur notification dans menu
function notification_page(){
	global $_,$myUser;
	if(!isset($_['module']) || $_['module'] !='notification') return;
	$page = !isset($_['page']) ? 'list' : $_['page'];
	$file = __DIR__.SLASH.'page.'.$page.'.php';
	if(!file_exists($file)) throw new Exception("Page ".$page." inexistante");
	
	require_once($file);
}

//Fonction executée lors de l'activation du plugin
function notification_install($id){
	if($id != 'fr.idleman.notification') return;
	Entity::install(__DIR__);

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

	$recipients = array();
	foreach (User::getAll() as $user) {
		$recipients[] = $user->login;
	}
	// envoi premiere notif
	Notification::emit(
		array(
			'label' => "Nouvelle fonctionnalité de notification !",
			'html' => "Une nouvelle <strong>Notification</strong> 
			à été ajoutée à votre espace.<br/> Vous pouvez consulter toutes vos notifications <a href='".ROOT_URL."/index.php?module=notification'>ici</a> et configurer vos <a href='".ROOT_URL."/account.php?section=notification'>préférences la.</a>",
			'meta' => array(
				'link' => ROOT_URL.'/index.php?module=notification',
			),
			'recipients' => $recipients
		)
	);
}

//Fonction executée lors de la désactivation du plugin
function notification_uninstall($id){
	if($id != 'fr.idleman.notification') return;
	Entity::uninstall(__DIR__);
}

//Déclaration des sections de droits du plugin
function notification_section(&$sections){
	$sections['notification'] = "Gestion des droits sur le plugin notification";
}

//Cette fonction comprends toutes les actions
//du plugin qui ne nécessitent pas de vue html
function notification_action(){
	require_once(__DIR__.SLASH.'action.php');
}

//Déclaration du menu de réglages
function notification_menu_setting(&$settingMenu){
	global $_, $myUser;
	if(!$myUser->can('notification','configure')) return;
	$settingMenu[]= array(
		'sort' =>1,
		'url' => 'setting.php?section=notification',
		'icon' => 'fas fa-angle-right',
		'label' => 'Notifications'
	);
}
function notification_menu_account(&$accountMenu){
	global $_, $myUser;
	if(!$myUser->connected() || !$myUser->can('notification', 'read')) return;
	$accountMenu[]= array(
		'sort' =>0,
		'url' => 'account.php?section=notification',
		'icon' => 'fas fa-angle-right',
		'label' => 'Notifications',
	);	
}

//Déclaration des pages de réglages
function notification_content_setting(){
	global $_;
	if(file_exists(__DIR__.SLASH.'setting.'.$_['section'].'.php'))
		require_once(__DIR__.SLASH.'setting.'.$_['section'].'.php');
}

//Déclaration des pages de réglages
function notification_content_account(){
	global $_;
	if(file_exists(__DIR__.SLASH.'account.'.$_['section'].'.php'))
		require_once(__DIR__.SLASH.'account.'.$_['section'].'.php');
}

//Émission d'une notification
function notification_emit_notification($params){
	require_once(__DIR__.SLASH.'Notification.class.php');
	Notification::emit($params);
}

function notification_methods(&$sendTypes){
	require_once(__DIR__.SLASH.'Notification.class.php');
	require_once(__DIR__.SLASH.'UserNotification.class.php');

	$sendTypes[] = array(
		'slug' => 'mail',
		'label' => 'Mail',
		'explain' => 'Envoi par e-mail',
		'icon' => 'far fa-envelope-open',
		'callback' => function($recipient, $infos, $notification){
			if($infos['pinned'] == 1) return;
			if(!isset($recipient)) throw new Exception("Aucun destinataires n\'a été renseignés pour l\'envoi de mail");

			// ENVOI MAIL

			global $conf;
			$expeditor = $conf->get('notification_mail_from') != '' ? $conf->get('notification_mail_from'): 'Hackpoint <no-reply@hackpoint.fr>';
			$reply = $conf->get('notification_mail_reply') != '' ? $conf->get('notification_mail_reply'): 'no-reply@hackpoint.fr';

			$mail = new Mail();
			$mail->expeditor = $expeditor;
			$mail->reply = $reply;
			$mail->title = $infos['label'];
			$mail->message = '<h3>'.$infos['label'].'</h3><p>'.$infos['html'].'</p>';
			$mail->message .= (isset($infos['meta']['link'])) ? '<a href="'.$infos['meta']['link'].'">Accéder à l\'ERP</a>' : '';

			$usermail = User::byLogin($recipient);
			$mail->recipients['to'][]  = $usermail->mail;

			/* /!\ ralentissements  /!\ */
			$test = $mail->send();
		}
	);
	$sendTypes[] = array(
		'slug' => 'interface',
		'label' => 'Interface',
		'explain' => 'Visualisation via l\'ERP',
		'icon' => 'far fa-bell',
		'callback' => function($recipient, $infos, $notification){

			if($infos['pinned'] == 1) return;

			if(!isset($recipient))
				throw new Exception("Aucun destinataires n\'a été renseignés pour l\'envoi de notifications à travers l\'ERP");


			$userNotification = new UserNotification();
			$userNotification->notification = $notification->id;
			$userNotification->user = $recipient;
			$userNotification->read = 0;
			$userNotification->save();
			
		}
	);
}

function notification_widget(&$widgets){
	global $myUser;
	require_once(__DIR__.SLASH.'..'.SLASH.'dashboard'.SLASH.'DashboardWidget.class.php');


	$modelWidget = new DashboardWidget();
	$modelWidget->model = 'notification';
	$modelWidget->title = 'Notification';
	$modelWidget->options[] = array('function'=>'window.location = \'index.php?module=notification\';','icon'=>'fa-eye','title'=>'Toutes les notifications');
	$modelWidget->icon = 'fas fa-bell';
	$modelWidget->background = '#fa8231';
	$modelWidget->load = 'action.php?action=notification_widget_load';
	$modelWidget->configure = 'action.php?action=notification_widget_configure';
	$modelWidget->configure_callback = 'notification_widget_configure_save';
	$modelWidget->js = [Plugin::url().'/js/widget.js?v='.time()];
	$modelWidget->css = [Plugin::url().'/css/widget.css?v=1'.time()];
	$modelWidget->description = "Affiche les dernières alertes d'une catégorie donnée";

	$widgets[] = $modelWidget;
}

//Déclaration des settings de base
//Types possibles : text,select ( + "values"=> array('1'=>'Val 1'),password,checkbox. Un simple string définit une catégorie.
Configuration::setting('notification',array(
    "E-mail",
    'notification_mail_from' => array("label"=>"Envois de la part de","legend"=>"format: Nom &lt;email&gt;, &nbsp;&nbsp;&nbsp; ex: Idleman &lt;no-reply@hackpoint.fr&gt;","type"=>"text"),
    'notification_mail_reply' => array("label"=>"Réponse au mail","legend"=>"adresse e-mail unique ex: me@domain.com","type"=>"text"),
));

//Déclation des assets
Plugin::addCss("/css/main.css"); 
Plugin::addJs("/js/main.js"); 

//Mapping hook / fonctions
Plugin::addHook("widget", "notification_widget");
Plugin::addHook("install", "notification_install");
Plugin::addHook("uninstall", "notification_uninstall"); 
Plugin::addHook("section", "notification_section");
Plugin::addHook("login_header", "notification_menu"); 
Plugin::addHook("page", "notification_page");  
Plugin::addHook("action", "notification_action");

Plugin::addHook("menu_account", "notification_menu_account");
Plugin::addHook("content_account", "notification_content_account");

Plugin::addHook("menu_setting", "notification_menu_setting");    
Plugin::addHook("content_setting", "notification_content_setting");    
 
Plugin::addHook("emit_notification", "notification_emit_notification");
Plugin::addHook("notification_methods", "notification_methods");
?>