<?php
namespace App\Controller\Front;
use App\Entity\{ContactPage, Contact, User};
use App\Form\{ContactType};
use App\Service\AccessClientService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use DateTime;
use DateTimeZone;
class ContactController extends AbstractController
{
/**
* @Route("/contact", name="app_front_contact")
*/
public function contact(
AccessClientService $accessClientService,
Request $request,
EntityManagerInterface $entityManager,
MailerInterface $mailer
): Response
{
$accessClientService->handleAccessControl();
$contactPage = $entityManager->getRepository(ContactPage::class)->find(1);
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$emailUser = $form->getData('email');
$user = $entityManager->getRepository(User::class)->findOneBy(['email' => $emailUser]);
if ($user) {
$userName = $user->getFirstname() . ' ' .$user->getLastname();
$userPhoto = $user->getAvatar();
} else {
$userName = null;
$userPhoto = null;
}
$contact->setStatus(Contact::RECEIVED);
$timezone = new DateTimeZone('Europe/Paris');
$createdAt = new DateTime('now', $timezone);
$contact->setCreatedAt($createdAt);
$entityManager->persist($contact);
$entityManager->flush();
$email = (new Email())
->from($contact->getEmail())
->to('rabemanantsaina29@gmail.com')
->subject('Nouveau message de contact depuis RYVUP')
->html($this->renderView('emails/contact.html.twig', [
'contact' => $contact,
'userName' => $userName,
'userPhoto' => $userPhoto,
'messageUrl' => $this->generateUrl('app_admin_email_inbox', [], UrlGeneratorInterface::ABSOLUTE_URL)
]));
$mailer->send($email);
$this->addFlash('success', "Succès ! Votre message a bien été envoyé.");
return $this->redirectToRoute('app_front_contact');
}
return $this->render('front/contact/contact.html.twig', [
'contactPage' => $contactPage,
'form' => $form->createView()
]);
}
}