<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\Entity\User;
use App\Form\RegistrationFormType;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
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]);
}
/**
* @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.');
}
/**
* @Route("/forgot-password", name="app_forgot_password")
*/
public function forgotPassword(): Response
{
// Aquí iría la lógica para enviar email de recuperación
return $this->render('security/forgot_password.html.twig');
}
/**
* @Route("/register", name="app_register")
*/
public function register(
Request $request,
UserPasswordHasherInterface $passwordHasher,
EntityManagerInterface $entityManager
): Response {
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Rol por defecto para nuevos registros públicos
$user->setRoles(['ROLE_CLIENT']);
// Hash de la contraseña
$hashedPassword = $passwordHasher->hashPassword(
$user,
$user->getPlainPassword()
);
$user->setPassword($hashedPassword);
try {
// Buscar al admin por rol
$admin = $entityManager->getRepository(User::class)
->createQueryBuilder('u')
->andWhere('u.roles LIKE :role')
->setParameter('role', '%"ROLE_ADMIN"%')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
if ($admin) {
// Relación ManyToMany: asignar el paciente al admin
$admin->addPatient($user);
$entityManager->persist($admin);
}
// Guardar usuario
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', 'Cuenta creada correctamente.');
return $this->redirectToRoute('app_login');
} catch (UniqueConstraintViolationException $e) {
$this->addFlash('error', 'Ya existe una cuenta con este correo electrónico.');
}
}
return $this->render('security/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
}