<?php

namespace App\Controller;

use App\Entity\GlobalParameter;
use App\Form\Type\ContactFormType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;

class ContactController extends AbstractController
{
    private $em;
    private $mailer;
    private $templating;

    public function __construct(EntityManagerInterface $em, \Swift_Mailer $mailer, Environment $templating)
    {
        $this->em = $em;
        $this->mailer = $mailer;
        $this->templating = $templating;
    }

    /**
     * @Route("/contact", name="contact")
     */
    public function contactAction(Request $request)
    {
        $form = $this->createForm(ContactFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $name = $form['nom']->getData();
            $emailFrom = $form['email']->getData();
            $message = $form['message']->getData();
            $senderTypeAsSubjectSuffix = '';
            if ($this->getParameter('tav_env') && $this->getParameter('presta_self_init_and_eval')) {
                switch ($form['type']) {
                    case 'prestataire_candidate':
                        $senderTypeAsSubjectSuffix = " d'un point de vente candidat";
                        break;
                    case 'adherent':
                        $senderTypeAsSubjectSuffix = " d'un adhérent";
                        break;
                }
            }

            $this->sendMail($name, $emailFrom, $message, $senderTypeAsSubjectSuffix);

            $this->addFlash(
                'success',
                'Merci ! Le message a bien été envoyé !'
            );
            $referer = $request->headers->get('referer');
            if ($referer && !$request->isXmlHttpRequest()) {
                return $this->redirect($referer);
            } elseif (!$request->isXmlHttpRequest()) {
                return new Response('', Response::HTTP_BAD_REQUEST);
            }
        }

        return $this->render('@kohinos/contact.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    private function sendMail($name, $from, $message, $senderTypeAsSubjectSuffix = '')
    {
        $subject = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NAME_SMALL) . ' : Contact' . $senderTypeAsSubjectSuffix;
        $mail = (new \Swift_Message($subject))
            ->setFrom($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NOTIF_EMAIL)) //using $from here sometimes fails with 550 5.7.1 Sender mismatch
            ->setTo($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_CONTACT_EMAIL))
            ->setBody(
                $this->templating->render(
                    '@kohinos/email/contact.html.twig',
                    [
                        'subject' => $subject,
                        'from' => $from,
                        'name' => $name,
                        'message' => $message,
                    ]
                ),
                'text/html'
            );
        $this->mailer->send($mail);
    }
}
