<?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();

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

            $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)
    {
        $subject = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NAME_SMALL) . ' : Contact';
        $mail = (new \Swift_Message($subject))
            ->setFrom($from)
            ->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);
    }
}
