<?php
/**
 * Email Sender
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Email;

use Swift_Mailer;
use Swift_Message;
use VisualM\FormBundle\Entity\FormEntry;

use Swift_Attachment;
/**
 * Email Sender
 * 
 * @author Elze Kool <info@visualmedia.nl>
 */
class EmailSender
{

    /**
     * Mailer
     * @var Swift_Mailer
     */
    private $mailer;

    /**
     * Sender e-mailadres
     * @var string
     */
    private $sender;

    /**
     * Constructor
     *
     * @param Swift_Mailer $mailer Mailer
     * @param string       $sender Sender e-mailadres
     */
    public function __construct(Swift_Mailer $mailer, $sender)
    {
        $this->mailer = $mailer;
        $this->sender = $sender;
    }

    /**
     * Send E-mails for Form Entry
     *
     * @param FormEntry $entry Form Entity
     */
    public function sendEmails(FormEntry $entry)
    {
        $form = $entry->getForm();
       
        $this->sendEmail($entry);

        // Check if we have to send a kopie
        if ($form->getKopieNaarAfzender()) {
            $this->sendKopieEmail($entry);
        }
    }

    /**
     * Send E-mail
     *
     * @param FormEntry $entry Entry
     */
    protected function sendEmail(FormEntry $entry)
    {
        $form = $entry->getForm();
        $emailHtml = $entry->getEmailHtml();
        $data = $entry->getRawdata();

        // Create Message
        $message = $this->mailer->createMessage();
        /* @var $message Swift_Message */

        $message
            ->setSender($this->sender)
            ->setSubject($this->replaceControlValues($form->getEmailOnderwerp(), $data))

            ->addTo(
                $this->replaceControlValues($form->getOntvangerEmail(), $data),
                $this->replaceControlValues($form->getOntvangerNaam(), $data)
            )

            ->setFrom(
                $this->replaceControlValues($form->getAfzenderEmail(), $data),
                $this->replaceControlValues($form->getAfzenderNaam(), $data)
            )

            ->setBody($emailHtml, 'text/html');
        
        foreach ($form->getFields()->getValues()as $field) {
            if ($field->getType() == 'file') {
                $referentie = $field->getReferentie();
                $filename = $data[$referentie];

                if (!empty($filename)){
                    $message->attach(Swift_Attachment::fromPath('userfiles/form/uploads/'. $filename));
                }
            }
        }
    
        if ($form->getBccEmail() != '' AND $form->getBccEmail() != null) {
            foreach(explode(';', $form->getBccEmail()) as $bcc) {
                $message->addBcc(trim($bcc));
            }
        }

        $this->mailer->send($message);
    }

    /**
     * Send kopie E-mail
     *
     * @param FormEntry $entry Entry
     */
    protected function sendKopieEmail(FormEntry $entry)
    {
        $form = $entry->getForm();
        $html = $entry->getKopieEmailHtml();
        $data = $entry->getRawdata();
        
        $message = $this->mailer->createMessage()
            ->setSender($this->sender)
            ->setSubject(
                $this->replaceControlValues(
                    (
                        $form->getKopieEmailOnderwerp() != ''
                            ? $form->getKopieEmailOnderwerp()
                            : $form->getEmailOnderwerp()
                    ),
                    $data
                )
            )
            ->addTo($this->replaceControlValues(
                $form->getAfzenderEmail(), $data),
                $this->replaceControlValues($form->getAfzenderNaam(), $data)
            )

            ->setFrom(
                $this->replaceControlValues($form->getOntvangerEmail(), $data),
                $this->replaceControlValues($form->getOntvangerNaam(), $data)
            )

            ->setBody($html, 'text/html');
      
        foreach ($form->getFields()->getValues()as $field) {
            if ($field->getType() == 'file') {
                
                $referentie = $field->getReferentie();
                $filename = $data[$referentie];
              
                if (!empty($filename)){
                    $message->attach(Swift_Attachment::fromPath('userfiles/form/uploads/'. $filename));
                }
            }
        }

        $this->mailer->send($message);
    }



    /**
     * Replace {Control:name} values in string
     *
     * @param string        $string Input string
     * @param array<string> $data   Data from Form
     *
     * @return string String with replacements
     */
    protected function replaceControlValues($string, $data)
    {
        $replacements = [];
        foreach($data as $key => $value) {
            if (!is_array($value)) {
                $replacements[sprintf('{control:%s}', $key)] = $value;
            }
        }
        return str_replace(array_keys($replacements), array_values($replacements), $string);
    }


}