<?php
/*
	Effet de workflow
	Envois un mail a une ou plusieurs adresses
*/
class MailEffect{

	//Descriptif du type d'effet
	public static function manifest($key = null){
		$manifest = array(
			'slug' => 'mail',
			'label' => 'Envoyer un e-mail',
			'class' => get_called_class(),
			'path' => __FILE__,
			'icon' => 'fas fa-envelope-open-text',
			'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();


		ob_start();
		?>

		<div class="input-group">
			<div class="input-group-text input-group-prepend">
			Pour  :
			</div>
			<input type="text" data-id="to" class="form-control" value="<?php echo isset($item['to']) ? $item['to'] : '' ?>" placeholder="jdoe@doe.com, jmith@smithcorp.com">
		</div>
		<div class="input-group mt-2">
			<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>
		<?php
		$html = ob_get_clean();
		return $html;
	}

	public static function run($effect,$parameters = array()){
		global $conf;
		$logs =  '';
		try{
			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'] = template($effect->values['title'],$parameters,true);
			$effect->values['message'] = template($effect->values['message'],$parameters,true);


			$expeditor = $conf->get('workflow_mail_from') != '' ? $conf->get('workflow_mail_from'): PROGRAM_NAME.' <workflow@'.PROGRAM_NAME.'.fr>';
			$reply = $conf->get('workflow_mail_reply') != '' ? $conf->get('workflow_mail_reply'): $expeditor;
			$mail = new Mail();
			$mail->expeditor = $expeditor;
			$mail->reply = $reply;
			$mail->title = $effect->values['title'];
			$mail->message = html_entity_decode($effect->values['message']);
			$mail->recipients['to'][]  =  $effect->values['to'];
			$logs = 'Sujet: "'.$mail->title.'" pour '.implode($mail->recipients['to']);
			$mail->send();

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

?>