<?php

namespace App\Controller;

use App\Entity\OrganizerInvitation;
use App\Service\MailerService;
use App\Service\UnsubscribeManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class UnsubscribeController extends AbstractController
{
    #[Route('/unsubscribe/{token}', name: 'app_unsubscribe', methods: ['GET', 'POST'])]
    public function __invoke(Request $request, string $token, UnsubscribeManager $unsubscribeManager, EntityManagerInterface $em, MailerService $mailerService): Response
    {
        $email = base64_decode($token, true);

        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw $this->createNotFoundException();
        }

        if ($request->isMethod('POST')) {
            $unsubscribeManager->unsubscribe($email);

            $invitations = $em->getRepository(OrganizerInvitation::class)->findBy(['email' => $email]);
            foreach ($invitations as $invitation) {
                $invitation->setStatus(OrganizerInvitation::STATUS_REFUSED);
                $invitation->setRespondedAt(new \DateTimeImmutable());
            }
            $em->flush();

            if (\count($invitations) > 0) {
                $mailerService->sendEmail(
                    $this->getParameter('admin_email'),
                    'Desinscription invitation organisateur - '.$email,
                    '<p>'.$email.' s\'est desinscrit et avait '.\count($invitations).' invitation(s) en cours. Elles ont ete automatiquement refusees.</p>',
                    null,
                    null,
                    false,
                );
            }

            return $this->render('unsubscribe/confirmed.html.twig', [
                'email' => $email,
                'breadcrumbs' => [
                    ['name' => 'Accueil', 'url' => '/'],
                    ['name' => 'Desinscription', 'url' => '/unsubscribe/'.$token],
                ],
            ]);
        }

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