<?php
 
namespace App\Service;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class MailService
{
    protected $mailer;
    protected $twig;
 
    public function __construct(MailerInterface $mailer, \Twig\Environment $twig)
    {
        $this->mailer = $mailer;
        $this->twig = $twig;
    }
 
    /**
     * Send email
     *
     * @param   string   $template      email template
     * @param   mixed    $parameters    custom params for template
     * @param   string   $to            to email address or array of email addresses
     * @param   string   $from          from email address
     * @param   string   $fromName      from name
     *
     * @return  boolean                 send status
     */
    public function sendEmail($subject, $body, $to, $from, $fromName = null)
    {
        // Aucun destinataire ou expéditeur pas de mail
        if(empty($to)||empty($from)) return true;


        $template = $this->twig->load('Include\mail.html.twig');
        $parameters=["subject"=>$subject,"body"=>$body];
        $subject  = $template->renderBlock('subject', $parameters);
        $bodyHtml = $template->renderBlock('body', $parameters);
        
        try {
            $message = (new Email())
                    ->from($from)
                    ->subject($subject)
                    ->from(Address::create($fromName. "<".$from.">"))
                    ->html($bodyHtml);
            
            if(is_array($to)) $message->to(...$to);
            else $message->to($to);
            
            $response = $this->mailer->send($message);
 
        } catch (TransportExceptionInterface $e) {
            return $e->getMessage();
        }

        return $response;
    }
}