<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 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\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ReviewRequestConfigurationType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Mailer\ReviewInvitationMailer;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use CpCreation\VitiCore\Marketing\Model\ReviewRequestConfiguration;
use CpCreation\VitiCore\Marketing\Repository\ReviewRequestConfigurationRepository;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Translation\TranslatorInterface;

#[Route('/marketing/relances-avis')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN') or is_granted('ROLE_MARKETING')"))]
final class ReviewRequestController extends AbstractController
{
    public function __construct(
        private readonly ReviewRequestConfigurationRepository $configurationRepository,
        private readonly ContactRepository $contactRepository,
        private readonly ReviewInvitationMailer $mailer,
        private readonly TranslatorInterface $translator,
        private readonly LoggerInterface $logger,
    ) {}

    #[Route('', name: 'admin_marketing_review_request', methods: ['GET', 'POST'])]
    public function index(Request $request): Response
    {
        $configuration = $this->configurationRepository->findOne() ?? new ReviewRequestConfiguration();
        $form = $this->createForm(ReviewRequestConfigurationType::class, $configuration);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var ReviewRequestConfiguration $configuration */
            $configuration = $form->getData();
            $this->configurationRepository->save($configuration);
            $this->addFlash('alert-success', $this->translator->trans('marketing.review_request.configuration.saved'));

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

        return $this->render('@CpCreationVitiCore/admin/marketing/review_request/index.html.twig', [
            'configuration' => $configuration,
            'form' => $form->createView(),
            'test_email_recipient' => $this->contactRepository->findOne()?->getEmailToMessage() ?? '',
        ]);
    }

    #[Route('/email-test', name: 'admin_marketing_review_request_test_email', methods: ['POST'])]
    public function sendTestEmail(Request $request): Response
    {
        if (!$this->isCsrfTokenValid('marketing-review-request-test-email', $request->request->getString('_token'))) {
            throw $this->createAccessDeniedException();
        }

        $recipientEmail = mb_trim($request->request->getString('email'));
        if (false === filter_var($recipientEmail, \FILTER_VALIDATE_EMAIL)) {
            $this->addFlash('alert-danger', $this->translator->trans('marketing.test_email.invalid'));

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

        try {
            $this->mailer->sendTest(
                $recipientEmail,
                $this->configurationRepository->findOne() ?? new ReviewRequestConfiguration(),
            );
            $this->addFlash('alert-success', $this->translator->trans(
                'marketing.test_email.sent',
                ['%email%' => $recipientEmail],
            ));
        } catch (\Throwable $exception) {
            $this->logger->error('Échec de l’envoi d’un email de test de demande d’avis.', [
                'exception' => $exception,
                'recipient' => $recipientEmail,
            ]);
            $this->addFlash('alert-danger', $this->translator->trans('marketing.test_email.failed'));
        }

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