<?php

namespace App\Controller\Frontend;

use App\Controller\AbstractController;
use App\Form\ContactForm;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\HttpFoundation\Request;

class ContactController extends AbstractController
{
    public function contact()
    {
        $form = $this->createForm(ContactForm::class, null, array(
            'action' => $this->generateUrl('app_contact_form')
        ));

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

    public function contactForm(Request $request, MailerInterface $mailer)
    {
        $form = $this->createForm(ContactForm::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid() && $form->get('lccap')->getData() == 'blop') {
            $message = '<p>De : ' . $form->get('firstname')->getData() . ' ' . $form->get('lastname')->getData() . '<br />Email : ' . $form->get('email')->getData(
                ) . '<br />Objet : ' . $form->get(
                    'object'
                )->getData() . '</p><p>' . $form->get('message')->getData() . '</p>';

            $email = (new Email())
                ->from('nepasrepondre@laclic.fr')
                ->replyTo($form->get('email')->getData())
                ->to('agir@lacooperativedescitoyens.fr')
//                ->to('charly@laclic.fr')
                ->subject('Message de contact sur Aux Actes Citoyens !')
                ->text(strip_tags($message))
                ->html($message);

            $mailer->send($email);

            return new JsonResponse(
                [
                    'status' => 'success'
                ]
            );
        }
        return new JsonResponse(
            [
                'status' => 'error'
            ]
        );
    }

}