<?php

namespace App\Controller;

use App\Service\MailerService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class ContactController extends AbstractController
{
    #[Route('/contact', name: 'app_contact', methods: ['GET', 'POST'])]
    public function index(Request $request, MailerService $mailerService): Response
    {
        if ($request->isMethod('POST')) {
            $name = trim($request->request->getString('name'));
            $surname = trim($request->request->getString('surname'));
            $email = trim($request->request->getString('email'));
            $message = trim($request->request->getString('message'));

            if ('' === $name || '' === $surname || '' === $email || '' === $message) {
                $this->addFlash('error', 'Tous les champs sont obligatoires.');

                return $this->redirectToRoute('app_contact');
            }

            $html = $this->renderView('email/contact.html.twig', [
                'name' => $name,
                'surname' => $surname,
                'email' => $email,
                'message' => $message,
            ]);

            $mailerService->sendEmail(
                to: $this->getParameter('admin_email'),
                subject: sprintf('Contact de %s %s', $surname, $name),
                content: $html,
                replyTo: $email,
                withUnsubscribe: false,
            );

            $this->addFlash('success', 'Votre message a bien ete envoye. Nous vous repondrons dans les plus brefs delais.');

            return $this->redirectToRoute('app_contact');
        }

        return $this->render('contact/index.html.twig', [
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Contact', 'url' => '/contact'],
            ],
        ]);
    }
}
