<?php
/*
	Effet de workflow
	Envois une notification à un ou plusieurs utilisateurs interne
*/
class NotificationEffect{

	//Descriptif du type d'effet
	public static function manifest($key = null){
		$manifest = array(
			'slug' => 'notification',
			'label' => 'Envoyer une notification',
			'class' => get_called_class(),
			'path' => __FILE__,
			'icon' => 'far fa-bell',
			'color' => '#ff9f43',
		);
		if(!isset($key)) return $manifest;
		return isset($manifest[$key]) ? $manifest[$key] : '' ;
	}

	//méthode d'affichage de l'effet
	public static function form($item){
		$html  = '';
		$class = get_called_class();

		//$class::manifest('icon')
		ob_start();
		?>

		<div class="input-group">
			<div class="input-group-text input-group-prepend">
			Notifier  :
			</div>
			<input type="text" data-id="recipient" data-type="user" class="form-control" value="<?php echo isset($item['recipient']) ? $item['recipient'] : '' ?>" placeholder="utilisateur" required>

			<div class="input-group mt-1">
			<div class="input-group-text input-group-prepend">
			Titre  :
			</div>
			<input type="text" data-id="title" class="form-control" value="<?php echo isset($item['title']) ? $item['title'] : '' ?>" placeholder="Bonjour,...">
			</div>
			<textarea  data-id="message" data-type="wysiwyg"><?php echo isset($item['message']) ? $item['message'] : '' ?></textarea>

		</div>

		<?php
		$html = ob_get_clean();
		return $html;
	}

	public static function run($effect,$parameters = array()){
		global $conf;
		$logs = '';



		if( in_array($parameters['workflow']['type'] , array( Workflow::TYPE_ENTITY, Workflow::TYPE_LIST))  ){
			if(isset($parameters['current'])) $parameters['current'] = $parameters['current']->toArray();
			if(isset($parameters['old'])) $parameters['old'] = $parameters['old']->toArray();
		}
		$effect->values['title'] = isset($effect->values['title']) ? template($effect->values['title'],$parameters,true) : '';
		$effect->values['message'] =isset($effect->values['message']) ? template($effect->values['message'],$parameters,true): '';

		try{
			$logs = 'Pour '.$effect->values['recipient'].': '.$effect->values['title'];
			Plugin::callHook('emit_notification',array(array(
				'label' => $effect->values['title'],
				'html' => wysiwyg_filter(html_entity_decode($effect->values['message'])),
				'pinned' => 0,
				'type' => 'notice',
				'recipients' => array($effect->values['recipient'])
			)));


		}catch(Exception $e){
			$logs .= '<span  class="text-danger"><br>Erreur : '.$e->getMessage().'</span>';
		}
		return $logs;
	}
}

?>