<?php
namespace App\Controller\Frontend\NuevoIngreso;
use App\Entity\NuevoIngreso\Aspirante;
use App\Entity\NuevoIngreso\AspRegistro;
use App\Entity\NuevoIngreso\PlanesOfertados;
use App\Entity\User;
use App\Form\Backend\NuevoIngreso\AspiranteEditarType;
use App\Form\NuevoIngreso\AspiranteType;
use App\Form\NuevoIngreso\BuscaPreregistroCurpType;
use App\Form\NuevoIngreso\BuscaPreregistroType;
use App\Repository\NuevoIngreso\AspiranteRepository;
use App\Repository\NuevoIngreso\AspRegistroRepository;
use App\Repository\NuevoIngreso\PlanesOfertadosRepository;
use App\Service\Mailer\Mailer;
use App\Service\NuevoIngreso\AspiranteService;
use App\Utils\FormErrorsSerializer;
use Doctrine\Persistence\ManagerRegistry;
use Qipsius\TCPDFBundle\Controller\TCPDFController;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\Service\Aspirantes\Multiculturalidad as AspirateService;
/**
* @Route("/public/aspirante")
*/
class AspirantePreregistroController extends AbstractController
{
private $passwordHasher;
//STATUS 1, es para PREREGISTRO, para tomar en cuenta en fechas, etc.
private const STATUS = 1;
/**
* @var ManagerRegistry
*/
private $doctrine;
public function __construct(ManagerRegistry $doctrine, UserPasswordHasherInterface $passwordHasher)
{
$this->doctrine = $doctrine;
$this->passwordHasher = $passwordHasher;
}
/**
* @Route("/new/{id}", name="frontend_aspirante_new", methods={"GET","POST"})
*/
public function new(Request $request, PlanesOfertados $plan, Mailer $mailer, AspirateService $aspiranteService, PlanesOfertadosRepository $planesOfertadosRepository): Response
{
//Checamos si el plan en realidad se encuentra en las fechas de inicio y fin de preregistro, de acuerdo ala fecha/hora actual
if(!$planesOfertadosRepository->findPlanPorFecha($plan, self::STATUS)) {
$this->addFlash('error', 'El plan no se encuentra activo. No lo intente de nuevo.');
return $this->redirectToRoute('frontend_aspirante_nivel', [ 'nivel' => $plan->getNivelPlanEstudios() ]);
}
$aspirante = new Aspirante();
$form = $this->createForm(AspiranteType::class, $aspirante, [
'nivelPlan' => $plan->getNivelPlanEstudios()
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//Access to array collection form to aspRegistro to generate some fields
$data = $form->getData();
//dd($plan->getPeriodoInicioPlan());
foreach ($data->getAspRegistros() as $formAspRegsitro)
{
$formAspRegsitro->setNivelIngresar($plan->getNivelPlanEstudios());
$formAspRegsitro->setPlanOfertado($plan);
$formAspRegsitro->setClaveUnicaRegistro($aspiranteService->getRandomString(8, $plan->getNivelPlanEstudios()));
$formAspRegsitro->setPeriodoIngreso('2023B');
}
$entityManager = $this->doctrine->getManager();
$entityManager->persist($aspirante);
$entityManager->flush();
//$mailer->enviarEmailAspirante($aspirante);
$this->addFlash('success', 'El Registro se guardó correctamente.');
return $this->redirectToRoute('frontend_aspirante_registro_finalizado', [ "id" => $aspirante->getId() ]);
}
return $this->renderForm('frontend/aspirante/new.html.twig', [
'form' => $form,
'planOfertado' => $plan,
'accion' => 'new'
]);
}
/**
* @Route("/registration-finished/{id}", name="frontend_aspirante_registro_finalizado")
*/
public function registroFinalizado(Aspirante $aspirante)
{
return $this->render('frontend/aspirante/registro_finalizado.html.twig', [
'aspirante' => $aspirante
]);
}
/**
* @Route("/edit/{id}/{plan}", name="frontend_aspirante_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Aspirante $aspirante, PlanesOfertados $plan, Mailer $mailer, AspRegistroRepository $aspRegistroRepository): Response
{
$existe = $request->query->get('existe');
$form = $this->createForm(AspiranteType::class, $aspirante, [
'nivelPlan' => $plan->getNivelPlanEstudios(), 'status' => self::STATUS
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//TODO Aqui antualizamos el Registro
$aspRegistro = $aspRegistroRepository->findBy(['aspirante' =>$aspirante->getId()]);
$entityManager = $this->doctrine->getManager();
//Validamos que ya exista un usuario para el aspirante, si no existe, lo creamos
if(!$aspirante->getUsuario()){
$user = new User();
$user->setEmail($aspirante->getCorreoElectronico());
$user->setNombre($aspirante->getNombre());
$user->setApellidos($aspirante->getApellidoPaterno() . ' ' . $aspirante->getApellidoMaterno());
$user->setRoles(["ROLE_VIOLETA", "ROLE_BACKEND"]);
$user->setActivo(true);
$user->setFechaCreacion(new \DateTime());
$user->setFechaActualizacion(new \DateTime());
$user->setPassword('1234567890');
$entityManager->persist($user);
$aspirante->setUsuario($user);
$aspirante->setFechaActualizacion(new \DateTime());
$entityManager->persist($aspirante);
$entityManager->flush();
}
// Actualizamos estado, fechaCreacion, fechaActualizacion en Multiculturalidad
// Actualizamos en AspRegistro
$aspRegistro[0]->setFechaCreacion(new \DateTime());
$aspRegistro[0]->setFechaActualizacion(new \DateTime());
$aspRegistro[0]->setEstado(1);
//$aspRegistro[0]->setCiclo(null);
$aspRegistro[0]->setFolioCeneval(null);
$aspRegistro[0]->setConsecutivoPlesxures(null);
$aspRegistro[0]->setGrupo('');
$aspRegistro[0]->setTurno(0);
$aspRegistro[0]->setReferencia('');
$aspRegistro[0]->setPeriodoIngreso('2024B');
$entityManager->flush();
$mailer->enviarEmailAspirante($aspirante);
$this->addFlash('success', 'El Registro se editó correctamente.');
return $this->redirectToRoute('frontend_aspirante_registro_finalizado', [ "id" => $aspirante->getId() ]);
}
return $this->renderForm('frontend/aspirante/edit.html.twig', [
'form' => $form,
'planOfertado' => $plan,
'accion' => 'edit',
'existe' => $existe
]);
}
/**
* @Route("/{id}/enviar-email", name="frontend_aspirante_enviar_email")
*/
public function enviaEmail(Aspirante $aspirante, Mailer $mailer)
{
if($aspirante)
{
$mailer->enviarEmailAspirante($aspirante);
$this->addFlash('success', 'Se ha enviado el correo satisfactoriamente.');
} else {
$this->addFlash('error', 'No se ha encontrado email.');
}
return $this->redirectToRoute('frontend_aspirante_registro_finalizado', [ 'id'=> $aspirante->getId() ]);
}
/**
* @Route("/{id}/pdf", name="frontend_aspirante_pdf")
*/
public function generaPDF(Aspirante $aspirante, AspRegistroRepository $aspRegistroRepository,TCPDFController $tcpdf, AspiranteService $aspiranteService, $projectDir)
{
$datosRegistro = $aspRegistroRepository->findByAspirante($aspirante->getId());
if($datosRegistro)
{
$pdf = $aspiranteService->generaRegistroPDF($tcpdf, $aspirante, $datosRegistro, $projectDir);
//$pdf = $aspiranteService->generarPreregistroPDF($aspirante, $datosRegistro);
$pdf->Output('registroUAGro.pdf', 'D');
} else {
$this->addFlash('error', 'No se ha encontrado Preregistro con los datos proporcionados.');
return $this->redirectToRoute('frontend_aspirante_buscar_preregistro_curp');
}
}
/**
* @Route("/search-preregistration-curp", name="frontend_aspirante_buscar_preregistro_curp")
*/
public function buscarPreregistroCurp(Request $request, AspiranteRepository $aspiranteRepository, AspRegistroRepository $aspRegistroRepository): Response
{
$form = $this->createForm(BuscaPreregistroCurpType::class, null);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
$aspirante = $aspiranteRepository->findOneBy([
'curp' => $formData['curp']
]);
if ($aspirante) {
$this->addFlash('success', 'Preregistro encontrado.');
return $this->redirectToRoute('frontend_aspirante_registro_finalizado', [ "id" => $aspirante->getId() ]);
} else {
$this->addFlash('error', 'No se ha encontrado Preregistro con la CURP proporcionada.');
return $this->redirectToRoute('frontend_aspirante_buscar_preregistro_curp');
}
}
return $this->renderForm('frontend/aspirante/buscar_preregistro_curp.html.twig', [
'form' => $form
]);
}
/**
* @Route("/search-preregistration", name="frontend_aspirante_buscar_preregistro")
*/
public function buscarPreregistro(Request $request, AspiranteRepository $aspiranteRepository, AspRegistroRepository $aspRegistroRepository): Response
{
$form = $this->createForm(BuscaPreregistroType::class, null);
// Obtenemos los valores enviados en el $request
// dd($request->request->all());
// dd($request->request->get('busca_preregistro')['curp']);
$curp = $request->request->get('busca_preregistro')['curp'] ?? null;
if(isset($curp)){
// Buscamos datospor la CURP
$aspirante = $aspiranteRepository->findOneBy([
'curp' => $curp
]);
$aspRegistro = $aspRegistroRepository->findOneBy([
'aspirante' => $aspirante,
//'claveUnicaRegistro' => '3-4MM929E3'
]);
return $this->renderForm('frontend/aspirante/resultado_preregistro_curp.html.twig', [
'registro' => $aspRegistro,
]);
/* if ($aspRegistro) {
$this->addFlash('success', 'Preregistro encontrado.');
return $this->redirectToRoute('frontend_aspirante_edit', [ 'id' => $aspirante->getId(), 'plan' => $aspRegistro->getPlanOfertado()->getId(), 'existe' => true ]);
}*/
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
$aspirante = $aspiranteRepository->findOneBy([
'curp' => $formData['curp']
]);
$aspRegistro = $aspRegistroRepository->findOneBy([
'aspirante' => $aspirante,
'claveUnicaRegistro' => $formData['clur']
]);
if ($aspRegistro) {
$this->addFlash('success', 'Preregistro encontrado.');
return $this->renderForm('frontend/aspirante/resultado_preregistro_curp.html.twig', [
'registro' => $aspRegistro,
]);
// return $this->redirectToRoute('frontend_aspirante_edit', [ 'id' => $aspirante->getId(), 'plan' => $aspRegistro->getPlanOfertado()->getId() ]);
//return $this->redirectToRoute('frontend_aspirante_edit', [ 'id' => $aspirante->getId(), 'plan' => $aspRegistro->getPlanOfertado()->getId() ]);
} else {
$this->addFlash('error', 'No se ha encontrado Preregistro con los datos proporcionados.');
return $this->redirectToRoute('frontend_aspirante_buscar_preregistro');
}
}
return $this->renderForm('frontend/aspirante/buscar_preregistro.html.twig', [
'form' => $form
]);
}
/**
* @Route("/search-exist-preregistration/{curp}", name="frontend_aspirante_buscar_curp_preregistro")
*/
public function buscarExistPreregistro(Request $request, $curp, AspiranteRepository $aspiranteRepository, AspRegistroRepository $aspRegistroRepository): Response
{
$form = $this->createForm(BuscaPreregistroType::class, null);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
$aspirante = $aspiranteRepository->findOneBy([
'curp' => $formData['curp']
]);
$aspRegistro = $aspRegistroRepository->findOneBy([
'aspirante' => $aspirante,
'claveUnicaRegistro' => $formData['clur']
]);
if ($aspRegistro) {
$this->addFlash('success', 'Preregistro encontrado.');
return $this->redirectToRoute('frontend_aspirante_edit', [ 'id' => $aspirante->getId(), 'plan' => $aspRegistro->getPlanOfertado()->getId() ]);
} else {
$this->addFlash('error', 'No se ha encontrado Preregistro con los datos proporcionados.');
return $this->redirectToRoute('frontend_aspirante_buscar_preregistro');
}
}
return $this->renderForm('frontend/aspirante/buscar_preregistro.html.twig', [
'form' => $form
]);
}
// Creamos una accion para validar el correo electronico en la entidad Use
/**
* @Route("/validate-email", name="frontend_aspirante_validate_email", methods={"GET"})
*/
public function validateEmail(Request $request): JsonResponse
{
$email = $request->query->All();
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $email['correo']]);
if ($user) {
return new JsonResponse(['status' => 'success', 'message' => 'El correo electrónico ya se encuentra registrado, favor de ingresar otro correo'], 200);
}
return new JsonResponse(['status' => 'error', 'message' => 'El correo electrónico es válido'], 404);
}
}