<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Controller\Fragment;

use Ferienpass\CmsBundle\Form\SimpleType\ContaoRequestTokenType;
use Ferienpass\CoreBundle\Controller\AbstractPrivateFragmentController;
use Ferienpass\CoreBundle\Message\DeleteUserAccount;
use Ferienpass\CoreBundle\Message\UnblockEmail;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;

class AccountUnsubscribedController extends AbstractPrivateFragmentController
{
    public function __construct(private readonly MessageBusInterface $commandBus)
    {
    }

    public function __invoke(Request $request): Response
    {
        $form = $this->createFormBuilder()
            ->add('requestToken', ContaoRequestTokenType::class)
            ->add('unblock', SubmitType::class, ['label' => 'Zu den E-Mails wieder anmelden'])
            ->add('delete', SubmitType::class, ['label' => 'Meinen Account löschen'])
            ->getForm()
        ;

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            if ($form->get('unblock')->isClicked()) {
                $this->commandBus->dispatch(new UnblockEmail($request->query->get('email', ''), $request->query->get('uuid')));

                return $this->redirect('/');
            }

            if ($form->get('delete')->isClicked()) {
                $this->commandBus->dispatch(new DeleteUserAccount($request->query->get('uuid')));

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

        return $this->render('@Contao/fragment/account_unsubscribed.html.twig', [
            'email' => $request->query->get('email'),
            'unsubscribed' => new \DateTimeImmutable($request->query->get('unsubscribed') ?? 'now'),
            'actions' => $form,
        ]);
    }
}
