<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Service\SendEmail;
use DateInterval;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;

class RegistrationController extends AbstractController
{


    /**
     * @Route("/register", name="app_register")
     * @throws TransportExceptionInterface
     **/
    public function register(Request $request,
                             SendEmail $sendEmail,
                             UserPasswordHasherInterface $userPasswordHasherInterface,
                             TokenGeneratorInterface $tokenGenerator): Response
    {
        $user = new User();
        $form = $this->createForm(RegistrationFormType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $registrationToken= $tokenGenerator->generateToken();
            $di = new DateTimeImmutable("now");
            $di = $di->add(new DateInterval('P1D')); // $di now changed
            $user   ->setRegistrationToken( $registrationToken)
                    ->setPassword( // encode the plain password
                        $userPasswordHasherInterface->hashPassword(
                            $user,
                            $form->get('password')->getData()
                        )
                    )
                    ->setAccountMustBeVerifiedBefore($di);


            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            // do anything else you need here, like send an email
            $subject="Vérification de votre email pour activer votre compte utilisateur";
            $sendEmail->send([
                'recipient_email'   =>  $user->getEmail(),
                'subject'           =>  $subject,
                'html_template'     =>  "registration/register_confirmation_email.html.twig",
                'context'           =>  [
                    'userId'            =>  $user->getId(),
                    'registrationToken' =>  $registrationToken,
                    'tokenLifeTime'     =>  $user->getAccountMustBeVerifiedBefore()->format('d/m/Y à H:i')
                ]
            ]);

            $this->addFlash('success',"Votre compte utlisateur a bien été créé,
                            vérifiez votre messagerie pour l'activer");
            return $this->redirectToRoute('app_login');
        }

        return $this->render('registration/register.html.twig', [
            'registrationForm' => $form->createView(),
        ]);
    }


    /**
     * @Route("/{id}/{token}", name="app_verify_account", methods={"GET"})
     * @param EntityManagerInterface $entityManager
     * @param User $user
     * @param string $token
     * @return Response
     */
   public function verifyUserAccount(
       // see paramsconverter for </d+>
        EntityManagerInterface $entityManager,
        User $user,
        string $token):Response
    {
        if (($user->getRegistrationToken() === null) ||
            ($user->getRegistrationToken() !== $token) ||
            ($this->isNotRequestedinTime($user->getAccountMustBeVerifiedBefore()))) {
            throw new AccessDeniedException();
        }
        $user->setIsVerified(true);
        $user->setAccountVerifiedAt(new \DateTimeImmutable('now'));
        $user->setRegistrationToken(null);
        $entityManager->flush();

        $this->addFlash('success', "Votre compte utilisateur est à présent,
                    vous pouvez dés à présent vous connecter");
        return $this->redirectToRoute('app_login');
    }
    private function isNotRequestedinTime(?\DateTimeImmutable $accountMustBeVerifiedBefore): bool
    {
        return (new \DateTimeImmutable()>$accountMustBeVerifiedBefore);
    }


}
