<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Site\Order\ContactType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\ReCaptcha;
use CpCreation\VitiCore\Contact\Model\Contact;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use CpCreation\VitiCore\Depot\Repository\CategoryRepository;
use CpCreation\VitiCore\Event\Repository\EventRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Contracts\Translation\TranslatorInterface;

final class ContactController extends AbstractController
{
    public function __construct(
        private ContactRepository $contactRepository,
        private ReCaptcha $reCaptcha,
        private TranslatorInterface $translator,
        private MailerInterface $mailer,
        private CategoryRepository $categoryRepository,
        private EventRepository $eventRepository,
    ) {
    }

    /**
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function index(Request $request): Response|RedirectResponse
    {
        $categories = $this->categoryRepository->findCategories();
        $salons = $this->eventRepository->findBy(['disabled' => false], ['beginAt' => 'ASC']);

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();

        $recaptchaKeyPublic = $contact->isRecaptcha()
            ? $contact->getRecaptchaKeyPublic()
            : false;

        $form = $this->createForm(ContactType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();

            if ($contact->isRecaptcha() && !$this->reCaptcha->verify($request->get('g-recaptcha-response'))) {
                $this->addFlash('error', $this->translator->trans('contact.form.recaptcha.error'));

                return $this->render('contact.html.twig', [
                    'categories' => $categories,
                    'salons' => $salons,
                    'contact' => $contact,
                    'classMenu' => 'black',
                    'reCaptchaKeyPublic' => $recaptchaKeyPublic,
                    'form' => $form->createView(),
                ]);
            }

            $subject = 'Prise de contact depuis le site '.$contact->getCompany();

            $html = \sprintf(
                'Nom : %s<br/>Téléphone : %s<br/>E-mail : %s<br/>Message : %s<br/>',
                $data['lastname'],
                $data['phone'],
                $data['email'],
                $data['message'],
            );

            $text = \sprintf(
                'Nom : %s Téléphone : %s E-mail : %s Message : %s %s',
                $data['lastname'],
                $data['phone'],
                $data['email'],
                $data['message'],
                $contact->getCompany(),
            );

            $email = (new Email())
                ->subject($subject)
                ->from(new Address($contact->getEmailFrom(), $contact->getCompany()))
                ->to($contact->getEmailToMessage())
                ->replyTo(new Address($data['email'], $data['lastname']))
                ->html($html)
                ->text($text);

            try {
                $this->mailer->send($email);

                $this->addFlash('success', $this->translator->trans('contact.form.success'));

                return $this->redirectToRoute('contact', ['contactSuccess' => 1]);
            } catch (\Throwable) {
                $this->addFlash('error', $this->translator->trans('contact.form.error'));
            }
        }

        return $this->render('contact.html.twig', [
            'categories' => $categories,
            'salons' => $salons,
            'contact' => $contact,
            'classMenu' => 'black',
            'reCaptchaKeyPublic' => $recaptchaKeyPublic,
            'form' => $form->createView(),
        ]);
    }
}
