<?php

namespace App\Controller\Frontend;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

use Symfony\Component\Routing\Attribute\Route;

use Symfony\Bundle\SecurityBundle\Security;

use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;

use App\Security\LoginAuthenticator;

use Doctrine\ORM\EntityManagerInterface;

use App\Entity\User;

use App\Form\UserRegistrationType;

use Symfony\Contracts\Translation\TranslatorInterface;

final class SecurityController extends AbstractController
{
    #[Route(path: '/login', name: 'security_login')]
    public function login(TranslatorInterface $translator, AuthenticationUtils $authenticationUtils): Response
    {
        if ($this->getUser()) {
            return $this->redirectToRoute('app_frontend_home');
        }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('frontend/login.html.twig', ['last_username' => $lastUsername, 'error' => $error, 'titlePage' => 'Connexion']);
    }

    #[Route(path: '/logout', name: 'security_logout')]
    public function logout(Security $security): RedirectResponse
    {
        $response = $security->logout(false);

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

    #[Route(path: '/registration', name: 'security_registration')]
    public function registration(
        Request $request,
        UserPasswordHasherInterface $userPasswordHasher,
        UserAuthenticatorInterface $userAuthenticator,
        LoginAuthenticator $authenticator,
        EntityManagerInterface $em
    ): Response {
        $user = new User();

        $form = $this->createForm(UserRegistrationType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->setPassword($userPasswordHasher->hashPassword($user, $form->get('password')->getData()));

            $em->persist($user);
            $em->flush();

            return $userAuthenticator->authenticateUser($user, $authenticator, $request);
        }

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

    #[Route('/change-language', name: 'change_language')]
    public function change_language(Request $request): RedirectResponse
    {
        $language = $request->query->get('lang');

        // Stocker la langue dans la session
        $request->getSession()->set('_locale', $language);

        $request->setLocale($language);

        // Rediriger vers la page précédente ou l'accueil
        $referer = $request->headers->get('referer');

        return $this->redirect($referer);
    }
}
