<?php

namespace App\Controller;

use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;

class SetPasswordController extends AbstractController
{
    #[Route('/set-password/{token}', name: 'app_set_password', methods: ['GET', 'POST'])]
    public function index(
        string $token,
        Request $request,
        UserRepository $userRepository,
        UserPasswordHasherInterface $passwordHasher,
        EntityManagerInterface $em,
    ): Response {
        $user = $userRepository->findOneBy(['tempPassword' => $token]);

        if (null === $user) {
            return $this->render('security/set_password_expired.html.twig');
        }

        $error = null;

        if ('POST' === $request->getMethod()) {
            $password = $request->request->getString('password');
            $passwordConfirm = $request->request->getString('password_confirm');

            if (\strlen($password) < 8) {
                $error = 'Le mot de passe doit contenir au moins 8 caracteres.';
            } elseif ($password !== $passwordConfirm) {
                $error = 'Les mots de passe ne correspondent pas.';
            } else {
                $user->setPassword($passwordHasher->hashPassword($user, $password));
                $user->clearTempPassword();
                $em->flush();

                $this->addFlash('success', 'Votre mot de passe a ete defini. Vous pouvez maintenant vous connecter.');

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

        return $this->render('security/set_password.html.twig', [
            'user' => $user,
            'error' => $error,
        ]);
    }
}
