<?php

namespace App\Controller;

use App\Entity\Account;
use App\Entity\AccountResetPasswordRequest;
use App\Entity\Sub;
use App\Form\RequestPasswordConfirmType;
use App\Form\RequestPasswordRequestType;
use App\Repository\SubRepository;
use App\Service\ResetPassword\Event\ResetPasswordConfirmEvent;
use App\Service\ResetPassword\Event\ResetPasswordEvent;
use Doctrine\ORM\EntityManagerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Twig\Environment;

class SecurityController extends AbstractController
{

    #[Route(path: '/notificationSub', name: 'app_notificationSub', options: ['sitemap' => false], methods: ['POST'])]
    public function notificationSub(Request $request,SubRepository $subRepository,EntityManagerInterface $entityManager): Response
    {
        $content = json_decode($request->getContent(),true);

        $sub = $subRepository->findOneBy(['subId'=>$content['subscription']['endpoint']]);
        if(!$sub instanceof Sub){
            $sub = new Sub();
            $sub->setSubId($content['subscription']['endpoint']);
            $sub->setSubcriber($content);
            $entityManager->persist($sub);
        }
        $entityManager->flush();
        return $this->json([]);
    }

    #[Route(path: '/connexion', name: 'app_login', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        if($this->getUser())
            return $this->redirectToRoute('app_home');
        return $this->render('security/login.twig', [
            'last_username' => $authenticationUtils->getLastUsername(),
            'error' => $authenticationUtils->getLastAuthenticationError(),
        ]);
    }
    #[Route(path: '/logout', name: 'app_logout', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function logout(): Response
    {

    }
    #[Route(path: '/mot-de-passe-oublie', name: 'app_forgot_password', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function forgotPassword(Request $request,EventDispatcherInterface $eventDispatcher): Response
    {
        $requestPasswordRequest = new ResetPasswordEvent();
        $form = $this->createForm(RequestPasswordRequestType::class,$requestPasswordRequest);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $eventDispatcher->dispatch($requestPasswordRequest);
           return $this->redirectToRoute('app_forgot_password_sent');
        }
        return $this->render('security/forgot_password.twig', [
            'form' => $form->createView(),
        ]);
    }
    #[Route(path: '/mot-de-passe-oublie/sent', name: 'app_forgot_password_sent', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function forgotPasswordSent(Request $request,EventDispatcherInterface $eventDispatcher): Response
    {
        return $this->render('security/forgot_password_success.twig', [
        ]);
    }
    #[Route(path: '/mot-de-passe-oublie/{id}/{token}', name: 'app_forgot_password_confirm', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function forgotPasswordConfirm(UserPasswordHasherInterface $userPasswordHasher,EventDispatcherInterface $eventDispatcher,Request $request,EntityManagerInterface $entityManager,string $id,string $token): Response
    {
        $errorMessage = "Requête non valide.";
        if (!is_numeric($id)) {
            $this->addFlash("error", $errorMessage);
            return $this->redirectToRoute('app_forgot_password');
        }
        $account = $entityManager->getRepository(Account::class)->find((int)$id);
        if (!$account instanceof Account) {
            $this->addFlash("error", $errorMessage);
            return $this->redirectToRoute('app_forgot_password');
        }
        $requestToken = $entityManager->getRepository(AccountResetPasswordRequest::class)->findOneBy([
            'Account' => $account, // Assurez-vous que 'Account' est le nom correct de la propriété/colonne dans votre entité AccountResetPasswordRequest.
            'token' => $token
        ]);
        if (!$requestToken instanceof AccountResetPasswordRequest) {
            $this->addFlash("error", $errorMessage);
            return $this->redirectToRoute('app_forgot_password');
        }
        $now = new \DateTimeImmutable();
        if ($requestToken->getExpiresAt() < $now) {
            $this->addFlash("error", "Le lien de réinitialisation de mot de passe a expiré.");
            return $this->redirectToRoute('app_forgot_password');
        }

        $event = new ResetPasswordConfirmEvent();
        $form = $this->createForm(RequestPasswordConfirmType::class,$event);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $account->setPassword($userPasswordHasher->hashPassword($account,$event->getPassword()));
            $entityManager->persist($account);
            $entityManager->flush();
            $this->addFlash("success", "Votre mot de passe a été mis à jour avec succès.");
            return $this->redirectToRoute('app_login');
        }
        return $this->render('security/forgot-password-confirm.twig', [
            'form' => $form->createView(),
            'noIndex' => true,
            'id' => $id,
            'token' => $token,
            'account' => $account,
        ]);
    }
}

