<?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, $userId, $code, $destinataireId, $emailSubjet, $emailMessage){

        //Get the Template
        $template = MessageHelper::GetTemplate($core, $code);
        
        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 ...
        } else {
            $subject = $emailSubjet;
            $message = $emailMessage;
        }

        //Destinataire 
        $destinataire = new User($core);
        $destinataire->GetById($destinataireId);
        
        //Send Email
        MessageHelper::SendMail($core, $destinataire->Email->Value, $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);
        }
    }
}