<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\Notify\Helper;

use Apps\Notify\Entity\NotifyTemplate;
use Core\Entity\User\User;

class MessageHelper{

    /***
     * Envoi un message 
     */
    public static function SendMessage($core, $code, $email, $params, $subject, $message){

        //Get the Template
        $template = MessageHelper::GetTemplate($core, $code);
        
        //On prend le template de l'utilsateur
        if($template != null) {
            $subject = $template->Title->Value;
            $message =  $template->Content->Value;

            //Todo remplacer les variables par Exemple {sender} => jerome oliva
            //Todo remplacer les variables par Exemple {to} => Pierre déchamp ...
        } 

        foreach($params as $key => $value){
            $message  = str_replace($key, $value, $message);
        }
        
        //Destinataire 
       /* $destinataire = new User($core);
        $destinataire->GetById($destinataireId);
        */
        
        //Send Email
        MessageHelper::SendMail($core, $email, $subject, $message);
 }

    /***
     * Get the Html Template to the Code
     * Verify in the NotifyTemplate
     */
    public static function GetTemplate($core, $code){

        $template = new NotifyTemplate($core);
        $template = $template->GetByCode($code);

        return $template;
    }

    /***
     * Send email by Smtp or by EmailPlugin
     */
    public static function SendMail($core, $email, $subject, $message){

        $emailPlugin = \Apps\EeApp\Helper\AppHelper::GetPluginType($core, "Notify", "Email");

        if($emailPlugin) {
            $emailPlugin->SendMail($email, $subject, $message);
        } else {
            EmailHelper::SendMail($core, $email, $subject, $message);
        }
    }
}