<?php

namespace App\Controller;

use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ResettingController extends AbstractController
{
    private $userManager;
    private $formFactory;
    private $dispatcher;

    public function __construct(UserManagerInterface $userManager, FactoryInterface $formFactory, EventDispatcherInterface $dispatcher)
    {
        $this->userManager = $userManager;
        $this->formFactory = $formFactory;
        $this->dispatcher = $dispatcher;
    }

    /**
     * Create a custom ResettingController for the reset password action.
     * This is done to prevent automatic activation of user after changing password,
     * in case the admin created the account disabled.
     * 
     * @Route("/resetting/reset/{token}", name="fos_user_resetting_reset")
     */
    public function resetAction(Request $request, string $token)
    {
        $user = $this->userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            throw $this->createNotFoundException(sprintf('L’utilisateur avec le token %s n’existe pas.', $token));
        }

        $form = $this->formFactory->createForm();
        $form->setData($user);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Save enabled state
            $wasEnabled = $user->isEnabled();

            $event = new FormEvent($form, $request);
            $this->dispatcher->dispatch($event, FOSUserEvents::RESETTING_RESET_SUCCESS);

            $user->setConfirmationToken(null);
            $user->setPasswordRequestedAt(null);

            $this->userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $response = new RedirectResponse($this->generateUrl('fos_user_profile_show'));
            }

            // Re-set original "enabled" state
            if ($user->isEnabled() !== $wasEnabled) {
                $user->setEnabled($wasEnabled);
                $this->userManager->updateUser($user);
            }

            $this->dispatcher->dispatch(
                new FilterUserResponseEvent($user, $request, $response),
                FOSUserEvents::RESETTING_RESET_COMPLETED
            );

            return $response;
        }

        return $this->render('@FOSUser/Resetting/reset.html.twig', [
            'token' => $token,
            'form' => $form->createView(),
        ]);
    }
}
