<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\UserType;
use App\Form\User2Type;
use App\Repository\UserRepository;
use App\Repository\ExpertRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="app_login")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        // if ($this->getUser()) {
        //     return $this->redirectToRoute('target_path');
        // }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error, 'error2' => '', 'success' => '']);
    }

    /**
     * @Route("/register", name="register", methods={"GET", "POST"})
     */
    public function new(UserPasswordHasherInterface $passwordHasher, Request $request, UserRepository $userRepository): Response
    {
        $user = new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $users = $userRepository->findByUsername($user->getUsername());
            $error = "";
            if ($user->getPassword() != $form['password2']->getData())
                $error = "Error: Les mots de passe ne correspondent pas!";
            if (count($users) > 0)    $error = "Erreur: cet utilisateur existe déjà dans la base!";
            if ($error != "")       return $this->render('user/new.html.twig', ['user' => $user, 'form' => $form->createView(), 'error' => $error]);
            $hashedPassword = $passwordHasher->hashPassword(
                $user,
                $user->getPassword()
            );
            $user->setPassword($hashedPassword);
            $user->setRoles(array('ROLE_USER'));
            $userRepository->add($user, true);
            $this->addFlash('success', 'Votre compte a bien été créé!');
            return $this->redirectToRoute('accueil');
        }

        return $this->renderForm('user/new.html.twig', [
            'user' => $user,
            'form' => $form,
            'error' => '',
        ]);
    }

    /**
     * @Route("/password-reset", name="password_reset", methods={"GET", "POST"})
     */
    public function passwordReset(UserPasswordHasherInterface $passwordHasher, Request $request, UserRepository $userRepository): Response
    {
        $user2 = new User();
        $form = $this->createForm(User2Type::class, $user2);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $userRepository->findOneBy([
                "username" => $user2->getUsername(),
                "email" => $user2->getEmail()]
            );
            $error = "";
            if ($user2->getPassword() != $form['password2']->getData())
                $error = "Error: Les mots de passe ne correspondent pas!";
            if ($user == null)  $error = "Error: Utilisateur invalide!";
            if ($error != "")       return $this->render('user/password-reset.html.twig', ['user' => $user2, 'form' => $form->createView(), 'error' => $error]);
            $hashedPassword = $passwordHasher->hashPassword(
                $user,
                $user2->getPassword()
            );
            $user->setPassword($hashedPassword);
            $userRepository->add($user, true);
            $this->addFlash('success', 'Votre mot de passe a bien été modifié!');
            return $this->redirectToRoute('accueil');
        }

        return $this->renderForm('user/password-reset.html.twig', [
            'user' => $user2,
            'form' => $form,
            'error' => '',
        ]);
    }

    /**
     * @Route("/logout", name="app_logout")
     */
    public function logout(): void
    {
        throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
    }
}