src/Controller/Frontend/IndexController.php line 591

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Frontend;
  3. use App\Controller\Shared\Livescoring\LivescoringCache;
  4. use App\Controller\Shared\MatchPlay\RyderCup\RyderCupResultsData;
  5. use App\Controller\Shared\Player\UpdatePlayerFromFederated;
  6. use App\Controller\Shared\Socket\LivescoringChannelKey;
  7. use App\DBAL\Backend\EnumEstadoInscrito;
  8. use App\DBAL\Backend\EnumEstadoRestringirLicencias;
  9. use App\Service\CalculateCurrentHoleService;
  10. use App\Entity\Backend\CompetitionSection;
  11. use App\Entity\Backend\CompetitionSectionHidden;
  12. use App\Service\Competition\PreferredLicenseClubChecker;
  13. use Doctrine\Common\Collections\ArrayCollection;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Redis;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  24. use Symfony\Component\HttpKernel\KernelInterface;
  25. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  26. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  27. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  28. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  29. use Symfony\Component\Form\Extension\Core\Type\TextType;
  30. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  31. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  32. use Symfony\Component\Validator\Constraints\NotBlank;
  33. use Symfony\Component\Asset\Packages;
  34. use Buzz\Browser;
  35. use Buzz\Client\FileGetContents;
  36. use Nyholm\Psr7\Factory\Psr17Factory;
  37. use App\Entity\Backend\Inscrito;
  38. use App\Entity\Backend\InscritoDocumento;
  39. use App\Entity\Backend\Log;
  40. use App\Entity\Backend\HcpJuego;
  41. use App\Entity\Backend\Equipo;
  42. use App\Util\Util;
  43. use App\Util\UtilStatic;
  44. use App\Util\UtilJugadores;
  45. use App\Util\Tarjetas;
  46. use App\Entity\Backend\Pedido;
  47. use App\Entity\Backend\Jugador;
  48. use App\Entity\Backend\Categoria;
  49. use App\Entity\Backend\CategoriaConfig;
  50. use App\Entity\Backend\Clasificacion;
  51. use App\Entity\Backend\Clasificado;
  52. use App\Entity\Backend\Cliente;
  53. use App\Entity\Backend\Comunidad;
  54. use App\Service\FederatedWebService;
  55. // use App\Service\RFEGWebService;
  56. use App\Util\RedsysAPI;
  57. use App\Util\Recipe;
  58. use App\Entity\Backend\JugadorRGPD;
  59. use App\Service\EnvioCorreo;
  60. use App\Service\EnvioSms;
  61. use App\Service\NotificacionesService;
  62. use App\Util\Utilidades;
  63. use App\Entity\Backend\Club;
  64. use App\Entity\Backend\Competicion;
  65. use App\Entity\Backend\Estadisticas;
  66. use App\Entity\Backend\Horario;
  67. use App\Entity\Backend\Jornada;
  68. use App\Entity\Backend\JornadaConfig;
  69. use App\Entity\Backend\Resultado;
  70. use App\Entity\Backend\Sms;
  71. use App\Entity\Backend\SoftwareGolf;
  72. use App\Entity\Backend\Trazado;
  73. use App\Entity\Backend\TrazadoBarra;
  74. use App\Entity\Gestion\JugadorHorario;
  75. use App\Entity\Gestion\PartidaHorario;
  76. use App\Entity\User\User;
  77. use App\Entity\User\UserApp;
  78. use App\Entity\Backend\Provincia;
  79. use Doctrine\Persistence\ManagerRegistry;
  80. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  81. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  82. use App\Util\SoftwareExternoUtil;
  83. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  84. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  85. class IndexController extends AbstractController
  86. {
  87.     public function __construct(
  88.         private readonly EntityManagerInterface    $em,
  89.         private readonly Util                      $util,
  90.         private readonly Utilidades                $utilidades,
  91.         private readonly TokenStorageInterface     $tokenStorage,
  92.         private readonly SessionInterface          $session,
  93.         private readonly UpdatePlayerFromFederated $updatePlayerFromFederated,
  94.         private readonly RyderCupResultsData       $ryderCupResultsData
  95.     )
  96.     {
  97.     }
  98.     /**
  99.      * F-017 Pagina principal
  100.      *
  101.      * @Route("/", name="portada")
  102.      *
  103.      */
  104.     public function index(Request $requestEnvioCorreo $mailer)
  105.     {
  106. //        $secret = $this->getParameter('secret');
  107. //        $long = $this->getParameter('next.longitud.hash');
  108. //        $cifrado = $this->util->encriptarLargo('majgolfacademyForSlope', $secret, $long);
  109.         $numTournaments $this->em->getRepository(Competicion::class)->cuentaCompeticionesTotal();
  110.         $totalPaidEnrolled $this->em->getRepository(Inscrito::class)->countPaid();
  111.         // Creamos el formulario. Lo creamos asi ya que no hace falta entidad para contacto.
  112.         $form $this->createContactForm();
  113.         $form->handleRequest($request);
  114.         // Cuando se mande el formulario se enviara un correo para nosotros con el mensaje del usuario y los datos que ha introducido
  115.         if ($form->isSubmitted() && $form->isValid()) {
  116.             $this->sendContact($form$mailer);
  117.             $form $this->createContactForm();
  118.             return $this->redirectToRoute('portada');
  119.         }
  120.         // Se recoge la informacion necesaria para mostrar el componente de las plazas de la competicion
  121.         $competicionesInscripcionCercana $this->em->getRepository(Competicion::class)->competicionesInscripcionCercana(12);
  122.         return $this->render('frontend/Default/index.html.twig', [
  123.             "form" => $form->createView(),
  124.             "limiteLivescoring" => 4// tarjetas que se muestran por cada componente livescoring
  125.             "competicionesInscripcionCercana" => $competicionesInscripcionCercana,
  126.             "counter" => [
  127.                 "tournaments" => $numTournaments,
  128.                 "players" => $totalPaidEnrolled
  129.             ]
  130.         ]);
  131.     }
  132.     // Creamos aqui el formulario de contacto que tendra la index
  133.     private function createContactForm()
  134.     {
  135.         $form $this->createFormBuilder()
  136.             ->setMethod("POST")
  137.             ->add('name'TextType::class, array(
  138.                 'constraints' => new NotBlank(),
  139.                 "required" => true,
  140.                 "label" => "labels.contact.name",
  141.                 "translation_domain" => "FrontendBundle",
  142.                 'label_attr' => [
  143.                     'class' => 'label'
  144.                 ],
  145.                 'attr' => [
  146.                     'class' => "text-input"
  147.                 ]
  148.             ))
  149.             ->add('email'EmailType::class, array(
  150.                 'constraints' => new NotBlank(),
  151.                 "required" => true,
  152.                 "label" => "labels.contact.email",
  153.                 "translation_domain" => "FrontendBundle",
  154.                 'label_attr' => [
  155.                     'class' => 'label'
  156.                 ],
  157.                 'attr' => [
  158.                     'class' => "text-input"
  159.                 ]
  160.             ))
  161.             ->add('club'TextType::class, array(
  162.                 "required" => false,
  163.                 "label" => "labels.contact.club",
  164.                 "translation_domain" => "FrontendBundle",
  165.                 'label_attr' => [
  166.                     'class' => 'label'
  167.                 ],
  168.                 'attr' => [
  169.                     'class' => "text-input"
  170.                 ]
  171.             ))
  172.             ->add('license'TextType::class, array(
  173.                 "required" => false,
  174.                 "label" => "labels.contact.license",
  175.                 "translation_domain" => "FrontendBundle",
  176.                 'label_attr' => [
  177.                     'class' => 'label'
  178.                 ],
  179.                 'attr' => [
  180.                     'class' => "text-input"
  181.                 ]
  182.             ))
  183.             ->add('message'TextareaType::class, array(
  184.                 'constraints' => new NotBlank(),
  185.                 "required" => true,
  186.                 "label" => "labels.contact.message",
  187.                 "translation_domain" => "FrontendBundle",
  188.                 'label_attr' => [
  189.                     'class' => 'label'
  190.                 ],
  191.                 'attr' => [
  192.                     "rows" => 4,
  193.                     "cols" => 50,
  194.                     'class' => "textarea"
  195.                 ]
  196.             ))
  197.             ->add('privacyPolicy'CheckboxType::class, array(
  198.                 'constraints' => new NotBlank(),
  199.                 "required" => true,
  200.                 "label" => false,
  201.                 'label_attr' => [
  202.                     'class' => 'label-check'
  203.                 ],
  204.                 "translation_domain" => "FrontendBundle"
  205.             ))
  206.             ->add('send'SubmitType::class, array(
  207.                 'label' => "labels.contact.send",
  208.                 "translation_domain" => "FrontendBundle",
  209.                 'attr' => [
  210.                     'class' => "button enviar"
  211.                 ]
  212.             ))
  213.             ->getForm();
  214.         return $form;
  215.     }
  216.     /**
  217.      * @Route("/livescoring-start", name="livescoring_start")
  218.      */
  219.     public function indexLivescoringStart(LivescoringCache $livescoringCacheLivescoringChannelKey $livescoringChannelKey)
  220.     {
  221.         // Devuelve las jornadas que se quieren mostrar en el livescoring de la index
  222.         $jornadasLivescoring $this->em->getRepository(Jornada::class)->indexLivescoring();
  223.         if (empty($jornadasLivescoring)) {
  224.             return $this->json([]);
  225.         }
  226.         $roundIds array_column($jornadasLivescoring"id");
  227.         $jornadas $this->em->getRepository(Jornada::class)->findBy(['id' => $roundIds]);
  228.         $jornadasById = [];
  229.         foreach ($jornadas as $jornadaLoaded) {
  230.             $jornadasById[$jornadaLoaded->getId()] = $jornadaLoaded;
  231.         }
  232.         $livescoring = [];
  233.         foreach ($jornadasLivescoring as $jl) {
  234.             if (!isset($jornadasById[$jl["id"]])) {
  235.                 continue;
  236.             }
  237.             $jornada $jornadasById[$jl["id"]];
  238.             $competicion $jornada->getCompeticion();
  239.             $livescoringParams = [
  240.                 'isTeamLivescoring' => false
  241.             ];
  242.             $livescoring["l-" $jl["id"]] = [
  243.                 ...$livescoringCache->__invoke($jornada$livescoringParams),
  244.                 "compId" => $competicion->getId(),
  245.                 "nombreClub" => $competicion->getClub()->getNombre(),
  246.                 "nombreCompeticion" => $competicion->getNombre(),
  247.                 'socketChannel' => $livescoringChannelKey->__invoke($competicion)
  248.             ];
  249.         }
  250.         return $this->json($livescoring);
  251.     }
  252.     // public function contacto(Request $request, SendEmailUtil $mailer): Response {
  253.     //     $sended = 0;
  254.     //     //Creamos el formulario. Lo creamos asi ya que no hace falta entidad para contacto.
  255.     //     $form = $this->createContactForm([]);
  256.     //     $form->handleRequest($request);
  257.     //     if (count($form->getErrors()) > 0) {
  258.     //         $sended = -1;
  259.     //     }
  260.     //     if ($form->isSubmitted() && $form->isValid() /* && $this->captchaverify($request->get('g-recaptcha-response')) */) {
  261.     //         $mailer->sendEmail([
  262.     //             "from" => $this->getParameter('app.notifications.email_sender'),
  263.     //             "to" => $this->getParameter('email.contacto'),
  264.     //             "asunto" => 'Contacto FGM',
  265.     //             "cco" => "gest.slope@gmail.com",
  266.     //             "html" => $this->renderView('mail/contact_mail.html.twig', [
  267.     //                 'nombre' => $form->get("name")->getData(),
  268.     //                 'emailFrom' => $form->get("email")->getData(),
  269.     //                 'texto' => $form->get("text")->getData(),
  270.     //                 'telefono' => $form->get("phone")->getData(),
  271.     //                 'bloque' => 'contacto'
  272.     //             ])
  273.     //         ]);
  274.     //         //EmailContacto::sendEmailContact($form, $mailer, $this->getParameter('emails.contacto.user'));
  275.     //         //Limpiamos el array (lo creamos de nuevo)
  276.     //         $data = array();
  277.     //         $form = $this->createContactForm($data);
  278.     //         $sended = 1;
  279.     //     }
  280.     //     return $this->render('frontend/default/contacto.html.twig', array("form" => $form->createView(), "sended" => $sended));
  281.     // }
  282.     /**
  283.      * @Route("/search-panel", name="searchPanel", options={"expose"=true})
  284.      *
  285.      * Hace la busqueda de competiciones y clubes en la index
  286.      */
  287.     public function searchPanel(Request $request)
  288.     {
  289.         $text $request->request->get('text');
  290.         $competicionesBusqueda $this->em->getRepository(Competicion::class)->indexSearch($text);
  291.         $clubes $this->em->getRepository(Club::class)->findClubes($text);
  292.         $competiciones = [];
  293.         foreach ($competicionesBusqueda as $cb) {
  294.             $competiciones[] = [
  295.                 "id" => $cb["id"],
  296.                 "nombre" => $cb["nombre"],
  297.                 "fecha" => $cb["fecha"]->format("Y-m-d"),
  298.                 "nombreClub" => $cb["nombreClub"]
  299.             ];
  300.         }
  301.         return $this->json([
  302.             "competiciones" => $competiciones,
  303.             "clubes" => $clubes
  304.         ]);
  305.     }
  306.     /**
  307.      * F-018 Falso feed de calendario
  308.      *
  309.      * @Route("/{locale}/f/club/{club}/feed.ics", name="feed")
  310.      *
  311.      */
  312.     public function feed($locale$club)
  313.     {
  314.         return new JsonResponse(["club" => $club"locale" => $locale]);  //$this->redirect($this->generateUrl('_club', array('id' => $club)));
  315.     }
  316.     /**
  317.      * F-019 Envio de SMS de prueba para los usuarios con rol marketing
  318.      *
  319.      * @Route("/sms-reset", name="sms_reset_marketing", options={"expose"=true})
  320.      *
  321.      */
  322.     public function smsReset(Request $requestEnvioCorreo $mailerEnvioSms $messagingUtilJugadores $util_jugadores)
  323.     {
  324.         $respuesta = array();
  325.         $numero $request->request->get('numero');
  326.         if (!$numero) {
  327.             $respuesta['codigo'] = -2;
  328.             $respuesta['mensaje'] = "No se ha indicado ningĆŗn numero de telefono al que mandar los mensajes";
  329.             return new JsonResponse($respuesta);
  330.         }
  331.         //usamos el campo publicidad a modo de prioridad. Buscamos los que son de prioridad negativa, segun su usuario
  332.         $usuario $request->request->get('usuario');
  333.         $smss $this->em->getRepository(Sms::class)->findBy(array('publicidad' => (-$usuario)));
  334.         if (!$smss) {
  335.             $respuesta['codigo'] = -1;
  336.             $respuesta['mensaje'] = "No hay ningĆŗn SMS de ejemplo";
  337.             return new JsonResponse($respuesta);
  338.         }
  339.         $ahora = new \DateTime('now');
  340.         $secret $this->getParameter('secret');
  341.         //ponemos los mensjaes como no enviados y le asignamos el numero de telefono que le corresponde
  342.         foreach ($smss as $sms) {
  343.             $sms->setTelefono($numero$secret);
  344.             $sms->setUpdatedAt($ahora);
  345.             $messaging->enviarSmsAPI($smstrue0true);
  346.         }
  347.         $this->em->flush();
  348.         //tomamos la IP y la localización del cliente para adjuntarla al email
  349.         $client_location Recipe::getClientLocation();
  350.         $client_IP Recipe::getClientIP();
  351.         $user $this->em->getRepository(User::class)->findOneBy(array('ccc' => $usuario));
  352.         //mandamos email avisando del login
  353.         $args = [
  354.             "to" => "nacho.perez.benito@gmail.com",
  355.             "subject" => 'NextCaddy - SMS de prueba enviados (pagina de marketing)',
  356.             "html" => $this->renderView('backend/mail/email_envio_sms.html.twig', array(
  357.                 'user' => $user,
  358.                 'numero' => $numero,
  359.                 'client_ip' => $client_IP,
  360.                 'client_location' => $client_location))
  361.         ];
  362.         //EnvioCorreo::enviarCorreo($args);
  363.         $mailer->enviarCorreo($args);
  364.         $respuesta['codigo'] = 0;
  365.         $respuesta['mensaje'] = "Se han enviado los mensajes de ejemplo";
  366.         return new JsonResponse($respuesta);
  367.     }
  368.     /**
  369.      * @Route("/field-f1", name="field_f1")
  370.      */
  371.     public function fieldF1()
  372.     {
  373.         $totalRoundsNumber $this->em->getRepository(Jornada::class)->countAllWithDeleted();
  374.         $totalPaidEnrolled $this->em->getRepository(Inscrito::class)->countPaid();
  375.         return $this->render("frontend/Television/formula1.html.twig", [
  376.             "totalRoundsNumber" => $totalRoundsNumber,
  377.             "totalPaidEnrolled" => $totalPaidEnrolled
  378.         ]);
  379.     }
  380.     /**
  381.      * F-020 Envio de SMS de prueba para demos y presentaciones
  382.      *
  383.      * @Route("/sms-reset/{numero}", name="sms_reset", options={"expose"=true})
  384.      *
  385.      */
  386.     public function smsExample($numeroEnvioSms $messaging)
  387.     {
  388.         $respuesta = ['codigo' => 0];
  389.         //usamos el campo publicidad a modo de prioridad. Buscamos los que son de maxima prioridad, ya que esos seran los que sean de ejemplo (prioridad minima 8, 9 o mas, no envia)
  390.         $smss $this->em->getRepository(Sms::class)->findBy(array('publicidad' => 0));
  391.         if (!$smss) {
  392.             $respuesta['codigo'] = -1;
  393.             return $this->render("frontend/Default/smsExamples.html.twig"$respuesta);
  394.         }
  395.         $ahora = new \DateTime('now');
  396.         $secret $this->getParameter('secret');
  397.         //ponemos los mensjaes como no enviados y le asignamos el numero de telefono que le corresponde
  398.         foreach ($smss as $sms) {
  399.             $sms->setTelefono($numero$secret);
  400.             $sms->setUpdatedAt($ahora);
  401.             $messaging->enviarSmsAPI($smstrue0true);
  402.         }
  403.         $this->em->flush();
  404.         $log_message "Envio de Sms de prueba al telĆ©fono " $numero;
  405.         $log = new Log('i'$log_messagenull);
  406.         $this->em->persist($log);
  407.         $this->em->flush();
  408.         return $this->render("frontend/Default/smsExamples.html.twig"$respuesta);
  409.     }
  410.     /**
  411.      * F-021 Envio de visita a la pagina para estadisticas de Google Analitycs para Internet Explorer o fallo de la libreria Javascript
  412.      *
  413.      * @Route("/collect", name="collect", options={"expose"=true})
  414.      *
  415.      */
  416.     public function collect()
  417.     {
  418.         $params = array('v' => 1,
  419.             'tid' => "UA-61056427-1",
  420.             'cid' => rand(10000009999999),
  421.             't' => "event",
  422.             'ec' => "Blocking",
  423.             'ea' => "NextCaddy",
  424.             'ni' => '0',
  425.             'z' => rand(10000009999999),
  426.         );
  427.         $client = new FileGetContents(new Psr17Factory());
  428.         $browser = new Browser($client, new Psr17Factory());
  429.         $url 'https://www.google-analytics.com/collect?' http_build_query($params);
  430.         try {
  431.             $response $browser->get($url);
  432.             $res $response->getStatusCode() == '200';
  433.         } catch (\Throwable $e) {
  434.             $res false;
  435.         }
  436.         return new JsonResponse($res);
  437.     }
  438.     /**
  439.      * F-022 Obtención de datos de un club concreto
  440.      *
  441.      * @Route("/getClubs", name="_ajGetClubs", options={"expose"=true})
  442.      *
  443.      */
  444.     public function getClubsByName(Request $request)
  445.     {
  446.         //retrieve the query
  447.         $query $request->request->get("query");
  448.         $Clubs $this->em->getRepository(Club::class)->findClubByName($query);
  449.         if (!$Clubs) {
  450.             // throw exception
  451.         }
  452.         $response = new JsonResponse();
  453.         $response->setData($Clubs);
  454.         return $response;
  455.     }
  456.     /**
  457.      * F-023 Obtención de datos de un jugador en un torneo
  458.      *
  459.      * @Route("/getJugador", name="_ajGetJugador", options={"expose"=true})
  460.      *
  461.      */
  462.     public function getJugadorByName(Request $request)
  463.     {
  464.         //retrieve the query
  465.         $query $request->get('query');
  466.         $tour $request->get('tournament');
  467.         $playersNames $this->em->getRepository(Jugador::class)->findPlayerCard($query$tour);
  468.         if (!$playersNames) {
  469.             // throw exception
  470.         }
  471.         $response = new JsonResponse();
  472.         $response->setData($playersNames);
  473.         return $response;
  474.     }
  475.     /**
  476.      * F-024 Pagina de instrucciones para integrar NextCaddy en la web del club
  477.      *
  478.      * @Route("/integracion", name="integracion")
  479.      */
  480.     public function integracionWidget()
  481.     {
  482.         $clubs $this->em->getRepository(Club::class)->findTodosParaRandom();
  483.         if (!$clubs) {
  484.             $this->addFlash(
  485.                 'error'"Ha ocurrido un error. Por favor, intĆ©ntelo mĆ”s tarde");
  486.             //return $this->redirect($this->generateUrl('_club', array('id' => "AM00")));
  487.             return $this->redirect($this->generateUrl('portada'));
  488.         }
  489.         return $this->render("frontend/Club/generarWidget.html.twig", [
  490.             'clubes' => $clubs
  491.         ]);
  492.     }
  493.     /**
  494.      * F-025 Pagina de Politica de cookies
  495.      *
  496.      * @Route("/cookies", name="cookies")
  497.      */
  498.     public function cookies()
  499.     {
  500.         return $this->render("frontend/Default/politica_cookies.html.twig");
  501.     }
  502.     /**
  503.      * F-026 Pagina de Politica de privacidad
  504.      *
  505.      * @Route("/privacidad", name="privacidad")
  506.      */
  507.     public function privacidad()
  508.     {
  509.         return $this->render("frontend/Default/privacidad.html.twig");
  510.     }
  511.     /**
  512.      * F-027 Pagina de Terminos y condiciones
  513.      *
  514.      * @Route("/terminos-y-condiciones", name="terminos_condiciones")
  515.      */
  516.     public function terminosCondiciones()
  517.     {
  518.         return $this->render("frontend/Default/terminos_condiciones.html.twig");
  519.     }
  520.     /**
  521.      * F-029 Seleccionamos el tipo de livescoring para la competicion
  522.      *
  523.      * @Route("/livescoring-select/{id}/{ordenUrl}/{letra}", name="envivo_select", defaults={"letra"="H", "ordenUrl"=0}, options={"expose"=true})
  524.      */
  525.     public function envivoSelect($id$ordenUrl$letra): RedirectResponse
  526.     {
  527.         $competicion $this->em->getRepository(Competicion::class)->find($id);
  528.         if (empty($competicion)) {
  529.             throw new \Exception("Competition with id $id not found");
  530.         }
  531.         if (in_array($competicion->getFormula()->getId(), ['R''P'])) {
  532.             return $this->redirect($this->generateUrl('gestion_ryder_cup_livescoring', array('idc' => $id)));
  533.         }
  534.         //TODO search all uses and change to new livesoring route. While Redirect to new livescoring
  535.         return $this->redirect($this->generateUrl('livescoring', array('id' => $id)));
  536.     }
  537.     /**
  538.      * F-030 Visualización de competiciones a travĆ©s del widget (iframe)
  539.      *
  540.      * @Route("/widget/{id}", name="_widget")
  541.      */
  542.     public function widget($id)
  543.     {
  544.         $entity $this->em->getRepository(Club::class)->findOneBy(array("id" => $id"habilitado" => true));
  545.         if (!$entity) {
  546.             $this->addFlash(
  547.                 'error'"No encontramos el Club que nos ha solicitado");
  548.             //return $this->redirect($this->generateUrl('_club', array('id' => "AM00")));
  549.             return $this->redirect($this->generateUrl('portada'));
  550.         }
  551.         $futuras = array();
  552.         $pasadas = array();
  553.         if ($id != "AM00") {
  554.             //Me traigo competiciones futuras y pasadas
  555.             $futuras $this->em->getRepository(Competicion::class)->getCompeticiones($id360"mayor""ASC"true);
  556.             $pasadas $this->em->getRepository(Competicion::class)->getCompeticiones($id360"menor""DESC"true);
  557.         } else {
  558.             //Me traigo competiciones futuras y pasadas
  559.             $futuras $this->em->getRepository(Competicion::class)->getCompeticionesOrganizador("AM00"480"mayor""ASC"true);
  560.             $pasadas $this->em->getRepository(Competicion::class)->getCompeticionesOrganizador("AM00"480"menor""DESC"true);
  561.         }
  562.         return $this->render("frontend/Club/widget.html.twig", [
  563.             'entity' => $entity,
  564.             'futuras' => $futuras,
  565.             'pasadas' => $pasadas
  566.         ]);
  567.     }
  568.     /**
  569.      * F-033 Mostrar inscritos estado de corte. [Creo que en desuso]
  570.      *
  571.      * @Route("/inscritoscorte", name="_ajInscritosCorte", options={"expose"=true})
  572.      */
  573.     public function inscritosCorte(Request $request)
  574.     {
  575.         $id $request->request->get("id");
  576.         //comprobar datos de ordenacion competicion.
  577.         $comp_criteria $this->em->getRepository(Competicion::class)->find($id);
  578.         $num_jugadores $comp_criteria->getJugadores();
  579.         //Distinguimos entre si tenemos 1 o mas jugadores por equipo en la competicion,
  580.         //de esta manera para parejas y equipos mostramos la lista sin linea de corte (que ha sido deshabilidada en el backend)
  581.         //para mostrar el listado que estĆ” agrupado por parejas o equipos
  582.         if ($num_jugadores == 1) {
  583.             $params['competi'] = $comp_criteria;
  584.             if ($comp_criteria->getCriterio() == null && $comp_criteria->getCriterio2() == null) {
  585.                 //comprobar datos de ordenacion categoria.
  586.                 //$cat_criteria = $this->em->getRepository(Categoria::class)->findByCompeticion($id);
  587.                 $cat_criteria $this->em->getRepository(Categoria::class)->findCategoriasInscritosActivos($id);
  588.                 foreach ($cat_criteria as $crit) {
  589.                     $inscritosporcategoria[$crit->getId()] = $this->em->getRepository(Inscrito::class)->getPlayersByCatCorte($id$crit->getId(), $crit->getCriterio(), $crit->getCriterio2());
  590.                 }
  591.                 $params['inscritosbycat'] = $inscritosporcategoria;
  592.                 $params['categorias'] = $cat_criteria;
  593.             } else {
  594.                 $cri1 null;
  595.                 $ord1 "ASC";
  596.                 $cmpcr1 $comp_criteria->getCriterio();
  597.                 if (!empty($cmpcr1)) {
  598.                     $cri1 $cmpcr1->getCampo();
  599.                     $ord1 $cmpcr1->getOrden();
  600.                 }
  601.                 $cri2 null;
  602.                 $ord2 "ASC";
  603.                 $cmpcr2 $comp_criteria->getCriterio2();
  604.                 if (!empty($cmpcr2)) {
  605.                     $cri2 $cmpcr2->getCampo();
  606.                     $ord2 $cmpcr2->getOrden();
  607.                 }
  608.                 $players $this->em->getRepository(Inscrito::class)->getPlayersByCorte($id$cri1$ord1$cri2$ord2);
  609.                 $params['inscritos'] = $players;
  610.             }
  611.             $params['showInscribeDateInWaitingList'] = $this->checkIfShowInscribeDateInWaitingList($id);
  612.             return $this->render('frontend/Inscritos/inscritos_corte_tbl_new.html.twig'$params);
  613.         } else {
  614.             $players $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($comp_criteriatrue);
  615.             if ($num_jugadores == 2) {
  616.                 $view 'frontend/Inscritos/inscritos_tbl_parejas_new.html.twig';
  617.             } else {
  618.                 $view 'frontend/Inscritos/inscritos_tbl_equipos_new.html.twig';
  619.             }
  620.             $list = array();
  621.             foreach ($players as $i) {
  622.                 if (!in_array($i->getJugador()->getSexo(), $listtrue)) {
  623.                     array_push($list$i->getJugador()->getSexo());
  624.                 }
  625.             }
  626.             // if (!$players) {
  627.             //     $response = new JsonResponse();
  628.             //     return $response->setData('No data');
  629.             // } else {
  630.             return $this->render($view, array(
  631.                 'inscritos' => $players,
  632.                 'competi' => $comp_criteria,
  633.                 'sexos' => count($list)
  634.             ));
  635.             // }
  636.         }
  637.     }
  638.     /**
  639.      * F-034 Mostrar inscritos con y sin linea de corte
  640.      * Ya es la plantilla la que me lo separa. Yo solo mando array agrupado
  641.      *
  642.      * @Route("/getListadoInscritos", name="listado_inscritos", options={"expose"=true})
  643.      *
  644.      */
  645.     public function listadoInscritos(Request $request)
  646.     {
  647.         $competitionId $request->request->get("id"0);
  648.         $token $request->request->get("token"null);
  649.         //comprobar datos de ordenacion competicion.
  650.         $competition $this->em->getRepository(Competicion::class)->find($competitionId);
  651.         if (!$competition) {
  652.             return new JsonResponse(-1);
  653.         }
  654.         if (!$this->util->checkTokenValidIframe($competition$token)) {
  655.             return new JsonResponse(-1);
  656.         }
  657.         $numPlayersByTeam $competition->getJugadores();
  658.         //Distinguimos entre si tenemos 1 o mas jugadores por equipo en la competicion,
  659.         //de esta manera para parejas y equipos mostramos la lista sin linea de corte (que ha sido deshabilidada en el backend)
  660.         //para mostrar el listado que estĆ” agrupado por parejas o equipos
  661.         if ($numPlayersByTeam == 1) {
  662.             $numTotalJornadas count($competition->getJornadas());
  663.             $params['competition'] = $competition;
  664.             $jornadaConfigByCategory = [];
  665.             if ($competition->getCriterio() == null && $competition->getCriterio2() == null) {
  666.                 $inscritosByCategory = [];
  667.                 $categoriasByCompetition = [];
  668.                 $cutOffByCategory false;
  669.                 $inscritos $this->em->getRepository(Inscrito::class)->getActiveInscribedOrdered($competition);
  670.                 foreach ($inscritos as $inscrito) {
  671.                     $inscribedCategory $inscrito->getCategoria();
  672.                     if (is_null($inscribedCategory)) {
  673.                         continue;
  674.                     }
  675.                     if (!isset($categoriasByCompetition[$inscribedCategory->getId()])) {
  676.                         $categoriasByCompetition[$inscribedCategory->getId()] = [
  677.                             'id' => $inscribedCategory->getId(),
  678.                             'name' => $inscribedCategory->getNombre(),
  679.                             'criterio' => $inscribedCategory->getCriterio()?->getNombre(),
  680.                             'criterio_id' => $inscribedCategory->getCriterio()?->getId(),
  681.                             'criterio_orden' => $inscribedCategory->getCriterio()?->getOrden(),
  682.                             'criterio2' => $inscribedCategory->getCriterio2()?->getNombre(),
  683.                         ];
  684.                         if (!$cutOffByCategory && !is_null($inscribedCategory->getCriterio())) {
  685.                             $cutOffByCategory true;
  686.                         }
  687.                         $inscritosByCategory[$inscribedCategory->getId()] = [];
  688.                     }
  689.                     if ($inscrito->getParticipa() !== -1) {
  690.                         $inscritosByCategory[$inscribedCategory->getId()][] = $inscrito;
  691.                     }
  692.                     $inscritosByCategory['total'][] = $inscrito;
  693.                 }
  694.                 foreach ($categoriasByCompetition as $categoria) {
  695.                     if ($numTotalJornadas == 1) {
  696.                         $jornadaConfigByCategory[$categoria['id']] = $this->em->getRepository(JornadaConfig::class)->findOneByCategoria($categoria['id']);
  697.                     }
  698.                     if ($categoria['criterio_id'] == 'HCP') {
  699.                         usort($inscritosByCategory[$categoria['id']], function (Inscrito $aInscrito $b) use ($categoria$competition) {
  700.                             $participaComparison $b->getParticipa() <=> $a->getParticipa();
  701.                             if ($participaComparison !== 0) {
  702.                                 return $participaComparison;
  703.                             }
  704.                             if ($competition->getRestringirLicencia() === EnumEstadoRestringirLicencias::PREFERENCIA) {
  705.                                 $orderWaitingListComparison $a->getOrderWaitingList() <=> $b->getOrderWaitingList();
  706.                                 if ($orderWaitingListComparison !== 0) {
  707.                                     return $orderWaitingListComparison;
  708.                                 }
  709.                             }
  710.                             if ($categoria['criterio_orden'] == 'ASC') {
  711.                                 $hcpComparison $a->getHCP() <=> $b->getHCP();
  712.                             } else {
  713.                                 $hcpComparison $b->getHCP() <=> $a->getHCP();
  714.                             }
  715.                             if ($hcpComparison === 0) {
  716.                                 return $a->getId() <=> $b->getId();
  717.                             }
  718.                             return $hcpComparison;
  719.                         });
  720.                     }
  721.                 }
  722.                 $categoriasByCompetition['total'] = [
  723.                     'id' => 'total',
  724.                     'name' => 'Total'
  725.                 ];
  726.                 if ($cutOffByCategory) {
  727.                     unset($inscritosByCategory['total']);
  728.                     unset($categoriasByCompetition['total']);
  729.                 }
  730.                 $params['inscritosByCat'] = $inscritosByCategory;
  731.                 $params['categories'] = $categoriasByCompetition;
  732.                 $params['jornadaConfig'] = $jornadaConfigByCategory;
  733.             } else {
  734.                 $players $this->em->getRepository(Inscrito::class)->getPlayersByCorte($competitionId$competition->getCriterio()?->getCampo(), $competition->getCriterio()?->getOrden(), $competition->getCriterio2()?->getCampo(), $competition->getCriterio2()?->getOrden());
  735.                 $params['inscritos'] = $players;
  736.             }
  737.             $params['showInscribeDateInWaitingList'] = $this->checkIfShowInscribeDateInWaitingList($competitionId);
  738.             return $this->render('frontend/Inscritos/inscritos_corte_tbl_new.html.twig'$params);
  739.         } else {
  740.             $players $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($competitiontrue);
  741.             if ($numPlayersByTeam == && $competition->getEstricto()) {
  742.                 $view 'frontend/Inscritos/inscritos_tbl_parejas_new.html.twig';
  743.             } else {
  744.                 $view 'frontend/Inscritos/inscritos_tbl_equipos_new.html.twig';
  745.             }
  746.             $list = array();
  747.             foreach ($players as $i) {
  748.                 if (!in_array($i->getJugador()->getSexo(), $listtrue)) {
  749.                     array_push($list$i->getJugador()->getSexo());
  750.                 }
  751.             }
  752.             if (!$players) {
  753.                 $response = new JsonResponse();
  754.                 return $response->setData('No data');
  755.             } else {
  756.                 return $this->render($view, array(
  757.                     'inscritos' => $players,
  758.                     'competi' => $competition,
  759.                     'sexos' => count($list)
  760.                 ));
  761.             }
  762.         }
  763.     }
  764.     private function checkIfShowInscribeDateInWaitingList(int $competitionId): bool
  765.     {
  766.         $competitionSectionInscribedDateInWaitingList $this->em->getRepository(CompetitionSection::class)->findOneBy([
  767.             "dom_id" => "fecha_lista_espera"
  768.         ]);
  769.         $competitionSectionHiddenInscribedDateInWaitingList $this->em->getRepository(CompetitionSectionHidden::class)->findOneBy([
  770.             "competition" => $competitionId,
  771.             "competition_section" => $competitionSectionInscribedDateInWaitingList
  772.         ]);
  773.         return empty($competitionSectionHiddenInscribedDateInWaitingList);
  774.     }
  775.     /**
  776.      * @Route("/f1/{roundId}", name="formula1", options={"expose"=true})
  777.      */
  778.     public function formula1($roundId)
  779.     {
  780.         $round $this->em->getRepository(Jornada::class)->find($roundId);
  781.         if (empty($round)) {
  782.             return $this->json([]);
  783.         }
  784.         $calculateCurrentHoleService = new CalculateCurrentHoleService();
  785.         $jornadaConfig $this->em->getRepository(JornadaConfig::class)->findOneByJornada($round->getId());
  786.         $holesRange explode("-"$jornadaConfig->getHoyos());
  787.         $holesRangeArray range(intval($holesRange[0]), intval($holesRange[1]));
  788.         $isIndividual "I" === $round->getModalidad()->getId();
  789.         $playerSchedules $this->em->getRepository(JugadorHorario::class)->findJugadoresJornadaPublicada($round);
  790.         $numberHolesPlayed 0;
  791.         $players = [];
  792.         if ($playerSchedules) {
  793.             foreach ($playerSchedules as $playerSchedule) {
  794.                 $match $playerSchedule->getPartida();
  795.                 $lastHolePlayed $this->em->getRepository(Resultado::class)->findUltimoHoyo($roundId, [$playerSchedule->getInscrito()->getId()])["hoyo"] ?? 0;
  796.                 $currentHole $calculateCurrentHoleService->calculateCurrentHole($lastHolePlayed$holesRangeArray$match->getTee(), $numberHolesPlayed);
  797.                 if ($isIndividual) {
  798.                     $player $playerSchedule->getInscrito()?->getJugador();
  799.                     $hcp_juego $playerSchedule->getInscrito()->getHcpJuego() ? unserialize($playerSchedule->getInscrito()->getHcpJuego()) : "";
  800.                     if (!empty($hcp_juego)) {
  801.                         $hcpGame $this->em->getRepository(HcpJuego::class)->findOneBy(["inscrito" => $playerSchedule->getInscrito(), "jornada" => array_keys($hcp_juego)[0]]);
  802.                     }
  803.                     $players[] = [
  804.                         "teamId" => $playerSchedule->getEquipo(),
  805.                         "pairId" => $playerSchedule->getPareja(),
  806.                         "hcp" => round($playerSchedule->getInscrito()?->getHcp(), 2),
  807.                         "hcp_game" => round($hcpGame?->getHcp(), 2),
  808.                         "matchId" => $match->getId(),
  809.                         "teeTime" => $match->getHora(),
  810.                         "currentHole" => $currentHole,
  811.                         "name" => $player->getNombre(),
  812.                         "surname" => $player->getApellidos(),
  813.                         "license" => $player->getLicencia()
  814.                     ];
  815.                 } else {
  816.                     $enrolleds $this->em->getRepository(Inscrito::class)->findBy([
  817.                         "competicion" => $round->getCompeticion()?->getId(),
  818.                         "equipo" => $playerSchedule->getEquipo(),
  819.                         "pareja" => $playerSchedule->getPareja(),
  820.                         "participa" => 1,
  821.                         "estado" => "pagado"
  822.                     ]);
  823.                     foreach ($enrolleds as $enrolled) {
  824.                         $hcp_juego $enrolled->getHcpJuego() ? unserialize($enrolled->getHcpJuego()) : "";
  825.                         $hcpGame "";
  826.                         if (!empty($hcp_juego)) {
  827.                             $hcpGame $this->em->getRepository(HcpJuego::class)->findOneBy(["inscrito" => $enrolled"jornada" => array_keys($hcp_juego)[0]]);
  828.                         }
  829.                         $players[] = [
  830.                             "teamId" => $playerSchedule->getEquipo(),
  831.                             "pairId" => $playerSchedule->getPareja(),
  832.                             "hcp" => $enrolled?->getHcp(),
  833.                             "hcp_game" => round($hcpGame2),
  834.                             "matchId" => $match->getId(),
  835.                             "teeTime" => $match->getHora(),
  836.                             "currentHole" => $currentHole,
  837.                             "name" => $enrolled->getJugador()?->getNombre(),
  838.                             "surname" => $enrolled->getJugador()?->getApellidos(),
  839.                             "license" => $enrolled->getJugador()?->getLicencia()
  840.                         ];
  841.                     }
  842.                 }
  843.             }
  844.         }
  845.         return $this->json($players);
  846.     }
  847.     /**
  848.      * @Route("/3djs/{teeId}/{holeId}", name="3djs", options={"expose"=true})
  849.      */
  850.     public function apiInfoMarkers(Request $request)
  851.     {
  852.         $id $request->request->get("id"0);
  853.     }
  854.     /**
  855.      * F-036 Mostrar listado de las clasificaciones publicadas
  856.      *
  857.      * @Route("/getListadoClasificaciones", name="listado_clasificaciones", options={"expose"=true})
  858.      *
  859.      */
  860.     public function listadoClasificaciones(Request $request)
  861.     {
  862.         $id $request->request->get("id"0);
  863.         $token $request->request->get("token"null);
  864.         //comprobar competicion.
  865.         $competicion $this->em->getRepository(Competicion::class)->find($id);
  866.         if (!$competicion) {
  867.             return new JsonResponse(-1);
  868.         }
  869.         if (!$this->util->checkTokenValidIframe($competicion$token)) {
  870.             return new JsonResponse(-1);
  871.         }
  872.         $tipoClasif 0;    //Normal, ExAequo, PlayOff
  873.         $clasificaciones = array();
  874.         $nombresEquipos = array();
  875.         $equipos = array();
  876.         $numJugadores $competicion->getJugadores();
  877.         //Me traigo todas las clasificaciones de esta competicion que sean visibles
  878.         $clasifs $this->em->getRepository(Clasificacion::class)->findBy(["competicion" => $id"publicada" => true], array("orden" => "ASC""id" => "DESC"));
  879.         //Esta es la que sustituye a la anterior cuando se haga bien el menu para que no salga el icono de clasificaicones si no hay ninguna clasificacion visible
  880.         //$clasifs = $this->em->getRepository(Clasificacion::class)->findBy(array("id" => $id, "publicada" => 1), array("id" => "DESC"));
  881.         foreach ($clasifs as $clf) {
  882.             $modalidad = ($numJugadores == || $clf->getModalidad() != "pareja") ? $clf->getModalidad() : "equipo-pareja";
  883.             $posicionAnt 0;
  884.             $classificationCalculation $clf->getCalculo();
  885.             if (empty($classificationCalculation)) {
  886.                 continue; // han llegado errores al correo que segun la base de datos tienen que ser de competiciones antiguas, pero para que no siga
  887.             }
  888.             $classificationId $clf->getId();
  889.             switch ($modalidad) {
  890.                 case "individual":
  891.                     //13/07/2018 Jose: Se saca fuera del for $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasByClasificacion($competicion);
  892.                     //indexamos por clasificacion
  893.                     //Tengo un listado ordenado por clasificaciones, de manera que tengo primero todos los clasificados ordenados de la 1Āŗ clasif, despues la 2Āŗ clasif y asi
  894.                     $clasificaciones[$classificationId] = array("clasificacion" => $clf->getNombre(), "modalidad" => $modalidad"calculo" => $classificationCalculation->getId(), "tipo" => $clf->getTipo(), "clasificados" => array(), "plantilla" => "Frontend:Clasificacion:clasificados_new-torneo-profesional.html.twig""equipos" => array());
  895.                     $listado $this->em->getRepository(Clasificado::class)->getClasificacionIndividualListado($id$classificationCalculation->getId(), $classificationId);
  896.                     foreach ($listado as $elemento) {
  897.                         //El listado me repite el jugador para la siguiente jornada, me aprovecho de eso
  898.                         //Al estar indexado, no repito los datos del jugador
  899.                         if ($posicionAnt != $elemento["posicion"]) {
  900.                             $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]] = array("idi" => $elemento["idi"], "nombre" => $elemento["nombre"], "apellidos" => $elemento["apellidos"], "licencia" => $elemento["licencia"], "nacimiento" => $elemento["nacimiento"], "hcp" => $elemento["hcp"], "nivel" => $elemento["nivel"], "jornadas" => array());
  901.                             $posicionAnt $elemento["posicion"];
  902.                         }
  903.                         //Como estoy indexando arrays y no necesito repetir el jugador, aƱado tantas jornadas con sus resultados como necesite para ese jugador
  904.                         $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]]["jornadas"][$elemento["jornada"]] = array(
  905.                             "bruto" => $elemento["bruto"],
  906.                             "neto" => $elemento["neto"],
  907.                             "contrapar" => $elemento["contrapar"],
  908.                             "ide" => $elemento["ide"],
  909.                             "penalidad" => $elemento["penalidad"],
  910.                             "hcpJuego" => $elemento["hcpJuego"],
  911.                             "especial" => $elemento["especial"]
  912.                         );
  913.                     }
  914.                     break;
  915.                 case "equipo-pareja":
  916.                     //caso inscritos equipo clasificacion parejas. La plantilla puede ser la de equipo y parejas
  917.                     $esEquipo false;
  918.                     //13/07/2018 Jose: Se saca fuera del for $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasByClasificacionCouple($competicion, $esEquipo);
  919.                     //Tengo un listado ordenado por clasificaciones, de manera que tengo primero todos los clasificados ordenados de la 1Āŗ clasif, despues la 2Āŗ clasif y asi
  920.                     $clasificaciones[$classificationId] = array("clasificacion" => $clf->getNombre(), "modalidad" => $modalidad"calculo" => $classificationCalculation->getId(), "tipo" => $clf->getTipo(), "clasificados" => array(), "plantilla" => "Frontend:Clasificacion:clasificadosParejasEquipos_new-torneo.html.twig");
  921.                     $listado $this->em->getRepository(Clasificado::class)->getClasificacionParejaListado($id$competicion->getCalculo()->getId(), $classificationId);
  922.                     foreach ($listado as $elemento) {
  923.                         //El listado me repite el jugador para la siguiente jornada, me aprovecho de eso
  924.                         //Al estar indexado, no repito los datos del jugador
  925.                         if ($posicionAnt != $elemento["posicion"]) {
  926.                             $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]] = array("equipo" => $elemento["equipo"], "pareja" => $elemento["pareja"], "jornadas" => array());
  927.                             $posicionAnt $elemento["posicion"];
  928.                         }
  929.                         //Como estoy indexando arrays y no necesito repetir el jugador, aƱado tantas jornadas con sus resultados como necesite para ese jugador
  930.                         $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]]["jornadas"][$elemento["jornada"]] = array(
  931.                             "bruto" => $elemento["bruto"],
  932.                             "neto" => $elemento["neto"],
  933.                             "contrapar" => $elemento["contrapar"],
  934.                             "ide" => $elemento["ide"],
  935.                             "especial" => $elemento["especial"]
  936.                         );
  937.                     }
  938.                     $equipos = array();
  939.                     //$nombresEquipos = array();
  940.                     $equiposAux $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($competicion);
  941.                     foreach ($equiposAux as $equipo) {
  942.                         $indice $equipo->getEquipo() . "-" $equipo->getPareja();
  943.                         if (!isset($equipos[$indice])) {
  944.                             $equipos[$indice] = array();
  945.                             $nombresEquipos[$indice] = $equipo->getNombreEquipo();
  946.                         }
  947.                         $jugador $equipo->getJugador();
  948.                         $equipos[$indice][] = array(
  949.                             "idi" => $equipo->getId(),
  950.                             "nombre" => $jugador->getNombre(),
  951.                             "apellidos" => $jugador->getApellidos(),
  952.                             "licencia" => $jugador->getLicencia(),
  953.                             "nacimiento" => $jugador->getFecha(),
  954.                             "hcp" => $equipo->getHcp(),
  955.                             "nivel" => (!is_null($equipo->getNivel())) ? $equipo->getNivel()->getId() : "M"
  956.                         );
  957.                     }
  958.                     $clasificaciones[$classificationId]["equipos"] = $equipos;
  959.                     break;
  960.                 default:
  961.                     //caso inscritos equipo clasificacion equipo
  962.                     //caso inscritos parejas clasificacion parejas
  963.                     $equipos = array();
  964.                     $esEquipo = ($competicion->getJugadores() > 2);
  965.                     //13/07/2018 Jose: Se saca fuera del for $njornadasAux = $this->em->getRepository(Clasificado::class)->getJornadasByClasificacionCouple($competicion, $esEquipo);
  966.                     //Tengo un listado ordenado por clasificaciones, de manera que tengo primero todos los clasificados ordenados de la 1Āŗ clasif, despues la 2Āŗ clasif y asi
  967.                     $clasificaciones[$classificationId] = array("clasificacion" => $clf->getNombre(), "modalidad" => $modalidad"calculo" => $classificationCalculation->getId(), "tipo" => $clf->getTipo(), "clasificados" => array(), "plantilla" => "Frontend:Clasificacion:clasificadosParejasEquipos_new-torneo.html.twig");
  968.                     $listado $this->em->getRepository(Clasificado::class)->getClasificacionParejaListado($id$competicion->getCalculo()->getId(), $classificationId);
  969.                     foreach ($listado as $elemento) {
  970.                         //El listado me repite el jugador para la siguiente jornada, me aprovecho de eso
  971.                         //Al estar indexado, no repito los datos del jugador
  972.                         if ($posicionAnt != $elemento["posicion"]) {
  973.                             $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]] = array("equipo" => $elemento["equipo"], "equipoId" => $elemento["equipoId"], "pareja" => $elemento["pareja"], "jornadas" => array());
  974.                             $posicionAnt $elemento["posicion"];
  975.                         }
  976.                         //Como estoy indexando arrays y no necesito repetir el jugador, aƱado tantas jornadas con sus resultados como necesite para ese jugador
  977.                         $clasificaciones[$classificationId]["clasificados"][$elemento["posicion"]]["jornadas"][$elemento["jornada"]] = array(
  978.                             "bruto" => $elemento["bruto"],
  979.                             "neto" => $elemento["neto"],
  980.                             "contrapar" => $elemento["contrapar"],
  981.                             "ide" => $elemento["ide"],
  982.                             "especial" => $elemento["especial"]
  983.                         );
  984.                         //Para una competicion de equipos (clasif de equipos) ha ocurrido que (supongo con logica) ha publicado las clasificaciones con pareja = 0,
  985.                         //entocnes a la hora de buscar por equipo-pareja no encuentra los miembros, por lo que no los pintaba en el listado
  986.                         //Si filtramos de manera que si pareja = 0 coja todos los miembros del equipo, ya los debe de pintar
  987.                         if ($elemento["equipoId"]) {
  988.                             if ($elemento["pareja"] != 0) {
  989.                                 $miembros $this->em->getRepository(Inscrito::class)->getParejaByEquipoEntidad($elemento["pareja"], $elemento["equipoId"]);
  990.                             } else {
  991.                                 $miembros $this->em->getRepository(Inscrito::class)->findBy(["estado" => "pagado""equipo_entidad" => $elemento["equipoId"]]);
  992.                             }
  993.                             $indice $elemento["equipoId"];
  994.                         } else {
  995.                             if ($elemento["pareja"] != 0) {
  996.                                 $miembros $this->em->getRepository(Inscrito::class)->getInscritosParejaCompeticion($competicion->getId(), $elemento["pareja"], $elemento["equipo"]);
  997.                             } else {
  998.                                 $miembros $this->em->getRepository(Inscrito::class)->findBy(["estado" => "pagado""equipo" => $elemento["equipo"], "pareja" => $elemento["pareja"], "competicion" => $competicion]);
  999.                             }
  1000.                             $indice $elemento["equipo"] . "-" $elemento["pareja"];
  1001.                         }
  1002.                         foreach ($miembros as $miembro) {
  1003.                             $jugador $miembro->getJugador();
  1004.                             $mid $miembro->getId();
  1005.                             $equipos[$indice][$mid] = array(//indexamos el miembro por Id de inscrito para evitar que duplique, que es lo que ocurria
  1006.                                 "idi" => $mid,
  1007.                                 "nombre" => $jugador->getNombre(),
  1008.                                 "apellidos" => $jugador->getApellidos(),
  1009.                                 "licencia" => $jugador->getLicencia(),
  1010.                                 "nacimiento" => $jugador->getFecha(),
  1011.                                 "hcp" => $miembro->getHcp(),
  1012.                                 "pais" => (!is_null($jugador->getPais())) ? $jugador->getPais()->getId() : "EX",
  1013.                                 "nivel" => (!is_null($miembro->getNivel())) ? $miembro->getNivel()->getId() : "M"
  1014.                             );
  1015.                         }
  1016.                     }
  1017.                     //$nombresEquipos = array();
  1018.                     //$equiposEntidadAux = $this->em->getRepository(Equipo::class)->findEquiposEnClasificacion($clf->getId());
  1019.                     //$equiposAux = $this->em->getRepository(Inscrito::class)->getPlayersParejasByCompeticion($id);
  1020.                     /* if (count($equiposEntidadAux) > 1) { //26/07/2018 Jose: Si hay equipos de la entidad nueva se hace mas facil
  1021.                       foreach ($equiposEntidadAux as $idAux) {
  1022.                       $equipo = $this->em->getRepository(Equipo::class)->find($idAux[1]); //Tengo que hacer el "[1]" por como lo devuelve la query.
  1023.                       $indice = $equipo->getEquipo();
  1024.                       if (!isset($equipos[$indice])) {
  1025.                       $equipos[$indice] = array();
  1026.                       $nombresEquipos[$indice] = $equipo->getNombre();
  1027.                       }
  1028.                       foreach ($equipo->getInscritos() as $inscrito) {
  1029.                       $jugador = $inscrito->getJugador();
  1030.                       $equipos[$indice][] = array(
  1031.                       "idi" => $inscrito->getId(),
  1032.                       "nombre" => $jugador->getNombre(),
  1033.                       "apellidos" => $jugador->getApellidos(),
  1034.                       "licencia" => $jugador->getLicencia(),
  1035.                       "hcp" => $inscrito->getHcp(),
  1036.                       "nivel" => (!is_null($inscrito->getNivel())) ? $inscrito->getNivel()->getId() : "M"
  1037.                       );
  1038.                       }
  1039.                       }
  1040.                       } else {
  1041.                      */
  1042.                     /* foreach ($equiposAux as $equipo) {//"equipo" es inscrito
  1043.                       if (!$esEquipo) {
  1044.                       $indice = $equipo->getPareja();
  1045.                       } else {
  1046.                       $indice = $equipo->getEquipo();
  1047.                       }
  1048.                       if (!isset($equipos[$indice])) {
  1049.                       $equipos[$indice] = array();
  1050.                       $nombresEquipos[$indice] = $equipo->getNombreEquipo();
  1051.                       }
  1052.                       $jugador = $equipo->getJugador();
  1053.                       $equipos[$indice][] = array(
  1054.                       "idi" => $equipo->getId(),
  1055.                       "nombre" => $jugador->getNombre(),
  1056.                       "apellidos" => $jugador->getApellidos(),
  1057.                       "licencia" => $jugador->getLicencia(),
  1058.                       "nacimiento" => $jugador->getFecha(),
  1059.                       "hcp" => $equipo->getHcp(),
  1060.                       "nivel" => (!is_null($equipo->getNivel())) ? $equipo->getNivel()->getId() : "M"
  1061.                       );
  1062.                       } */
  1063.                     $equiposEntity $this->em->getRepository(Equipo::class)->findEquiposParticipantesTodos($competicion);
  1064.                     if ($equiposEntity) {
  1065.                         foreach ($equiposEntity as $equipo) {
  1066.                             $nombresEquipos[$equipo->getEquipo()] = $equipo->getNombre();
  1067.                         }
  1068.                     }
  1069.                     //}
  1070.                     $clasificaciones[$classificationId]["equipos"] = $equipos;
  1071.                     break;
  1072.             }
  1073.             $clasificaciones[$classificationId]["posicion_corte"] = $clf->getPosicionCorte();
  1074.             $clasificaciones[$classificationId]["etiqueta_corte"] = $clf->getEtiquetaCorte();
  1075.         }
  1076.         //13/07/2018 Jose: Se hace aqui porque no hay que calcularlo dentro de cada clasificacion
  1077.         $njornadasAux $this->em->getRepository(Clasificado::class)->getJornadasClasificacionByCompeticion($competicion);
  1078.         //Busco cuantas jornadas tiene cada clasificacion, lo necesito para la cabecera de las tablas
  1079.         $njornadas = array();
  1080.         foreach ($njornadasAux as $nja) {
  1081.             $njornadas[$nja['id']] = $nja['contador'];
  1082.         }
  1083.         // $zonasneutras = [];
  1084.         // $bajadas = [];
  1085.         // $znsAux = $this->em->getRepository(ZonaNeutra::class)->findBy([], ["tipoPrueba" => "ASC", "campoCorto" => "ASC", "son18hoyos" => "ASC", "categoria" => "ASC"]);
  1086.         // foreach ($znsAux as $zn) {
  1087.         //     $zonasneutras[$zn->getTipoPrueba()][intval($zn->getCampoCorto())][intval($zn->getSon18hoyos())][$zn->getCategoria()->getId()] = ['max' => $zn->getPuntosMax(), 'min' => $zn->getPuntosMin(), 'subida' => $zn->getSubidaInferiorZn()];
  1088.         // }
  1089.         // $bajadasAux = $this->em->getRepository(Bajada::class)->findBy([], array('tipoPrueba' => 'ASC', 'campoCorto' => 'ASC', 'categoria' => 'ASC', 'puntos' => 'ASC'));
  1090.         // foreach ($bajadasAux as $b) {
  1091.         //     $bajadas[$b->getTipoPrueba()][intval($b->getCampoCorto())][$b->getCategoria()->getId()][$b->getPuntos()] = $b->getBajada();
  1092.         // }
  1093.         // $categoriasHcp = $this->em->getRepository(CategoriaHandicap::class)->findAll();
  1094.         return $this->render("frontend/Clasificacion/clasificacion_base.html.twig", [
  1095.             'clasificaciones' => $clasificaciones,
  1096.             'competicion' => $competicion,
  1097.             'njornadas' => $njornadas,
  1098.             'numJugadores' => $numJugadores,
  1099.             'equipos' => $equipos,
  1100.             'nombresEquipos' => $nombresEquipos,
  1101.             'tipoClasif' => $tipoClasif,
  1102.             //            "zonasneutras" => $zonasneutras,
  1103.             //            "bajadas" => $bajadas,
  1104.             //            "categoriasHcp" => $categoriasHcp,
  1105.         ]);
  1106.     }
  1107.     /**
  1108.      * F-037 Listado ordenado de resultados hasta un hoyo concreto
  1109.      *
  1110.      * @Route("/getListadoDinamicoClasificacion", name="listado_dinamico", options={"expose"=true})
  1111.      *
  1112.      */
  1113.     public function listadoClasificacionDinamico(Request $request)
  1114.     {
  1115.         $id $request->request->get("id"0);
  1116.         $token $request->request->get("token"null);
  1117.         //comprobar competicion.
  1118.         $competicion $this->em->getRepository(Competicion::class)->find($id);
  1119.         if (!$competicion) {
  1120.             return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", array('listado' => []));
  1121.         }
  1122.         if (!$this->util->checkTokenValidIframe($competicion$token)) {
  1123.             return new JsonResponse(-1);
  1124.         }
  1125.         $nJor $this->em->getRepository(Jornada::class)->getCountPorCompeticion($competicion);
  1126.         $clasificacionId $request->request->get("clasificacion");
  1127.         $clasificacion $this->em->getRepository(Clasificacion::class)->find($clasificacionId);
  1128.         if (is_null($clasificacion)) {
  1129.             return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", array('listado' => []));
  1130.         }
  1131.         $orden $request->request->get("orden"$nJor);
  1132.         $jornada $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion'orden' => intval($orden)));
  1133.         if (!$jornada) {
  1134.             return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", array('listado' => []));
  1135.         }
  1136.         $hoyo $request->request->get("hoyo"18);
  1137.         $inscritos $this->em->getRepository(Inscrito::class)->getPlayersByCompeticion($competicion);
  1138.         foreach ($inscritos as $inscrito) {
  1139.             $hcpJuego unserialize($inscrito->getHcpJuego());
  1140.             if (isset($hcpJuego[$jornada->getId()])) {
  1141.                 $hcpJuegoJornada $hcpJuego[$jornada->getId()];
  1142.                 $hcpJuegoNuevaTabla $this->em->getRepository(HcpJuego::class)->findOneBy(array('jornada' => $jornada'inscrito' => $inscrito));
  1143.                 if (is_null($hcpJuegoNuevaTabla)) {
  1144.                     $hcpJuegoNuevaTabla = new HcpJuego();
  1145.                     $hcpJuegoNuevaTabla->setHcp($hcpJuegoJornada);
  1146.                     $hcpJuegoNuevaTabla->setInscrito($inscrito);
  1147.                     $hcpJuegoNuevaTabla->setJornada($jornada);
  1148.                     $this->em->persist($hcpJuegoNuevaTabla);
  1149.                     $this->em->flush();
  1150.                 }
  1151.             }
  1152.         }
  1153.         //Si es individual o si es Four Ball o Canada que se guarda tambiĆ©n la tarjeta individual del jugador.
  1154.         if ($clasificacion->getModalidad() == "individual" || $jornada->getModalidad()->getId() == "P" || $jornada->getModalidad()->getId() == "C") {
  1155.             $listado $this->em->getRepository(Resultado::class)->getListadoAcumuladoHoyos($clasificacion->getId(), $jornadaintval($hoyo), $clasificacion->getCalculo()->getId(), $competicion->getFormula()->getId());
  1156.         } else {
  1157.             /*
  1158.              * Habria que hacer la query para clasificar individualmente a los miembros de la pareja en caso de haberse hecho una clasificacion individual de una Xsome.
  1159.              */
  1160.         }
  1161.         return $this->render("frontend/Clasificacion/clasificacionListadoDinamico.html.twig", [
  1162.             'listado' => $listado,
  1163.             'hoyo' => $hoyo,
  1164.             'competicion' => $competicion,
  1165.             'njornadas' => $nJor,
  1166.             'clasificacion' => $clasificacion,
  1167.             'orden' => $orden
  1168.         ]);
  1169.     }
  1170.     /**
  1171.      * F-038 Listado ordenado de resultados de parejas hasta un hoyo concreto variable
  1172.      *
  1173.      * @Route("/getListadoDinamicoClasificacionPareja", name="listado_dinamico_pareja", options={"expose"=true})
  1174.      *
  1175.      */
  1176.     public function listadoClasificacionDinamicoPareja(Request $request)
  1177.     {
  1178.         $id $request->request->get("id");
  1179.         //comprobar competicion.
  1180.         $competicion $this->em->getRepository(Competicion::class)->findOneById($id);
  1181.         if (!$competicion) {
  1182.             return new JsonResponse(-1);
  1183.         }
  1184.         $nJor $this->em->getRepository(Jornada::class)->getCountPorCompeticion($competicion);
  1185.         $numJugadores $competicion->getJugadores();
  1186.         $clasificacionId $request->request->get("clasificacion");
  1187.         $clasificacion $this->em->getRepository(Clasificacion::class)->findOneById($clasificacionId);
  1188.         if (is_null($clasificacion)) {
  1189.             return new JsonResponse(-1);
  1190.         }
  1191.         $orden $request->request->get("orden");
  1192.         if (is_null($orden)) {
  1193.             $orden $nJor;
  1194.         }
  1195.         $jornada $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion'orden' => intval($orden)));
  1196.         if (!$jornada) {
  1197.             return new JsonResponse(-1);
  1198.         }
  1199.         $hoyo $request->request->get("hoyo"18);
  1200.         $inscritos $this->em->getRepository(Inscrito::class)->getPlayersByCompeticion($competicion);
  1201.         $nombresEquipos = array();
  1202.         foreach ($inscritos as $inscrito) {
  1203.             $hcpJuego unserialize($inscrito->getHcpJuego());
  1204.             if (isset($hcpJuego[$jornada->getId()])) {
  1205.                 $hcpJuegoJornada $hcpJuego[$jornada->getId()];
  1206.                 $hcpJuegoNuevaTabla $this->em->getRepository(HcpJuego::class)->findOneBy(array('jornada' => $jornada'inscrito' => $inscrito));
  1207.                 if (is_null($hcpJuegoNuevaTabla)) {
  1208.                     $hcpJuegoNuevaTabla = new HcpJuego();
  1209.                     $hcpJuegoNuevaTabla->setHcp($hcpJuegoJornada);
  1210.                     $hcpJuegoNuevaTabla->setInscrito($inscrito);
  1211.                     $hcpJuegoNuevaTabla->setJornada($jornada);
  1212.                     $this->em->persist($hcpJuegoNuevaTabla);
  1213.                     $this->em->flush();
  1214.                 }
  1215.             }
  1216.             if ($numJugadores != 2) {
  1217.                 if (!isset($nombresEquipos[$inscrito->getEquipo()])) {
  1218.                     $nombresEquipos[$inscrito->getEquipo()] = $inscrito->getNombreEquipo();
  1219.                 }
  1220.             }
  1221.         }
  1222.         if ($clasificacion->getModalidad() == "pareja" || $clasificacion->getModalidad() == "equipo") {
  1223.             $listado $this->em->getRepository(Resultado::class)->getAcumuladoHoyosEquipo($clasificacion->getId(), $jornadaintval($hoyo), $clasificacion->getCalculo()->getId());
  1224.         } else {
  1225.             /*
  1226.              * Habria que hacer la query para buscar la suma de cada miembro de la pareja.
  1227.              */
  1228.         }
  1229.         $datosJugadores = array();
  1230.         foreach ($listado as $equipo) {
  1231.             $datosJugadores[$equipo["equipo"]] = $this->em->getRepository(Inscrito::class)->getDatosHcpJuegoByEquipo($equipo["equipo"], $jornada);
  1232.         }
  1233.         return $this->render("frontend/Clasificacion/clasificacionListadoDinamicoPareja.html.twig", array(
  1234.             'listado' => $listado,
  1235.             'datosJugadores' => $datosJugadores,
  1236.             'hoyo' => $hoyo,
  1237.             'competicion' => $competicion,
  1238.             'njornadas' => $nJor,
  1239.             'clasificacion' => $clasificacion,
  1240.             'numJugadores' => $numJugadores,
  1241.             'nombresEquipos' => $nombresEquipos,
  1242.             'orden' => $orden
  1243.         ));
  1244.     }
  1245.     /**
  1246.      * F-052 Verificacion del captcha
  1247.      *
  1248.      * @param type $recaptcha
  1249.      * @return type
  1250.      *
  1251.      */
  1252.     function captchaverify($recaptcha)
  1253.     {
  1254.         $url "https://www.google.com/recaptcha/api/siteverify";
  1255.         $ch curl_init();
  1256.         curl_setopt($chCURLOPT_URL$url);
  1257.         curl_setopt($chCURLOPT_HEADER0);
  1258.         curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
  1259.         curl_setopt($chCURLOPT_POSTtrue);
  1260.         curl_setopt($chCURLOPT_POSTFIELDS, array(
  1261.             "secret" => "6Ld1hVIUAAAAAPgO50zNtsjjVDmorOUMwMCf8J_U""response" => $recaptcha));
  1262.         $response curl_exec($ch);
  1263.         curl_close($ch);
  1264.         $data json_decode($response);
  1265.         return $data->success;
  1266.     }
  1267.     /**
  1268.      * F-060 Estadisticas de una partida tras haber sido jugada [EN DESUSO]
  1269.      *
  1270.      * @Route("/match/{token}/{publi}", name="_match", options={"expose"=true}, defaults={"publi" = 0})
  1271.      */
  1272.     public function partidaInscrito($token$publi)
  1273.     {
  1274.         // TODO: COMPROBAR QUE ESTƉ EN DESUSO Y ELIMINAR O RECUPERAR EN TAL CASO
  1275.         $i 0;
  1276.         $enc false;
  1277.         $partidas $this->em->getRepository(PartidaHorario::class)->findByToken($token);
  1278.         $tam count($partidas);
  1279.         while ($i $tam && !$enc) {
  1280.             $partida $partidas[$i];
  1281.             $enc = (strcmp($partida->getToken(), $token) == 0); //buscamos la partida exacta (antes habia un findoneby pero es caseinsensitive, por lo que no nos vale)
  1282.             $i++;
  1283.         }
  1284.         if (!$enc) {
  1285.             $this->addFlash('error'"No existe la partida");
  1286.             return $this->redirect($this->generateUrl('competiciones_comite'));
  1287.         }
  1288.         $jornada $partida->getHorario()->getJornada();     //Cuidado si horario es nulo porque no exista $partida
  1289.         if (!$jornada) {
  1290.             $this->addFlash('error'"No existe la Jornada");
  1291.             return $this->redirect($this->generateUrl('competiciones_comite'));
  1292.         }
  1293.         //Deshabilitamos el filtro del softdelete, ya que como no tenemos el ID de la competicion no podemos hacer su busqueda explicita para la comprobacion,
  1294.         //Al deshabilitarse la competicion va a existir, pero va a estar marcado el softdelete, por lo que si es asĆ­, avisamos de que estĆ” borrada
  1295.         $this->em->getFilters()->disable('softdeleteable');
  1296.         $competicion $jornada->getCompeticion();
  1297.         if (!$competicion || !is_null($competicion->getDeletedAt())) {
  1298.             $this->addFlash('error''No se ha encontrado la competición');
  1299.             return $this->redirect($this->generateUrl('competiciones_comite'));
  1300.         }
  1301.         $this->em->getFilters()->enable('softdeleteable');
  1302.         //Si no tenemos resultados, rediigimos a la pagina de frontend
  1303.         if (!$this->em->getRepository(Competicion::class)->hasResultados($competicion->getId())) {
  1304.             $this->addFlash('error''Información de partida aĆŗn no disponible. IntĆ©ntelo mĆ”s tarde');
  1305.             return $this->redirect($this->generateUrl('_tournament', array('id' => $competicion->getId())));
  1306.         }
  1307.         $jornadaId $jornada->getId();
  1308.         $modalidad $jornada->getModalidad()->getId();
  1309.         $jugadoresAux $this->em->getRepository(JugadorHorario::class)->findBy(['partida' => $partida->getId()], ['inscrito' => 'ASC']);     //ordenamos por ID inscrito para mantener siempre el orden
  1310.         $equipos = array();
  1311.         $hcpJs = array();
  1312.         $contrapares = array();
  1313.         $resumen = array();
  1314.         $valores = ["eagles" => -2"birdies" => -1"pares" => 0"bogeys" => 1];      //Falta resultado Peor (> +1)
  1315.         $acumulados = ["eagles" => 0"birdies" => 0"pares" => 0"bogeys" => 0"peor" => 0];      //Falta resultado Peor (> +1)
  1316.         //$calculo = ($competicion->getCalculo()->getId() == "H" ? "Hcp" : "Scratch" );
  1317.         //Si es medal play es susceptible de no tener los contrapares
  1318.         //Por lo tanto preparamos los datos que nos hacen falta
  1319.         if ($competicion->getFormula()->getId() == 'M') {
  1320.             $jcs $this->em->getRepository(JornadaConfig::class)->findByJornada($jornada);
  1321.             $hoyosDatos = array();
  1322.             $hoyosDatosAux = array();
  1323.             foreach ($jcs as $jc) {
  1324.                 $jconfig_cat $jc->getCategoria()->getId();
  1325.                 $cc $this->em->getRepository(CategoriaConfig::class)->findOneByCategoria($jconfig_cat);
  1326.                 if ($cc->getSexo() == "" || $cc->getSexo() == "sin especificar") {
  1327.                     $cc->setSexo('masculino');
  1328.                 }
  1329.                 $hoyosDatosAux $this->em->getRepository(Trazado::class)->findDatosHoyoByTrazado($jornada->getTrazado()->getNumero(), $jc->getBarra()->getId(), $cc->getSexo());
  1330.                 foreach ($hoyosDatosAux as $h) {
  1331.                     $hoyosDatos[$cc->getSexo()][$jconfig_cat][$h["numero"]] = $h;
  1332.                 }
  1333.             }
  1334.         }
  1335.         if ($modalidad == "I") {
  1336.             //AƱadido para calculo de contrapares que no tengamos todavia de medal play.
  1337.             if ($jornada->getCompeticion()->getFormula()->getId() == 'M') {
  1338.                 foreach ($jugadoresAux as $h) {
  1339.                     $insc $h->getInscrito();
  1340.                     $inscId $insc->getId();
  1341.                     $resultados $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId"inscrito" => $inscId], ['hoyo' => 'ASC']);
  1342.                     foreach ($resultados as $r) {
  1343.                         if (is_null($r->getContraparScratch())) {
  1344.                             $par $hoyosDatos[$insc->getJugador()->getSexo()][$insc->getCategoria()->getId()][$r->getHoyo()]["par"];
  1345.                             $r->setContraparScratch($r->getScratch() - $par);
  1346.                             $r->setContraparHcp($r->getHcp() - $par);
  1347.                         }
  1348.                     }
  1349.                 }
  1350.                 $this->em->flush();
  1351.             }
  1352.             foreach ($jugadoresAux as $h) {
  1353.                 $insc $h->getInscrito();
  1354.                 $inscId $insc->getId();
  1355.                 $jorConfig $this->em->getRepository(JornadaConfig::class)->findOneBy(["jornada" => $jornadaId"categoria" => $insc->getCategoria()]);
  1356.                 $tipo_hoyos $jorConfig->getHoyos();
  1357.                 $limits explode('-'$tipo_hoyos);
  1358.                 $esp $this->em->getRepository(Resultado::class)->findResultadoEspecial($inscId$jornadaId);   //buscamos si tiene resultado especial para no incluirlo
  1359.                 if (!$esp) {
  1360.                     $hoyos array_fill($limits[0], ($limits[1] - $limits[0]) + 1true);
  1361.                     $hcpJs[$inscId] = $this->em->getRepository(HcpJuego::class)->findOneByInscrito($insc);
  1362.                     foreach ($valores as $k => $v) {
  1363.                         $resultados $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId"inscrito" => $inscId"contrapar_scratch" => $v], ['hoyo' => 'ASC']);
  1364.                         $valor count($resultados);
  1365.                         $contrapares[$inscId][$k] = $valor;
  1366.                         $acumulados[$k] += $valor;
  1367.                         $resumen[$inscId][$k] = [];
  1368.                         foreach ($resultados as $resu) {
  1369.                             $resumen[$inscId][$k][] = $resu->getHoyo();
  1370.                             //eliminamos el hoyo, para saber cuales nos quedan sin usar, esos seran los resultados peores (ya que no son ni par, ni eagle, ni birdie ni bogey)
  1371.                             unset($hoyos[$resu->getHoyo()]);
  1372.                         }
  1373.                     }
  1374.                     //Lo que nos queda son los resultados peores
  1375.                     $peor count($hoyos);
  1376.                     $contrapares[$inscId]["peor"] = $peor;
  1377.                     $acumulados["peor"] += $peor;
  1378.                     $resumen[$inscId]["peor"] = [];
  1379.                     foreach ($hoyos as $hoyo => $ho) {
  1380.                         $resumen[$inscId]["peor"][] = $hoyo;
  1381.                     }
  1382.                     $jugadores[] = $h;
  1383.                 }
  1384.             }
  1385.         } else {
  1386.             //AƱadido para calculo de contrapares que no tengamos todavia de medal play.
  1387.             if ($jornada->getCompeticion()->getFormula()->getId() == 'M' && in_array($modalidad, ["C""P"])) {
  1388.                 $teams = array();
  1389.                 foreach ($jugadoresAux as $h) {
  1390.                     $equipo $h->getEquipo();
  1391.                     $pareja $h->getPareja();
  1392.                     $teams[$h->getEquipo() . "-" $h->getPareja()] = ["equipo" => $equipo"pareja" => $pareja];
  1393.                     $inscritos $this->em->getRepository(Inscrito::class)->findBy(['equipo' => $equipo'pareja' => $pareja'competicion' => $jornada->getCompeticion()->getId()], ['id' => 'ASC']);
  1394.                     $resultadosMiembros = array();
  1395.                     foreach ($inscritos as $inscrito) {
  1396.                         $resultados $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId"inscrito" => $inscrito->getId()], ['hoyo' => 'ASC']);
  1397.                         foreach ($resultados as $r) {
  1398.                             if (is_null($r->getContraparScratch())) {
  1399.                                 $par $hoyosDatos[$inscrito->getJugador()->getSexo()][$inscrito->getCategoria()->getId()][$r->getHoyo()]["par"];
  1400.                                 $r->setContraparScratch($r->getScratch() - $par);
  1401.                                 $r->setContraparHcp($r->getHcp() - $par);
  1402.                             }
  1403.                         }
  1404.                         array_push($resultadosMiembros$resultados);
  1405.                     }
  1406.                     $resultadosPareja $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId'equipo' => $equipo'pareja' => $pareja], ['hoyo' => 'ASC']);
  1407.                     foreach ($resultadosPareja as $loop => $rp) {
  1408.                         if (is_null($rp->getContraparScratch())) {
  1409.                             $m1 $resultadosMiembros[0][$loop];
  1410.                             $m2 $resultadosMiembros[1][$loop];
  1411.                             if ($modalidad == "C") {
  1412.                                 $rp->setContraparScratch($m1->getContraparScratch() + $m2->getContraparScratch());
  1413.                                 $rp->setContraparHcp($m1->getContraparHcp() + $m2->getContraparHcp());
  1414.                             } elseif ($modalidad == "P") {
  1415.                                 $rp->setContraparScratch(min($m1->getContraparScratch(), $m2->getContraparScratch()));
  1416.                                 $rp->setContraparHcp(min($m1->getContraparHcp(), $m2->getContraparHcp()));
  1417.                             }
  1418.                         }
  1419.                     }
  1420.                 }
  1421.                 $this->em->flush();
  1422.             }
  1423.             foreach ($jugadoresAux as $h) {
  1424.                 $equipo $h->getEquipo();
  1425.                 $pareja $h->getPareja();
  1426.                 $esp $this->em->getRepository(Resultado::class)->findResultadoEspecialEquipoPareja($equipo$pareja$jornadaId);
  1427.                 if (!$esp) {
  1428.                     $jugadores[$equipo "-" $pareja] = "";
  1429.                     $inscritos $this->em->getRepository(Inscrito::class)->findBy(['equipo' => $equipo'pareja' => $pareja'competicion' => $jornada->getCompeticion()->getId()], ['id' => 'ASC']);
  1430.                     foreach ($inscritos as $inscrito) {
  1431.                         $jugadores[$equipo "-" $pareja] .= $inscrito->getJugador()->getNombre() . " - ";
  1432.                     }
  1433.                     $jugadores[$equipo "-" $pareja] = substr($jugadores[$equipo "-" $pareja], 0strlen($jugadores[$equipo "-" $pareja]) - 3);
  1434.                     $jorConfig $this->em->getRepository(JornadaConfig::class)->findOneBy(["jornada" => $jornadaId"categoria" => $inscrito->getCategoria()]);
  1435.                     $tipo_hoyos $jorConfig->getHoyos();
  1436.                     $limits explode('-'$tipo_hoyos);
  1437.                     $hcpJs[$equipo "-" $pareja] = $this->em->getRepository(HcpJuego::class)->findOneBy(['equipo' => $equipo'pareja' => $pareja'jornada' => $jornada->getId()]);
  1438.                     $equipos[$equipo "-" $pareja] = $this->em->getRepository(Inscrito::class)->findOneBy(['equipo' => $equipo'pareja' => $pareja'competicion' => $competicion->getId()]);
  1439.                     $hoyos array_fill($limits[0], ($limits[1] - $limits[0]) + 1true);
  1440.                     //Calculo de los detalles por hoyo
  1441.                     foreach ($valores as $k => $v) {
  1442.                         $resultados $this->em->getRepository(Resultado::class)->findBy(["jornada" => $jornadaId'equipo' => $equipo'pareja' => $pareja"contrapar_scratch" => $v], ['hoyo' => 'ASC']);
  1443.                         $valor count($resultados);
  1444.                         $contrapares[$equipo "-" $pareja][$k] = $valor;
  1445.                         $acumulados[$k] += $valor;
  1446.                         $resumen[$equipo "-" $pareja][$k] = [];
  1447.                         foreach ($resultados as $resu) {
  1448.                             $resumen[$equipo "-" $pareja][$k][] = $resu->getHoyo();
  1449.                             //eliminamos el hoyo, para saber cuales nos quedan sin usar, esos seran los resultados peores (ya que no son ni par, ni eagle, ni birdie ni bogey)
  1450.                             unset($hoyos[$resu->getHoyo()]);
  1451.                         }
  1452.                     }
  1453.                     //Lo que nos queda son los resultados peores
  1454.                     $peor count($hoyos);
  1455.                     $contrapares[$equipo "-" $pareja]["peor"] = $peor;
  1456.                     $acumulados["peor"] += $peor;
  1457.                     $resumen[$equipo "-" $pareja]["peor"] = [];
  1458.                     foreach ($hoyos as $hoyo => $ho) {
  1459.                         $resumen[$equipo "-" $pareja]["peor"][] = $hoyo;
  1460.                     }
  1461.                 }
  1462.             }
  1463.         }
  1464.         // 2023/08/07 esto esta obsoleto a dia de hoy (deberia haberse ocultado en 2023/05/08)
  1465.         // $url = $this->util->acortarUrl('_match', array('token' => $token));
  1466.         return $this->render("frontend/Competicion/match.html.twig", [
  1467.             'competicion' => $competicion,
  1468.             'jugadores' => $jugadores,
  1469.             'hcpJs' => $hcpJs,
  1470.             'equipos' => $equipos,
  1471.             'ccc' => $publi,
  1472.             'contrapares' => $contrapares,
  1473.             'acumulados' => $acumulados,
  1474.             'resumen' => $resumen,
  1475.             'partida' => $partida,
  1476.             // 'url'         => $url,
  1477.             'modalidad' => $modalidad,
  1478.             'limits' => $limits
  1479.         ]);
  1480.     }
  1481.     /**
  1482.      * F-062
  1483.      *
  1484.      * @Route("/pago/{idi}/tpv/{idp}", name="pago_tpv")
  1485.      */
  1486.     public function tpv($idi$idpRequest $request)
  1487.     {
  1488.         $params = array();
  1489.         $inscrito $this->em->getRepository(Inscrito::class)->find($idi);
  1490.         if (!$inscrito) {
  1491.             throw new NotFoundHttpException("No existe el inscrito");
  1492.         }
  1493.         $competicion $inscrito->getCompeticion();
  1494.         if (!$competicion) {
  1495.             $this->addFlash(
  1496.                 'error'"El torneo buscado no existe");
  1497.             return $this->redirect($this->generateUrl('competiciones_abiertas'));
  1498.         }
  1499.         $pedido $this->em->getRepository(Pedido::class)->find($idp);
  1500.         if (!$pedido) {
  1501.             //poner que redirija a competicion en un mensaje de esos flash
  1502.             //y que ponga el inscrito y el pedido a "Error"
  1503.             throw new NotFoundHttpException("No existe el pedido asociado a la inscripcion");
  1504.         }
  1505.         $secret $this->getParameter('secret');
  1506.         $redsys = new RedsysAPI();
  1507.         $redsys->setParameter("DS_MERCHANT_AMOUNT"intval(number_format($pedido->getImporte() * 1000"""")));
  1508.         $redsys->setParameter("DS_MERCHANT_ORDER"strval($inscrito->getPedido()->getNumero()));
  1509.         $redsys->setParameter("DS_MERCHANT_CURRENCY"$this->getParameter('tpv.currency'));
  1510.         $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE"0);        //0 = Pago
  1511.         /*
  1512.           if (strpos($competicion->getOrganizador()->getId(), "AM") !== false) {
  1513.           $usuario = $this->em->getRepository(User::class)->findOneByUsername("AM00");
  1514.           } else {
  1515.           $usuario = $this->em->getRepository(User::class)->findOneByUsername($competicion->getOrganizador()->getId());
  1516.           }
  1517.          */
  1518.         $fechaTPVDesprosa = new \DateTime("2021-04-20 10:00:00");    //Desprosa es el nombre de la empresa y 20 de mayo es cuando se hizo este codigo
  1519.         $fechaTPVSherry = new \DateTime("2022-03-14 00:00:00");      //Aunque el cambio se hace el dia 09/03/2022, hay competiciones abiertas hasta el dia 12, por lo que se espera a que se cierren
  1520.         $fechaTPVAlhaurin = new \DateTime("2023-05-19 00:00:00");      //Peticion de la solicitud
  1521.         $idComp $competicion->getId();
  1522.         //El pago, lo hace LV05 o CM81 o lo hacemos con nuestra pasarela
  1523.         //IMportante!!! En la configuracion del TPV (en la web del redsys) debe de aparecer como "Asincrona"
  1524.         $orgnzdr "AM00";
  1525.         switch (trim($competicion->getOrganizador()->getId())) {
  1526.             case "LV05":
  1527.                 $orgnzdr "LV05";
  1528.                 break;
  1529.             case "GALN":
  1530.                 $orgnzdr "GALN";
  1531.                 break;
  1532.             case "CMC8":
  1533.                 $orgnzdr "CMC8";
  1534.                 if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1535.                     $orgnzdr "AM00";
  1536.                 }
  1537.                 break;
  1538.             case "CM81":
  1539.                 $orgnzdr "CM81";
  1540.                 if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1541.                     $orgnzdr "AM00";
  1542.                 }
  1543.                 break;
  1544.             case "AM15":
  1545.                 $orgnzdr "AM15";
  1546.                 if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1547.                     $orgnzdr "AM00";
  1548.                 }
  1549.                 break;
  1550.             case "AMC3":
  1551.                 $orgnzdr "AMC3";
  1552.                 if ($competicion->getInicio()->format("U") < $fechaTPVSherry->format("U")) {
  1553.                     $orgnzdr "AM00";
  1554.                 }
  1555.                 break;
  1556.             case "AM22":
  1557.                 $orgnzdr "AM22";
  1558.                 if ($competicion->getInicio()->format("U") < $fechaTPVAlhaurin->format("U")) {
  1559.                     $orgnzdr "AM00";
  1560.                 }
  1561.                 break;
  1562.             default:
  1563.                 $orgnzdr "AM00";
  1564.                 break;
  1565.         }
  1566.         $usuario $this->em->getRepository(User::class)->findOneByUsername($orgnzdr);
  1567.         $usuarioTpv $usuario->getTpv();
  1568.         $merchantCode $redsys->merchantCodeFromUser($usuarioTpv$secret);
  1569.         $terminal $redsys->terminalFromUser($usuarioTpv$secret);
  1570.         $redsys->setParameter("DS_MERCHANT_MERCHANTCODE"$merchantCode);
  1571.         $redsys->setParameter("DS_MERCHANT_TERMINAL"$terminal);
  1572.         $params['Ds_Merchant_KEY_256'] = $redsys->keyFromUser($usuarioTpv$secret); //Key de REAL del TPV correspondiente
  1573.         //lineas originales
  1574.         //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_test_256');   //Key de TEST.
  1575.         //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_256');   //Key de REAL. Codigo antiguo
  1576.         //$redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $this->getParameter('tpv.merchant_code'));
  1577.         //$redsys->setParameter("DS_MERCHANT_TERMINAL", $this->getParameter('tpv.terminal'));
  1578.         //$dire = str_replace("https", "http", $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL));   //Como el SSL de la pagina es Lets encrypt y el banco no lo admite, tenemos que hacerlo por HTTP, y no por HTTPS para evitar errores
  1579.         $dire $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  1580.         $redsys->setParameter("DS_MERCHANT_MERCHANTURL"$dire);    //URL de mi pagina para procesar el pago
  1581.         //$redsys->setParameter("DS_MERCHANT_MERCHANTURL", $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL));    //URL de mi pagina para procesar el pago
  1582.         $idInsc = ($competicion->getJugadores() == 1) ? $inscrito->getId() : 0;
  1583.         $paymentReturnParameters = array('id' => $idComp'idi' => $idInsc);
  1584.         if ((string) $request->query->get('fromapp''') === '1') {
  1585.             $paymentReturnParameters['fromapp'] = 1;
  1586.         }
  1587.         $redsys->setParameter("DS_MERCHANT_URLOK"$this->generateUrl('pago_terminado'array_merge($paymentReturnParameters, array('token' => 'success')), UrlGeneratorInterface::ABSOLUTE_URL));
  1588.         $redsys->setParameter("DS_MERCHANT_URLKO"$this->generateUrl('pago_terminado'array_merge($paymentReturnParameters, array('token' => 'fail')), UrlGeneratorInterface::ABSOLUTE_URL));
  1589.         $redsys->setParameter("DS_MERCHANT_PAYMETHODS""C");   //solo pago con tarjeta
  1590.         $redsys->setParameter("DS_MERCHANT_MERCHANTNAME"$this->getParameter('tpv.merchant_name'));
  1591.         $redsys->setParameter("DS_MERCHANT_MERCHANTDATA"base64_encode(json_encode(array('idi' => $idi'idp' => $idp))));
  1592.         $params['Ds_Merchant_URL_Pago'] = $this->getParameter('tpv.url');
  1593.         $params['Ds_SignatureVersion'] = $this->getParameter('tpv.version');      //Version SHA256 --> esto no se usa
  1594.         $params['Ds_MerchantParameters'] = $redsys->createMerchantParameters();              //Parametros, una vez codificados
  1595.         $params['Ds_Signature'] = $redsys->createMerchantSignature($params['Ds_Merchant_KEY_256']);                     //Firma de SHA256
  1596.         return $this->render('frontend/Default/tpv.html.twig'$params);
  1597.     }
  1598.     /**
  1599.      * F-063 Genera el formulario de devolución del banco
  1600.      *
  1601.      * @Route("/devolucion/{idi}/tpv/{idp}", name="devolucion_tpv")
  1602.      */
  1603.     public function tpvDevolucion($idi$idp)
  1604.     {
  1605.         $params = array();
  1606.         $inscrito $this->em->getRepository(Inscrito::class)->find($idi);
  1607.         if (!$inscrito) {
  1608.             throw new NotFoundHttpException("No existe el inscrito");
  1609.         }
  1610.         $competicion $inscrito->getCompeticion();
  1611.         if (!$competicion) {
  1612.             $this->addFlash(
  1613.                 'error'"El torneo buscado no existe");
  1614.             return $this->redirect($this->generateUrl('competiciones_abiertas'));
  1615.         }
  1616.         $pedido $this->em->getRepository(Pedido::class)->find($idp);
  1617.         if (!$pedido) {
  1618.             //poner que redirija a competicion en un mensaje de esos flash
  1619.             //y que ponga el inscrito y el pedido a "Error"
  1620.             throw new NotFoundHttpException("No existe el pedido asociado a la inscripcion");
  1621.         }
  1622.         $secret $this->getParameter('secret');
  1623.         $importeDev intval(number_format($pedido->getImporte() * 1000""""));
  1624.         $redsys = new RedsysAPI();
  1625.         $redsys->setParameter("DS_MERCHANT_AMOUNT"$importeDev);
  1626.         $redsys->setParameter("DS_MERCHANT_ORDER"$this->util->reformatPedido($pedido));
  1627.         $redsys->setParameter("DS_MERCHANT_CURRENCY"$this->getParameter('tpv.currency'));
  1628.         $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE"3);        //3 = Devolucion
  1629.         /*
  1630.           if (strpos($competicion->getOrganizador()->getId(), "AM") !== false) {
  1631.           $usuario = $this->em->getRepository(User::class)->findOneByUsername("AM00");
  1632.           } else {
  1633.           $usuario = $this->em->getRepository(User::class)->findOneByUsername($competicion->getOrganizador()->getId());
  1634.           }
  1635.          */
  1636.         $fechaTPVDesprosa = new \DateTime("2021-04-20 10:00:00");    //Desprosa es el nombre de la empresa y 20 de mayo es cuando se hizo este codigo
  1637.         $fechaTPVSherry = new \DateTime("2022-03-14 00:00:00");      //Aunque el cambio se hace el dia 09/03/2022, hay competiciones abiertas hasta el dia 12, por lo que se espera a que se cierren
  1638.         $fechaTPVAlhaurin = new \DateTime("2023-05-19 00:00:00");
  1639.         $idComp $competicion->getId();
  1640.         //El pago, lo hace LV05 o CM81 o lo hacemos con nuestra pasarela
  1641.         $orgnzdr "AM00";
  1642.         switch (trim($competicion->getOrganizador()->getId())) {
  1643.             case "LV05":
  1644.                 $orgnzdr "LV05";
  1645.                 break;
  1646.             case "GALN":
  1647.                 $orgnzdr "GALN";
  1648.                 break;
  1649.             case "CMC8":
  1650.                 $orgnzdr "CMC8";
  1651.                 if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1652.                     $orgnzdr "AM00";
  1653.                 }
  1654.                 break;
  1655.             case "CM81":
  1656.                 $orgnzdr "CM81";
  1657.                 if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1658.                     $orgnzdr "AM00";
  1659.                 }
  1660.                 break;
  1661.             case "AM15":
  1662.                 $orgnzdr "AM15";
  1663.                 if ($competicion->getInicio()->format("U") < $fechaTPVDesprosa->format("U")) {
  1664.                     $orgnzdr "AM00";
  1665.                 }
  1666.                 break;
  1667.             case "AMC3":
  1668.                 $orgnzdr "AMC3";
  1669.                 if ($competicion->getInicio()->format("U") < $fechaTPVSherry->format("U")) {
  1670.                     $orgnzdr "AM00";
  1671.                 }
  1672.                 break;
  1673.             case "AM22":
  1674.                 $orgnzdr "AM22";
  1675.                 if ($competicion->getInicio()->format("U") < $fechaTPVAlhaurin->format("U")) {
  1676.                     $orgnzdr "AM00";
  1677.                 }
  1678.                 break;
  1679.             default:
  1680.                 $orgnzdr "AM00";
  1681.                 break;
  1682.         }
  1683.         $usuario $this->em->getRepository(User::class)->findOneByUsername($orgnzdr);
  1684.         $usuarioTpv $usuario->getTpv();
  1685.         $redsys->setParameter("DS_MERCHANT_MERCHANTCODE"$redsys->merchantCodeFromUser($usuarioTpv$secret));
  1686.         $redsys->setParameter("DS_MERCHANT_TERMINAL"$redsys->terminalFromUser($usuarioTpv$secret));
  1687.         $params['Ds_Merchant_KEY_256'] = $redsys->keyFromUser($usuarioTpv$secret); //Key de REAL del TPV correspondiente
  1688.         //lineas originales
  1689.         //$redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $this->getParameter('tpv.merchant_code'));
  1690.         //$redsys->setParameter("DS_MERCHANT_TERMINAL", $this->getParameter('tpv.terminal'));
  1691.         //$dire = str_replace("https", "http", $this->generateUrl('competicion_cancelainscrito', array('id' => $idComp, 'pedido' => $idp), UrlGeneratorInterface::ABSOLUTE_URL));   //Como el SSL de la pagina es Lets encrypt y el banco no lo admite, tenemos que hacerlo por HTTP, y no por HTTPS para evitar errores
  1692.         $dire $this->generateUrl('competicion_cancelainscrito', array('id' => $idComp'pedido' => $idp), UrlGeneratorInterface::ABSOLUTE_URL);
  1693.         $redsys->setParameter("DS_MERCHANT_MERCHANTURL"$dire);    //URL de mi pagina para procesar el pago
  1694.         //$redsys->setParameter("DS_MERCHANT_MERCHANTURL", $this->generateUrl('pago_procesar', array(), UrlGeneratorInterface::ABSOLUTE_URL));    //URL de mi pagina para procesar el pago
  1695.         $idInsc = ($competicion->getJugadores() == 1) ? $inscrito->getId() : 0;
  1696.         $redsys->setParameter("DS_MERCHANT_URLOK"$this->generateUrl('pago_terminado', array('token' => 'cancel''id' => $idComp'idi' => $idInsc), UrlGeneratorInterface::ABSOLUTE_URL));
  1697.         $redsys->setParameter("DS_MERCHANT_URLKO"$this->generateUrl('pago_terminado', array('token' => 'fail''id' => $idComp'idi' => $idInsc), UrlGeneratorInterface::ABSOLUTE_URL));
  1698.         $redsys->setParameter("DS_MERCHANT_PAYMETHODS""C");   //solo pago con tarjeta
  1699.         $redsys->setParameter("DS_MERCHANT_MERCHANTNAME"$this->getParameter('tpv.merchant_name'));
  1700.         $redsys->setParameter("DS_MERCHANT_MERCHANTDATA"base64_encode(json_encode(array('idi' => $idi'idp' => $idp))));
  1701.         //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_test_256');   //Key de TEST.
  1702.         //$params['Ds_Merchant_KEY_256'] = $this->getParameter('tpv.key_256');   //Key de REAL. Codigo antiguo
  1703.         //$params['Ds_Merchant_URL_Pago'] = $this->getParameter('tpv.url_test');   //Direccion de TEST
  1704.         $params['Ds_Merchant_URL_Pago'] = $this->getParameter('tpv.url');      //Direccion REAL
  1705.         $params['Ds_SignatureVersion'] = $this->getParameter('tpv.version');      //Version SHA256 --> esto no se usa
  1706.         $params['Ds_MerchantParameters'] = $redsys->createMerchantParameters();              //Parametros, una vez codificados
  1707.         $params['Ds_Signature'] = $redsys->createMerchantSignature($params['Ds_Merchant_KEY_256']);                     //Firma de SHA256
  1708.         return $this->render('frontend/Default/tpv.html.twig'$params);
  1709.     }
  1710.     /**
  1711.      * F-064 Landing de retorno al pago en el banco
  1712.      *
  1713.      * @Route("/pago/{idi}/intermedio/{idp}", name="pago_intermedio")
  1714.      */
  1715.     public function pagoIntermedio($idi$idp)
  1716.     {
  1717.         $inscrito $this->em->getRepository(Inscrito::class)->find($idi);
  1718.         if (!$inscrito) {
  1719.             throw new NotFoundHttpException("No existe el inscrito");
  1720.         }
  1721.         $pedido $this->em->getRepository(Pedido::class)->find($idp);
  1722.         if (!$pedido) {
  1723.             //poner que redirija a competicion en un mensaje de esos flash
  1724.             //y que ponga el inscrito y el pedido a "Error"
  1725.             throw new NotFoundHttpException("No existe el pedido asociado a la inscripcion");
  1726.         }
  1727.         return $this->render("frontend/Default/pagoIntermedio.html.twig", [
  1728.             'inscrito' => $inscrito,
  1729.             'pedido' => $pedido
  1730.         ]);
  1731.     }
  1732.     /**
  1733.      * F-065 Landing de retorno al pago en el banco
  1734.      *
  1735.      * @Route("/pago-terminado/{token}/{id}/{idi}", name="pago_terminado", defaults={"idi" = 0})
  1736.      */
  1737.     public function pagoTerminado($token$id$idiUtilJugadores $util_jugadores)
  1738.     {
  1739.         $competicion $this->em->getRepository(Competicion::class)->find($id);
  1740.         if (!$competicion) {
  1741.             $this->addFlash(
  1742.                 'error'"El torneo buscado no existe");
  1743.             return $this->redirect($this->generateUrl('_tournament', array('id' => $id)));
  1744.         }
  1745.         $params = [
  1746.             'token' => $token,
  1747.             'id' => $id,
  1748.             'idj' => null,
  1749.         ];
  1750.         if ($idi != 0) {
  1751.             $inscrito $this->em->getRepository(Inscrito::class)->find($idi);
  1752.             if (!empty($inscrito) && ($token == "success")) {
  1753.                 $jugador $inscrito->getJugador();
  1754.                 $cl $competicion->getOrganizador()->getCliente();
  1755.                 $telefono $util_jugadores->getDatoPlanoDesdeJugador($jugador"Telefono"$cl);  //
  1756.                 if (empty($telefono)) {
  1757.                     $params["idj"] = $jugador->getId();
  1758.                 }
  1759.             }
  1760.         }
  1761.         /*
  1762.           $tarifa = $this->em->getRepository(Tarifa::class)->find($idt);
  1763.           if (!$tarifa) {
  1764.           //poner que redirija a competicion en un mensaje de esos flash
  1765.           //y que ponga el inscrito y el pedido a "Error"
  1766.           throw new NotFoundHttpException("No existe la tarifa");
  1767.           }
  1768.          */
  1769.         return $this->render("frontend/Default/pagoTerminado.html.twig"$params);
  1770.     }
  1771.     /**
  1772.      * F-066 Procesamiento del pago tras aviso del banco
  1773.      *
  1774.      * @Route("/pago-procesar", name="pago_procesar")
  1775.      *
  1776.      */
  1777.     public function pagoProcesar(Request $requestEnvioCorreo $mailerNotificacionesService $notificatorEnvioSms $messagingUtilJugadores $util_jugadoresSoftwareExternoUtil $swutilPreferredLicenseClubChecker $preferredLicenseClubChecker)
  1778.     {
  1779.         $redsys = new RedsysAPI();
  1780.         $Ds_MerchantParameters $request->request->get('Ds_MerchantParameters');
  1781.         $decodec $redsys->decodeMerchantParameters($Ds_MerchantParameters);
  1782.         $fields json_decode($decodectrue);
  1783.         $other_fields json_decode(base64_decode($fields['Ds_MerchantData']), true);
  1784.         $inscritos = array();
  1785.         $jugadores = array();
  1786.         $secret $this->getParameter('secret');
  1787.         $inscrito $this->em->getRepository(Inscrito::class)->find($other_fields['idi']);
  1788.         if (!$inscrito) {
  1789.             return new JsonResponse([]);
  1790.         }
  1791.         $pedido $this->em->getRepository(Pedido::class)->find($other_fields['idp']);
  1792.         if (!$pedido) {
  1793.             return new JsonResponse([]);
  1794.         }
  1795.         $competicion $inscrito->getCompeticion();
  1796.         $num_inscritos $this->em->getRepository(Inscrito::class)->getCountInscritosByEstadoCorrecto($competicion->getId(), false, ["pagado"]);
  1797.         $lista_espera = (($num_inscritos >= $competicion->getPlazas()) && $competicion->getListaEspera());
  1798.         //Permitimos que se terminen de inscribir aquellos, que aun habiendo acbado el plazo, la competicion sigue abierta a la espera de que la tarea la ponga en "finalizada"
  1799.         if (($competicion->getModo()->getId() != 3) && ($competicion->getEstado() != "abierta")) {
  1800.             //Mandamos correo a soporte para avisar
  1801.             $args = [
  1802.                 "to" => $this->getParameter('next.email.rfga'),
  1803.                 "bcc" => false,
  1804.                 "competicion" => $competicion,
  1805.                 "subject" => '⛳ NEXTCADDY - Inscripción AL LƍMITE [' $pedido->getNumero() . ']',
  1806.                 "html" => $this->renderView('frontend/Inscritos/emailInscripcionLimite.html.twig', array('jugador' => $inscrito->getJugador(),
  1807.                     'inscrito' => $inscrito,
  1808.                     'competicion' => $competicion,
  1809.                     'pedido' => $pedido,
  1810.                     'tarifa' => $pedido->getTarifa()
  1811.                 ))
  1812.             ];
  1813.             //EnvioCorreo::enviarCorreo($args);
  1814.             $mailer->enviarCorreo($args);
  1815.             return new JsonResponse([]);
  1816.         }
  1817.         //SWGOLF
  1818.         //$gmutil = new GolfmanagerUtilidad();
  1819.         $swbd $this->em->getRepository(SoftwareGolf::class)->findOneBy(["innerClass" => "Club""cliente" => $competicion->getOrganizador()->getCliente(), "clubId" => $competicion->getClub()->getId()]);
  1820.         if ($swbd) {
  1821.             $swutil->init($swbd);
  1822.         }
  1823.         if (in_array($inscrito->getEstado(), ["espera""error"]) && in_array($pedido->getEstado(), ["espera""error"])) {
  1824.             $avisar false;
  1825.             if ($fields['Ds_Order'] == $pedido->getNumero()) {
  1826.                 if (intval($fields['Ds_Response']) < 100) {
  1827.                     $estado "pagado";
  1828.                     $avisar true;
  1829.                     /*
  1830.                       } else if (intval($fields['Ds_Response']) == 900) {
  1831.                       $estado = "devolucion";
  1832.                       $avisar = false;
  1833.                      *
  1834.                      */
  1835.                     $pedido->setPayedAt(new \DateTime('now'));
  1836.                 } else {
  1837.                     $pedido->setCodigoError($fields['Ds_Response']);
  1838.                     $estado "error";
  1839.                     $avisar false;
  1840.                 }
  1841.                 //04/03/20 Subimos el pedido set estado aqui porque sospechamos que el guardaCsv ha podido dar error, para que el pedido e quede en "pagado"/"error" para evitar que la tarea que busca los "en espera" lo limpie.
  1842.                 $pedido->setEstado($estado);
  1843.                 $pedido->setUpdatedAt(new \DateTime('now'));
  1844.                 //buscamos todos los inscritos que tienen el mismo pedido para cambiarle el estado
  1845.                 $inscritos $this->em->getRepository(Inscrito::class)->findBy(array('pedido' => $pedido->getId()));
  1846.                 foreach ($inscritos as $ins) {
  1847.                     $ins->setEstado($estado);
  1848.                     $participateValue $lista_espera ? -1;
  1849.                     if ($competicion->getListaEspera() && $competicion->getRestringirLicencia() === EnumEstadoRestringirLicencias::PREFERENCIA) {
  1850.                         $belongsToPreferredClub $preferredLicenseClubChecker->belongsToPreferredClub($ins->getLicencia(), $competicion);
  1851.                         if (!$belongsToPreferredClub) {
  1852.                             $participateValue = -1;
  1853.                         }
  1854.                     }
  1855.                     $ins->setParticipa($participateValue);
  1856.                     $ins->setUpdatedAt(new \DateTime('now'));
  1857.                     $jugador $ins->getJugador();
  1858.                     $log_message "Inscripción online en Competicion " $competicion->getNombre() . "(" $competicion->getId() . "): " $jugador->getLicencia() . " - " $estado " - (" $pedido->getNumero() . ")";
  1859.                     $log = new Log('i'$log_messagenull);
  1860.                     $this->em->persist($log);
  1861.                     $this->em->flush();
  1862.                     try {
  1863.                         $this->util->guardaCsvInscripciones($ins);
  1864.                     } catch (\Throwable $ex) {
  1865.                         $log_message "Error guardaCsvInscripciones inscripcion online en Competicion " $competicion->getNombre() . "(" $competicion->getId() . "): " $jugador->getLicencia() . " - " $estado " - (" $pedido->getNumero() . ")";
  1866.                         $log = new Log('i'$log_messagenull);
  1867.                         $this->em->persist($log);
  1868.                         $this->em->flush();
  1869.                     }
  1870.                     //Pablo 22/02/2024: Borramos esta condicion, me da igual el softwaregolf que tengamos que ha de ejecutarse la funcion de agregar,
  1871.                     // como es de pago avisamos aqui al proveedor (pago formalziado)
  1872.                     if ($swbd) {
  1873.                         $swutil->addClientToActivity($inscrito$this->emtrue);
  1874.                     }
  1875.                 }
  1876.                 $this->em->flush();
  1877.             }
  1878.             //Separado, para eviar que falle y deje a la mitad la inscripcion, sino iria arriba. De esta manera nos aseguramos que
  1879.             if ($avisar) {
  1880.                 $url $this->util->getShortUrl($competicion);
  1881.                 if (!$lista_espera) {
  1882.                     $texto "Se ha inscrito correctamente en " substr($this->util->limpiar($competicion->getNombre()), 045) . ". Puede consultar el listado de inscritos en " $url;
  1883.                 } else {
  1884.                     $texto "EstĆ” en lista de espera de " substr($this->util->limpiar($competicion->getNombre()), 050) . ". Consulte lista de inscritos en " $url;
  1885.                 }
  1886.                 $cl $competicion->getOrganizador()->getCliente();
  1887.                 foreach ($inscritos as $ins) {
  1888.                     $jugador $ins->getJugador();
  1889.                     //Preparación y envio del SMS
  1890.                     $privacidad $inscrito->getJugador()->getPrivacidadSimple();
  1891.                     $rgpd false;
  1892.                     if (strpos($competicion->getOrganizador()->getId(), "AM") !== false) {    //si organiza alguien de la RFGA, buscamos la privacidad de RFGA
  1893.                         if (isset($privacidad["AM00"]) && $privacidad["AM00"]) {
  1894.                             $rgpd true;
  1895.                         }
  1896.                     } else {//buscamos la privacidad del organizador
  1897.                         if ((isset($privacidad[$competicion->getOrganizador()->getId()]) && $privacidad[$competicion->getOrganizador()->getId()]) || (isset($privacidad["AM00"]) && $privacidad["AM00"])) {
  1898.                             $rgpd true;
  1899.                         }
  1900.                     }
  1901.                     $telefono $util_jugadores->getDatoPlanoDesdeJugador($jugador"Telefono"$cl);
  1902.                     if ($rgpd && !empty($telefono)) {
  1903.                         $userApp $this->em->getRepository(UserApp::class)->findOneByTelefono($telefono);
  1904.                         //if (!$userApp) {
  1905.                         $api $cl?->getId() > 2;
  1906.                         $messaging->enviarSms($telefono$texto$competicion2$api);
  1907.                         //} else {
  1908.                         $args = [];
  1909.                         $args["title"] = "Nueva inscripción en torneo";
  1910.                         $args["msg"] = $texto;
  1911.                         $args["url"] = $url;
  1912.                         $args["destinatario"] = $userApp;
  1913.                         $args["tipo"] = "new-inscription";
  1914.                         $args["competicion"] = $competicion->getId();
  1915.                         $notificator->enviarNotificacion($args);
  1916.                         //}
  1917.                     }
  1918.                     $jugadores[] = $jugador;
  1919.                 }
  1920.                 //$email = $pedido->getEmail();
  1921.                 $email $pedido->getEmailCodDecod($secret);
  1922.                 if (count($jugadores) == 1) {
  1923.                     $html $this->renderView('frontend/Inscritos/emailInscripcion.html.twig', array('jugador' => $jugador,
  1924.                         'competicion' => $competicion,
  1925.                         'pedido' => $pedido,
  1926.                         'inscrito' => $inscrito,
  1927.                         'barras' => $this->em->getRepository(JornadaConfig::class)->findByInscrito($inscrito),
  1928.                         'tarifa' => $pedido->getTarifa(),
  1929.                         'lista_espera' => $lista_espera
  1930.                     ));
  1931.                     /* $email_send->addTo($email)
  1932.                       ->setBcc($this->getParameter('next.email.rfga'))
  1933.                       ->setFrom('mailing@nextcaddy.com')
  1934.                       ->setSubject('⛳ NextCaddy - Inscripción online [' . $pedido->getNumero() . ']')
  1935.                       ->setHtml($this->renderView('frontend/Inscritos/emailInscripcion.html.twig', array('jugador' => $jugador,
  1936.                       'competicion' => $competicion,
  1937.                       'pedido' => $pedido,
  1938.                       'tarifa' => $pedido->getTarifa()
  1939.                       ))
  1940.                       ); */
  1941.                 } else {
  1942.                     $html $this->renderView('frontend/Inscritos/emailInscripcionPareja.html.twig', array('jugadores' => $jugadores,
  1943.                         'competicion' => $competicion,
  1944.                         'inscritos' => $inscritos,
  1945.                         'pedido' => $pedido,
  1946.                         'tarifas' => $pedido->getImporte() . "€",
  1947.                         'lista_espera' => $lista_espera
  1948.                     ));
  1949.                 }
  1950.                 /* $organizador = (substr($competicion->getOrganizador()->getId(), 0, 2) == "AM") ? "AM00" : $competicion->getOrganizador()->getId();
  1951.                   $userSendgrid = $this->em->getRepository(User::class)->findOneByUsername($organizador);
  1952.                   $sendgridKey = $userSendgrid->getSocialRed($this->getParameter('secret'), "sendgrid");
  1953.                   $sendgrid = new \SendGrid($sendgridKey["api_key"]);      //segun usuario
  1954.                   if ($_SERVER['SERVER_NAME'] != 'localhost') {
  1955.                   $sendgrid->send($email_send); } */
  1956.                 $args = [
  1957.                     "to" => $email,
  1958.                     "competicion" => $competicion,
  1959.                     "subject" => '⛳ NEXTCADDY - Inscripción online [' $pedido->getNumero() . ']',
  1960.                     "html" => $html
  1961.                 ];
  1962.                 //EnvioCorreo::enviarCorreo($args);
  1963.                 $mailer->enviarCorreo($args);
  1964.             }
  1965.             //Simplificamos la condicion, ya que puede haber inscritos anulados y preservado el pedido e inscritos a los que se le devuelve el importe
  1966.         } else if (empty($pedido->getReturnedAt()) && in_array($pedido->getEstado(), ["devolucion""anulado"])) {
  1967.             //} else if ((empty($pedido->getReturnedAt())) && ($inscrito->getEstado() == $pedido->getEstado()) && (($pedido->getEstado() == "devolucion") || ($pedido->getEstado() == "anulado"))) {
  1968.             //
  1969.             //En este ELSEIF solamente entra cuando es una devolucion desde los emials de aviso por reemplazo de un jugador
  1970.             ////https://canales.redsys.es/canales/ayuda/documentacion/Manual%20integracion%20para%20conexion%20por%20Redireccion.pdf
  1971.             //0000 a 0099 Transacción autorizada para pagos y preautorizaciones
  1972.             //900 Transacción autorizada para devoluciones y confirmaciones
  1973.             //400 Transacción autorizada para anulaciones
  1974.             //Resto son errores en el pedido: Tarjeta caducada, Código de seguridad (CVV2/CVC2) incorrecto, Tarjeta no existente, etc
  1975.             $ds_response intval($fields['Ds_Response']);
  1976.             if (($ds_response == 900) || ($ds_response == 400)) {
  1977.                 //marcamos como devuelto en el banco el elemento
  1978.                 $pedido->setReturnedAt(new \DateTime('now'));
  1979.                 $pedido->setEstado("anulado");  //Esto es anulado, ya que para el caso de que el jugador autocancele su inscripcion va por la URL de "competicion_cancelainscrito"
  1980.                 $log_message "Devolución del pedido " $pedido->getNumero() . " realizada con Ć©xito.";
  1981.                 //Pablo 22/02/2024: Me da igual el softwaregolf que tengamos que ha de ejecutarse la funcion de borrar inscrito, como es de pago avisamos aqui al proveedor (devolucion formalziado)
  1982.                 //Lo ponemos aqui, que la devolucion ha ido OK, si hay fallo no borramos a nadie
  1983.                 if ($swbd) {
  1984.                     $swutil->deleteClientFromActivity($inscrito$this->emtrue);
  1985.                 }
  1986.             } else {
  1987.                 $pedido->setCodigoError($fields['Ds_Response']);
  1988.                 $log_message "Error realizando la devolución del pedido " $pedido->getNumero() . "Codigo de error: " $fields['Ds_Response'];
  1989.             }
  1990.             $log = new Log('i'$log_message$this->getUser()?->getUserIdentifier());
  1991.             $this->em->persist($log);
  1992.             $this->em->flush();
  1993.         }
  1994.         return new JsonResponse([]);
  1995.     }
  1996.     /**
  1997.      * Muestra los encuentros de resultados para competiciones Ryder Cup.
  1998.      *
  1999.      * @Route("/getListadoResultados", name="listado_resultados", options={"expose"=true})
  2000.      */
  2001.     public function listadoResultados(Request $request): JsonResponse|Response
  2002.     {
  2003.         $competitionId = (int)$request->request->get("id"0);
  2004.         $token $request->request->get("token"null);
  2005.         $competition $this->em->getRepository(Competicion::class)->find($competitionId);
  2006.         if (!$competition) {
  2007.             return new JsonResponse(-1);
  2008.         }
  2009.         if (!$this->util->checkTokenValidIframe($competition$token)) {
  2010.             return new JsonResponse(-1);
  2011.         }
  2012.         if ($competition->getFormula()?->getId() !== 'R') {
  2013.             return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2014.                 'results' => ['teams' => [], 'rounds' => [], 'matches' => []],
  2015.                 'mode' => 'results',
  2016.             ]);
  2017.         }
  2018.         return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2019.             'results' => $this->ryderCupResultsData->__invoke($competition),
  2020.             'mode' => 'results',
  2021.         ]);
  2022.     }
  2023.     /**
  2024.      * Muestra los enfrentamientos definidos para competiciones Ryder Cup.
  2025.      *
  2026.      * @Route("/getListadoEnfrentamientos", name="listado_enfrentamientos", options={"expose"=true})
  2027.      */
  2028.     public function listadoEnfrentamientos(Request $request): JsonResponse|Response
  2029.     {
  2030.         $competitionId = (int)$request->request->get("id"0);
  2031.         $token $request->request->get("token"null);
  2032.         $competition $this->em->getRepository(Competicion::class)->find($competitionId);
  2033.         if (!$competition) {
  2034.             return new JsonResponse(-1);
  2035.         }
  2036.         if (!$this->util->checkTokenValidIframe($competition$token)) {
  2037.             return new JsonResponse(-1);
  2038.         }
  2039.         if ($competition->getFormula()?->getId() !== 'R') {
  2040.             return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2041.                 'results' => ['teams' => [], 'rounds' => [], 'matches' => []],
  2042.                 'mode' => 'fixtures',
  2043.             ]);
  2044.         }
  2045.         return $this->render('frontend/Competicion/components/results_ryder.html.twig', [
  2046.             'results' => $this->ryderCupResultsData->buildFixtures($competition),
  2047.             'mode' => 'fixtures',
  2048.         ]);
  2049.     }
  2050.     /**
  2051.      * F-067 Muestra un listado con los cambios de handicap tras el torneo
  2052.      *
  2053.      * @Route("/getListadoCambiosHandicap", name="listado_cambios_handicap", options={"expose"=true})
  2054.      *
  2055.      */
  2056.     public function listadoCambiosHandicap(Request $request)
  2057.     {
  2058.         $id $request->request->get("id");
  2059.         //comprobar competicion.
  2060.         $competicion $this->em->getRepository(Competicion::class)->findOneById($id);
  2061.         if (!$competicion) {
  2062.             return new JsonResponse(-1);
  2063.         }
  2064.         $diferencias = array();
  2065.         $inscritos = array();
  2066.         $inscritosAux $this->em->getRepository(Inscrito::class)->getHandicapsSms($id);
  2067.         foreach ($inscritosAux as $inscrito) {
  2068.             $idi $inscrito->getId();
  2069.             $handicaps unserialize($inscrito->getHcpSms());
  2070.             $long count($handicaps);
  2071.             $cambio 0;
  2072.             for ($i 1$i <= $long$i++) {
  2073.                 if ($i != 1) {
  2074.                     $diferencias[$i] = number_format($handicaps[$i], 1) - number_format($handicaps[$i 1], 1);
  2075.                     $cambio += $diferencias[$i];
  2076.                 } else {
  2077.                     $diferencias[$i] = number_format($handicaps[$i], 1) - $inscrito->getHcp();
  2078.                     $cambio += $diferencias[$i];
  2079.                 }
  2080.             }
  2081.             $inscritos[$idi] = [
  2082.                 "nombre" => $inscrito->getJugador()->getNombre(),
  2083.                 "apellidos" => $inscrito->getJugador()->getApellidos(),
  2084.                 "licencia" => $inscrito->getJugador()->getLicencia(),
  2085.                 "hcp" => $inscrito->getHcp(),
  2086.                 "handicaps" => $handicaps,
  2087.                 "cambio" => $cambio,
  2088.                 "diferencias" => $diferencias
  2089.             ];
  2090.         }
  2091.         $cmp = function ($a$b) {
  2092.             $a1 number_format($a["cambio"], 1);
  2093.             $b1 number_format($b["cambio"], 1);
  2094.             if ($a1 == $b1) {
  2095.                 if (number_format($a["hcp"]) == number_format($b["hcp"])) {
  2096.                     return 0;
  2097.                 }
  2098.                 return (number_format($a["hcp"]) < number_format($b["hcp"])) ? -1;
  2099.             }
  2100.             return ($a1 $b1) ? -1;
  2101.         };
  2102.         //ordenamos
  2103.         usort($inscritos$cmp);
  2104.         return $this->render("frontend/Inscritos/listado_cambio_handicap.html.twig", [
  2105.             'competicion' => $competicion,
  2106.             'inscritos' => $inscritos
  2107.         ]);
  2108.     }
  2109.     /**
  2110.      * F-068 Devuelve las estadisticas de una competicion
  2111.      *
  2112.      * @Route("/getListadoEstadisticas", name="listado_estadisticas", options={"expose"=true})
  2113.      *
  2114.      */
  2115.     public function listadoEstadisticas(Request $request)
  2116.     {
  2117.         //$isAjax = $request->isXMLHttpRequest();
  2118.         //if ($isAjax) {
  2119.         $response = new JsonResponse();
  2120.         //comprobar que hay Puntuaciones publicadas.
  2121.         $competicion $request->get("id");
  2122.         $estadisticas $this->em->getRepository(Estadisticas::class)->findBy(array('competicion' => $competicion));
  2123.         if ($estadisticas) {
  2124.             $arDatos = array();
  2125.             foreach ($estadisticas as $data) {
  2126.                 if (!isset($arDatos[$data->getJornada()])) {
  2127.                     $arDatos[$data->getJornada()] = array();
  2128.                 }
  2129.                 $arDatos[$data->getJornada()][$data->getTipo()] = array("id" => $data->getId(), "datos" => $data->getDatos());
  2130.             }
  2131.             $response->setData($arDatos);
  2132.         } else {
  2133.             $response->setData("No data");
  2134.         }
  2135.         return $response;
  2136.         //} else {
  2137.         //    return new Response('This is not ajax!', 400);
  2138.         //}
  2139.     }
  2140.     /**
  2141.      * F-069 Muestra las estadisticas de una competicion
  2142.      *
  2143.      * @Route("/renderStats", name="_ajRenderStats", options={"expose"=true})
  2144.      *
  2145.      */
  2146.     public function renderEstadistica(Request $request)
  2147.     {
  2148.         $isAjax $request->isXMLHttpRequest();
  2149.         $response = new JsonResponse();
  2150.         $competicion $request->get("id");
  2151.         if ($isAjax) {
  2152.             $datos = array();
  2153.             $fechas = array(=> "");   //primer elemento ficticio para el total
  2154.             //comprobar que hay Puntuaciones publicadas.
  2155.             $estadisticas $this->em->getRepository(Estadisticas::class)->findBy(array('competicion' => $competicion), array("jornada" => "ASC"));
  2156.             if (!$estadisticas) {
  2157.                 $response->setData("No data");
  2158.             } else {
  2159.                 foreach ($estadisticas as $data) {
  2160.                     if (!isset($datos[$data->getJornada()])) {
  2161.                         $datos[$data->getJornada()] = array();
  2162.                         $jornada $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion"orden" => $data->getJornada()));
  2163.                         if ($jornada) {
  2164.                             $fechas[$data->getJornada()] = $jornada->getFecha();
  2165.                         }
  2166.                     }
  2167.                     $datos[$data->getJornada()][$data->getTipo()] = array('id' => $data->getId(), 'datos' => $data->getDatos());
  2168.                 }
  2169.             }
  2170.             return $this->render('frontend/Estadisticas/index.html.twig', array("datos" => $datos"fechas" => $fechas));
  2171.         } else {
  2172.             return new Response('This is not ajax!'400);
  2173.         }
  2174.     }
  2175.     /**
  2176.      * F-070 Pagina de bienvenida a jugadores
  2177.      *
  2178.      * @Route("/bienvenido/{lic}", name="bienvenido_nextcaddy")
  2179.      */
  2180.     public function bienvenido($lic)
  2181.     {
  2182.         $inicialFed substr(trim($lic), 02);
  2183.         $jugador $this->em->getRepository(Jugador::class)->findOneBy(array('habilitado' => 1'licencia_corta' => substr($lic, -6)));
  2184.         if (!$jugador) {
  2185.             //creamos un jugador por defecto si no existe, para que vaya a la pagina de club de la federacion
  2186.             $jugador = new Jugador(__METHOD__);
  2187.             $jugador->setLicencia($inicialFed "00123456");
  2188.         }
  2189.         $club $this->em->getRepository(Club::class)->findOneBy(array('id' => substr(trim($jugador->getLicencia()), 04), 'habilitado' => true));
  2190.         if (!$club) {
  2191.             $club $this->em->getRepository(Club::class)->find($inicialFed "00");
  2192.             if (!$club) {
  2193.                 return $this->redirect($this->generateUrl('provincias'));
  2194.             }
  2195.         }
  2196.         return $this->render("frontend/Default/bienvenido.html.twig", [
  2197.             'club' => $club,
  2198.             'jugador' => $jugador
  2199.         ]);
  2200.     }
  2201.     /**
  2202.      * F-071 Listado de clubes agrupados por provincia
  2203.      *
  2204.      * @Route("/provincias/{id}", name="provincias", defaults={"id" = 0})
  2205.      */
  2206.     public function provinces($id): Response
  2207.     {
  2208.         $clubRepository $this->em->getRepository(Club::class);
  2209.         $provinceRepository $this->em->getRepository(Provincia::class);
  2210.         $regionRepository $this->em->getRepository(Comunidad::class);
  2211.         $clubsByProvince $this->getClubsByProvince($clubRepository);
  2212.         $provincesWithCount $this->getProvincesWithClubCount($clubsByProvince$provinceRepository);
  2213.         $regionsWithProvinces $this->getRegionsWithProvinces($provincesWithCount$provinceRepository$regionRepository);
  2214.         return $this->render("frontend/Default/provincias.html.twig", [
  2215.             'id' => $id,
  2216.             'clubsByProvince' => $clubsByProvince,
  2217.             'provincesWithCount' => $provincesWithCount,
  2218.             'regions' => $regionsWithProvinces
  2219.         ]);
  2220.     }
  2221.     private function getClubsByProvince($clubRepository): array
  2222.     {
  2223.         $clubs $clubRepository->findTodosProvincia();
  2224.         $clubsByProvince = [];
  2225.         foreach ($clubs as $club) {
  2226.             $locality $club->getLocalidad();
  2227.             $province $locality?->getProvincia();
  2228.             if (!$province) {
  2229.                 continue;
  2230.             }
  2231.             $provinceId $province->getId();
  2232.             $clubsByProvince[$provinceId]['name'] = $province->getNombre();
  2233.             $clubsByProvince[$provinceId]['clubs'][] = [
  2234.                 'id' => $club->getId(),
  2235.                 'name' => $club->getNombre(),
  2236.                 'locality' => $locality->getNombre(),
  2237.                 'phone' => $club->getTelefono() ?? 'No disponible'
  2238.             ];
  2239.         }
  2240.         return $clubsByProvince;
  2241.     }
  2242.     private function getProvincesWithClubCount(array $clubsByProvince$provinceRepository): array
  2243.     {
  2244.         $provinces $provinceRepository->findAll();
  2245.         $provincesWithCount = [];
  2246.         foreach ($provinces as $province) {
  2247.             $provinceId $province->getId();
  2248.             $provincesWithCount[$provinceId] = [
  2249.                 'name' => $province->getNombre(),
  2250.                 'num_clubs' => count($clubsByProvince[$provinceId]['clubs'] ?? [])
  2251.             ];
  2252.         }
  2253.         return $provincesWithCount;
  2254.     }
  2255.     private function getRegionsWithProvinces(array $provincesWithCount$provinceRepository$regionRepository): array
  2256.     {
  2257.         $regions $regionRepository->findAll();
  2258.         $regionsWithProvinces = [];
  2259.         foreach ($regions as $region) {
  2260.             $regionsWithProvinces[$region->getId()] = [
  2261.                 'name' => $region->getNombre(),
  2262.                 'default_logo' => $region->getDefaultLogo() ?? 'https://resources.nextcaddy.com/clubResources/nextcaddy/logos/SVG/nextcaddy.svg',
  2263.                 'provinces' => []
  2264.             ];
  2265.         }
  2266.         foreach ($provincesWithCount as $provinceId => $provinceData) {
  2267.             $province $provinceRepository->find($provinceId);
  2268.             $regionId $province->getComunidad()->getId();
  2269.             if (isset($regionsWithProvinces[$regionId])) {
  2270.                 $regionsWithProvinces[$regionId]['provinces'][$provinceId] = $provinceData;
  2271.             }
  2272.         }
  2273.         return $regionsWithProvinces;
  2274.     }
  2275.     /**
  2276.      * F-072 Pagina para felicitar el aƱo nuevo
  2277.      * @Route("/felicitacion-navidad/{token}", name="felicitacion_navidad")
  2278.      *
  2279.      * MĆ”s info: https://slopenxt.atlassian.net/wiki/spaces/NXT/pages/638386177/Felicitaci+n+de+Navidad
  2280.      *
  2281.      */
  2282.     public function felicitacionNavidad($token)
  2283.     {
  2284.         $key $this->getParameter('secret');
  2285.         $cadena UtilStatic::desencriptar($token$key); //LICENCIA-AƑO
  2286.         $f = new \DateTime("now");
  2287.         if (intval($f->format("Y")) > 2020) {
  2288.             $valores explode("_"$cadena);   //asi los profesionales pueden verlo sin que sea generico
  2289.         } else {
  2290.             $valores explode("-"$cadena);
  2291.         }
  2292.         $licencia $valores[0];
  2293.         $year $valores[1];
  2294.         $jugador $this->em->getRepository(Jugador::class)->findOneBy(array('habilitado' => 1'licencia' => $licencia));
  2295.         if ($jugador) {
  2296.             //Excepcion en el aƱo 2019 por culpa de la RGPD
  2297.             if ($year != 2019) {
  2298.                 if (substr($jugador->getLicencia(), 02) != "CM") {
  2299.                     //buscamos las competiciones del aƱo anterior
  2300.                     $competiciones $this->em->getRepository(Inscrito::class)->getCompeticionesAnualLicencia($licencia"" . ($year 1));
  2301.                 }
  2302.             }
  2303.         } else {
  2304.             //creamos un jugador por defecto si no existe, para que vaya a la pagina de club de la federacion
  2305.             $jugador = new Jugador(__METHOD__);
  2306.             $jugador->setNombre("Golfista");
  2307.             $jugador->setLicencia("AM00123456");
  2308.             $competiciones = [];
  2309.         }
  2310.         if ($year >= 2020) {
  2311.             $view "frontend/Navidad/navidad_" $year ".html.twig";
  2312.         } else {
  2313.             $view "frontend/Navidad/navidad.html.twig";
  2314.         }
  2315.         return $this->render($view, array(
  2316.             'year' => $year,
  2317.             'jugador' => $jugador,
  2318.             'competiciones' => $competiciones,
  2319.             'leones' => false   //in_array($licencia, ["AM85111566"])
  2320.         ));
  2321.     }
  2322.     /**
  2323.      * F-073 Pagina para felicitar las fiestas navideƱas 2016/17
  2324.      *
  2325.      * @Route("/navidad/{licencia}", name="navidad")
  2326.      */
  2327.     public function navidad($licencia)
  2328.     {
  2329.         $key $this->getParameter('secret');
  2330.         $token UtilStatic::encriptar($licencia "-" 2017$key);
  2331.         return $this->redirect($this->generateUrl('felicitacion_navidad', array("token" => $token)));
  2332.         /*
  2333.           $jugador = $this->em->getRepository(Jugador::class)->findOneBy(array('licencia' => $licencia));
  2334.           if (!$jugador) {
  2335.           //creamos un jugador por defecto si no existe, para que vaya a la pagina de club de la federacion
  2336.           $jugador = new Jugador(__METHOD__);
  2337.           $jugador->setNombre("Golfista");
  2338.           $jugador->setLicencia("AM00123456");
  2339.           }
  2340.           $competiciones = $this->em->getRepository(Inscrito::class)->getCompeticionesAnualLicencia($licencia, "2016");
  2341.           return array('jugador' => $jugador,
  2342.           'competiciones' => $competiciones
  2343.           );
  2344.          * */
  2345.     }
  2346.     //    Pablo 10/08/2023: Se comenta ya que estan llegando muchos errores a esta pagina (posiblemente un bot);
  2347.     //    y asi evitar el bombardeo de emails de error en esta pagina obsoleta y sin mantenimiento
  2348.     // /**
  2349.     //  * F-074 Cambio de handicap de un jugador tras competicion
  2350.     //  *
  2351.     //  * @Route("/cambio-hcp/{id}/{orden}/{ccc}", name="cambio_hcp", defaults={ "ccc" = 0 })
  2352.     //  */
  2353.     // public function cambioHcp($id, $orden, $ccc) {
  2354.     //     $inscrito = $this->em->getRepository(Inscrito::class)->find($id);
  2355.     //     if (!$inscrito) {
  2356.     //         $this->addFlash(
  2357.     //                 'error', "No encontramos el Inscrito que nos ha solicitado");
  2358.     //         return $this->redirect($this->generateUrl('portada'));
  2359.     //     }
  2360.     //     $this->em->getFilters()->disable('softdeleteable');
  2361.     //     $competicion = $inscrito->getCompeticion();
  2362.     //     if (!$competicion || !is_null($competicion->getDeletedAt())) {
  2363.     //         $this->addFlash('error', 'No se ha encontrado la competición');
  2364.     //         return $this->redirect($this->generateUrl('portada'));
  2365.     //     }
  2366.     //     $this->em->getFilters()->enable('softdeleteable');
  2367.     //     //$totalJornadas = count($this->em->getRepository(Jornada'::class->findBy(array('competicion' => $competicion->getId()), array('orden' => 'ASC')));
  2368.     //     $totalJornadas = count($competicion->getJornadas());
  2369.     //     $jornada = $this->em->getRepository(Jornada::class)->findOneBy(array('competicion' => $competicion->getId(), 'orden' => $orden));
  2370.     //     if (!$jornada) {
  2371.     //         $this->addFlash(
  2372.     //                 'error', "No encontramos la Jornada que nos ha solicitado");
  2373.     //         return $this->redirect($this->generateUrl('portada'));
  2374.     //     }
  2375.     //     $hcpInscrito = $inscrito->getHcp();
  2376.     //     //buscamos la categoria de HCP para empezar a mirar la tabla
  2377.     //     $categoria = $this->em->getRepository(CategoriaHandicap::class)->findOneByHandicapRange($hcpInscrito);
  2378.     //     $handicaps = unserialize($inscrito->getHcpSms());
  2379.     //     $diferencia = 0;
  2380.     //     $precision = 1;
  2381.     //     if ($categoria->getId() == 6) {
  2382.     //         $precision = 0;      //Para 6a categoria se redondea sin decimales para que queden numeros enteros
  2383.     //     }
  2384.     //     if ((!isset($handicaps[$orden - 1])) || ($orden == 1)) {
  2385.     //         $diferencia = round($handicaps[$orden] - $inscrito->getHcp(), $precision);
  2386.     //     } else {
  2387.     //         $diferencia = round($handicaps[$orden] - $handicaps[$orden - 1], $precision);
  2388.     //     }
  2389.     //     $array_bajada = array();
  2390.     //     $clasificado = array();
  2391.     //     $acumulado = 0;
  2392.     //     if ($competicion->getFormula() != NULL) {
  2393.     //         if ($competicion->getFormula()->getId() == "S") {
  2394.     //             $clasificaciones = $this->em->getRepository(Clasificacion::class)->findBy(array('competicion' => $competicion->getId(), 'calculo' => 'H'));
  2395.     //             $parciales = $this->em->getRepository(Parcial::class)->findBy(array('jornada' => null, 'clasificacion' => $clasificaciones));
  2396.     //             $clasificado = $this->em->getRepository(Clasificado::class)->findOneBy(array('parcial' => $parciales, 'inscrito' => $inscrito->getId()));
  2397.     //             if ($clasificado) {
  2398.     //                 //buscamos en la zona neutra una vez que sabemos la categoriahcp
  2399.     //                 $tipo_prueba = "i";
  2400.     //                 if ($jornada->getModalidad()->getId() == "P") {
  2401.     //                     $tipo_prueba = "p";
  2402.     //                 }
  2403.     //                 $son18hoyos = true;
  2404.     //                 if ($tipo_prueba != "p") {    //el distinguir entre 18 o 9 hoyos solo tiene sentido para Individual o CanadaCup
  2405.     //                     $jc = $this->em->getRepository(JornadaConfig::class)->findOneBy(array('jornada' => $jornada->getId(), 'categoria' => $inscrito->getCategoria()));
  2406.     //                     if (!empty($jc)) {
  2407.     //                         if ($jc->getHoyos() != "1-18") {
  2408.     //                             $son18hoyos = false;
  2409.     //                         }
  2410.     //                     }
  2411.     //                 }
  2412.     //                 $campoCorto = false;
  2413.     //                 $t = $jornada->getTrazado();
  2414.     //                 if (!is_null($t->getCampoCorto())) {
  2415.     //                     $campoCorto = $t->getCampoCorto();
  2416.     //                 } else {
  2417.     //                     // Consultar a la espaƱola la primera vez y guardar el dato para las siguientes consultas
  2418.     //                     $numero_trazado = $t->spanishFederationNumberCourseFormat();
  2419.     //                     $this->cws->init();
  2420.     //                     //$resultado = $coursews->listar(array("courseCode" => $numero_trazado));
  2421.     //                     //$campoCorto = $resultado->course->shortCourse;
  2422.     //                     $resultado = $this->cws->listar2020(array("courseCode" => $numero_trazado));
  2423.     //                     $campoCorto = $resultado->courses->course->shortCourse; //En este caso solo se busca por un trzado en concreto, por lo que podemos acceder directamente
  2424.     //                     $t->setCampoCorto($campoCorto);
  2425.     //                     $this->em->flush();
  2426.     //                 }
  2427.     //                 $zona_neutra = $this->em->getRepository(ZonaNeutra::class)->findOneBy(array('categoria' => $categoria, 'tipoPrueba' => $tipo_prueba, 'campoCorto' => $campoCorto, 'son18hoyos' => $son18hoyos));
  2428.     //                 $ascValor = $jornada->getAscValor();
  2429.     //                 if ($ascValor == 99) {
  2430.     //                     $ascValor = 2;
  2431.     //                 }
  2432.     //                 $suma_asc_neto = $clasificado->getNeto() + $ascValor;   //$jornada->getAscValor();
  2433.     //                 if ($suma_asc_neto < $zona_neutra->getPuntosMin()) {
  2434.     //                     $array_bajada[$clasificado->getNeto() + $ascValor /* $jornada->getAscValor() */] = $zona_neutra->getSubidaInferiorZn();
  2435.     //                 } else {
  2436.     //                     if ($suma_asc_neto < $zona_neutra->getPuntosMax()) {
  2437.     //                         $array_bajada[$clasificado->getNeto() + $ascValor /* $jornada->getAscValor() */] = 0;
  2438.     //                     } else {
  2439.     //                         if ($suma_asc_neto > 72) {
  2440.     //                             $suma_asc_neto = 72;
  2441.     //                         }
  2442.     //                         if ($tipo_prueba == "i") {
  2443.     //                             for ($b = ($zona_neutra->getPuntosMax() + 1); $b <= $suma_asc_neto; $b++) {
  2444.     //                                 $bajada = $this->em->getRepository(Bajada::class)->findBajadasExact($b, $categoria->getId(), $tipo_prueba, $campoCorto);
  2445.     //                                 $array_bajada[$b] = $bajada->getBajada();
  2446.     //                                 $acumulado += $bajada->getBajada();
  2447.     //                                 //comprobamos si tenemos que actualizar categoria para cambiar los valores
  2448.     //                                 $acu = $inscrito->getHcp() + $acumulado;
  2449.     //                                 if (($acu < $categoria->getHcpMin()) || ($acu > $categoria->getHcpMax())) {
  2450.     //                                     $categoria = $this->em->getRepository(CategoriaHandicap::class)->findOneByHandicapRange($inscrito->getHcp() + $acumulado);
  2451.     //                                 }
  2452.     //                             }
  2453.     //                         } else {
  2454.     //                             $bajada = $this->em->getRepository(Bajada::class)->findBajadasExact($suma_asc_neto, $categoria->getId(), $tipo_prueba, $campoCorto);
  2455.     //                             $array_bajada[$suma_asc_neto] = $bajada->getBajada();
  2456.     //                             $acumulado += $bajada->getBajada();
  2457.     //                         }
  2458.     //                     }
  2459.     //                 }
  2460.     //             }
  2461.     //         }
  2462.     //     }
  2463.     //     $jugador = $inscrito->getjugador();
  2464.     //     $fb = $this->createFormBuilder($jugador, array('action' => $this->generateUrl('tour_autocomplete_update_rgpd'), 'method' => 'POST'))
  2465.     //             ->add('newsletters', CheckboxType::class, array('mapped' => false, "label" => "TambiĆ©n quiero recibir newsletters", "required" => false, "attr" => array("checked" => (strpos($competicion->getOrganizador()->getId(), "AM") !== false))))
  2466.     //             ->add('organizador', HiddenType::class, array('mapped' => false, 'attr' => array('value' => $competicion->getOrganizador()->getId())))
  2467.     //             ->add('rgpd', HiddenType::class, array('mapped' => false))
  2468.     //             ->add('id', HiddenType::class);
  2469.     //     //$secret = $this->getParameter('secret');
  2470.     //     //if (empty($jugador->getEmail())) {
  2471.     //     if (empty($jugador->getEmailCod())) {
  2472.     //         $fb->add('email', EmailType::class, array("label" => false, "required" => false, "attr" => array("placeholder" => "Introduzca email")));
  2473.     //     }
  2474.     //     $form = $fb->getForm();
  2475.     //     return $this->render("frontend/Default/cambioHcp.html.twig", [
  2476.     //                 'hcp'           => $handicaps[$orden],
  2477.     //                 'diferencia'    => $diferencia,
  2478.     //                 'competicion'   => $competicion,
  2479.     //                 'clasificado'   => $clasificado,
  2480.     //                 'orden'         => $orden,
  2481.     //                 'form'          => $form,
  2482.     //                 'id'            => $id,
  2483.     //                 'ccc'           => $ccc,
  2484.     //                 'inscrito'      => $inscrito,
  2485.     //                 'acumulado'     => round($acumulado, 1), //Es necesario redondear. Se manda para solucionar temporalmente el probblema del campo corto
  2486.     //                 'jornada'       => $jornada,
  2487.     //                 'totalJornadas' => $totalJornadas,
  2488.     //                 'array_bajada'  => $array_bajada
  2489.     //     ]);
  2490.     // }
  2491.     //    /**
  2492.     //     * F-075 Muestra la pagina de información de marketing
  2493.     //     *
  2494.     //     * @Route("/descripcion", name="marketing")
  2495.     //     */
  2496.     //    public function marketing()
  2497.     //    {
  2498.     //        $user = $this->getUser();
  2499.     //
  2500.     //        if (!$this->utilidades->compruebaRol(["NUEVA_FEDE", "PUBLICIDAD"], false)) {
  2501.     //            $this->addFlash(
  2502.     //                'error', "No tiene permisos suficientes para acceder a la pĆ”gina solicitada");
  2503.     //
  2504.     //            return $this->redirect($this->generateUrl('_club', array('id' => 'AM00')));
  2505.     //        }
  2506.     //
  2507.     //        return $this->render("frontend/Default/marketing.html.twig", [
  2508.     //            'user' => $user,
  2509.     //        ]);
  2510.     //    }
  2511.     /**
  2512.      * F-076 Demo de visualización del HĆ”ndicap actual de acceso al campeonato de EspaƱa INFANTIL
  2513.      *
  2514.      * @Route("/acceso-campeonato-rfeg/{licencia}", name="acceso_campeonato_rfeg")
  2515.      */
  2516.     public function accesoCampeonatosEspania($licenciaFederatedWebService $rfeg)
  2517.     {
  2518.         $lic substr($licencia4);
  2519.         $rfeg->init("AM00");
  2520.         //$jugadores = $rfeg->searchByCode(array('federationCode' => $lic));
  2521.         $dataForRequest = ['federatedCodes' => ['federatedCode' => $lic]];
  2522.         $jugadores $rfeg->listByCode2020($dataForRequest);
  2523.         if (isset($jugadores->federateds)) {
  2524.             if (isset($jugadores->federateds->federated)) {
  2525.                 $jugador $this->em->getRepository(Jugador::class)->findByLicenciaCortaNoTemporal($lic);
  2526.                 if (!$jugador) {
  2527.                     $jugador = new Jugador(__METHOD__);
  2528.                 }
  2529.                 $dataFromFederated $jugadores->federateds->federated;
  2530.                 $saceDataRequest $rfeg->getSACEData($dataForRequest);
  2531.                 $saceData $saceDataRequest->federateds->federated ?? null;
  2532.                 $this->updatePlayerFromFederated->__invoke($dataFromFederated$saceData$jugador);
  2533.             }
  2534.             //vemos si es el tercer o cuarto mejor handicap
  2535.             $posicionHcp = ($jugador->getNivel()->getId() != "B") ? 3;
  2536.             return $this->render("frontend/Default/acceso_campeonato_rfeg.html.twig", [
  2537.                 'jugador' => $jugador,
  2538.                 'posicionHcp' => $posicionHcp,
  2539.             ]);
  2540.         } else {
  2541.             $this->addFlash('error''No existen datos para ese jugador');
  2542.             return $this->redirect($this->generateUrl('competiciones_abiertas'));
  2543.         }
  2544.     }
  2545.     /**
  2546.      * @Route("/calculo-hcpjuego", name="nxt_calculo_hcpjuego", options={"expose"=true})
  2547.      */
  2548.     public function calculoHcpjuego(Request $request)
  2549.     {
  2550.         $data $request->request;
  2551.         $hcp str_replace(",""."$data->get('handicap')); //arreglo que en JS no funcionaba
  2552.         $tramo $data->get('tramo');
  2553.         $barraNombre $data->get('barra');
  2554.         $trazadoNombre $data->get('trazado');
  2555.         $porcentaje $data->get('porcentaje');
  2556.         $parAnt 0;
  2557.         $hcps_juego = array();
  2558.         $trazado_barra $this->em->getRepository(TrazadoBarra::class)->getTrazadoBarraByName($trazadoNombre$barraNombre);
  2559.         foreach ($trazado_barra as $tb) {
  2560.             $vs $tb["slope"];
  2561.             $vc $tb["campo"];
  2562.             $par $tb["par"];
  2563.             switch ($tramo) {
  2564.                 case "1-9":
  2565.                     $vs $tb["slope19"];
  2566.                     $vc $tb["campo19"];
  2567.                     $par $tb["par19"];
  2568.                     break;
  2569.                 case "10-18":
  2570.                     $vs $tb["slope1018"];
  2571.                     $vc $tb["campo1018"];
  2572.                     $par $tb["par1018"];
  2573.                     break;
  2574.             }
  2575.             if (!$par || $par == 0) {
  2576.                 $par $parAnt;
  2577.             }
  2578.             $hcps_juego[$tb["sexo"]] = null;
  2579.             if (!is_null($vs) && !is_null($vc) && ($par != 0)) {
  2580.                 $hcps_juego[$tb["sexo"]] = Tarjetas::calcularHcpJuego(null$hcp$vs$vc$par$tramo$porcentaje);
  2581.             }
  2582.             $parAnt $par;
  2583.         }
  2584.         return new JsonResponse($hcps_juego);
  2585.     }
  2586.     /**
  2587.      * F-079 Calcula el handicap de juego de un jugador para la vista de calculadora de club
  2588.      *
  2589.      * TODO Ya existe funcion "nxt_calculo_hcpjuego" que sustituye a esta, cuando se introduzca el nuevo componente en nextcaddy se debera eliminar
  2590.      *
  2591.      * @Route("/calculadora", name="nextcaddy_calculadora_hcpjuego", options={"expose"=true})
  2592.      */
  2593.     public function calculadoraHcpJuego(Request $request)
  2594.     {
  2595.         $data $request->request;
  2596.         $hcp str_replace(",""."$data->get('handicap'));   //arreglo que en JS no funcionaba
  2597.         $hoyo $data->get('hoyo');
  2598.         $barra $data->get('barra');
  2599.         $trazado $data->get('trazado');
  2600.         $parAnt 0;
  2601.         $hcps_juego = array();
  2602.         $trazado_barra $this->em->getRepository(TrazadoBarra::class)->findBy(array('trazado' => $trazado'barra' => $barra'activo' => 1));
  2603.         foreach ($trazado_barra as $tb) {
  2604.             $hoyos '1-18';
  2605.             $vs $tb->getSlope();
  2606.             $vc $tb->getCampo();
  2607.             $par $tb->getPar();
  2608.             switch ($hoyo) {
  2609.                 case 1:
  2610.                     $hoyos '1-9';
  2611.                     $vs $tb->getSlope19();
  2612.                     $vc $tb->getCampo19();
  2613.                     $par $tb->getPar19();
  2614.                     break;
  2615.                 case 2:
  2616.                     $hoyos '10-18';
  2617.                     $vs $tb->getSlope1018();
  2618.                     $vc $tb->getCampo1018();
  2619.                     $par $tb->getPar1018();
  2620.                     break;
  2621.             }
  2622.             //$limites = explode("-", $hoyos);
  2623.             //$par = $this->em->getRepository(Hoyo::class)->getSumaPar($tb->getId(), $limites[0], $limites[1]);
  2624.             if (!$par || $par == 0) {
  2625.                 $par $parAnt;
  2626.             }
  2627.             $hcps_juego[$tb->getSexo()] = null;
  2628.             if (!is_null($vs) && !is_null($vc) && ($par != 0)) {
  2629.                 $hcps_juego[$tb->getSexo()] = Tarjetas::calcularHcpJuego(null$hcp$vs$vc$par$hoyos);
  2630.             }
  2631.             $parAnt $par;
  2632.         }
  2633.         return new JsonResponse($hcps_juego);
  2634.     }
  2635. //    Esta vista deja de ser accesible, se comenta
  2636. //    /*
  2637. //     * F-080 URL de acceso rapido en la pagina de marketing para usuarios de rol Gerente
  2638. //     *
  2639. //     * @Route("/info", name="info", options={"expose"=true})
  2640. //     *
  2641. //     */
  2642. //    public function accesoGerente() {
  2643. //        $username = "gerente";
  2644. //        $token = strtoupper(sha1($username . $this->getParameter('next.secret')));
  2645. //
  2646. //        return $this->redirect($this->generateUrl('get_auto_login', array('username' => $username, 'token' => $token)));
  2647. //    }
  2648.     /**
  2649.      * F-081 Hace autologin y redirige
  2650.      *
  2651.      * @Route("/redirect-login", name="redirect_login", options={"expose"=true}, methods={"GET"})
  2652.      */
  2653.     public function redirectAutoLogin(Request $request)
  2654.     {
  2655.         $data json_decode(base64_decode($request->query->get("g")));
  2656.         $secret $this->getParameter("secret");
  2657.         $nxtSecret $this->getParameter("next.secret");
  2658.         $id UtilStatic::desencriptar($data->i$secret);
  2659.         $username UtilStatic::desencriptar($data->u$secret);
  2660.         $url UtilStatic::desencriptar($data->r$secret);
  2661.         $token UtilStatic::desencriptar($data->t$secret);
  2662.         $iat = new \DateTime(UtilStatic::desencriptar($data->a$secret));
  2663.         $hoy = new \DateTime("now");
  2664.         if ($hoy->format("U") > $iat->format("U")) {
  2665.             $this->addFlash('error'"Imposible acceder (-1)");
  2666.             return $this->redirect($this->generateUrl("portada"));
  2667.         }
  2668.         $user $this->em->getRepository(User::class)->findOneBy(array('username' => $username"enabled" => 1));
  2669.         if (!$user) {
  2670.             $this->addFlash('error'"Imposible acceder (-2)");
  2671.             return $this->redirect($this->generateUrl("portada"));
  2672.         }
  2673.         if (strtoupper($token) != strtoupper(sha1($nxtSecret UtilStatic::encriptar($username$secret) . $secret))) {
  2674.             $this->addFlash('error'"Imposible acceder (-3)");
  2675.             return $this->redirect($this->generateUrl("portada"));
  2676.         }
  2677.         $roles $user->getRoles();
  2678.         $uspsto = new UsernamePasswordToken($usernull'main'$roles);
  2679.         $this->get('security.token_storage')->setToken($uspsto);
  2680.         $this->get('session')->set('_security_main'serialize($uspsto));
  2681.         return $this->redirect($this->generateUrl($url, ['idc' => $id]));
  2682.     }
  2683.     /**
  2684.      * @Route("/staff-redirect/{params}", name="staff_redirect", methods={"GET"})
  2685.      */
  2686.     public function staffRedirect($params)
  2687.     {
  2688.         $params json_decode(base64_decode($params));
  2689.         $secret $this->getParameter("secret");
  2690.         $nxtSecret $this->getParameter("next.secret");
  2691.         $username UtilStatic::desencriptar($params->username$secret);
  2692.         $token UtilStatic::desencriptar($params->authToken$secret);
  2693.         $url UtilStatic::desencriptar($params->url$secret);
  2694.         $user $this->em->getRepository(User::class)->findOneBy(array('username' => $username"enabled" => 1));
  2695.         if (!$user) {
  2696.             return $this->json([
  2697.                 'success' => false
  2698.             ]);
  2699.         }
  2700.         if (strtoupper($token) != strtoupper(sha1($nxtSecret UtilStatic::encriptar($username$secret) . $secret))) {
  2701.             return $this->json([
  2702.                 'success' => false
  2703.             ]);
  2704.         }
  2705.         $uspsto = new UsernamePasswordToken($usernull'main'$user->getRoles());
  2706.         $this->tokenStorage->setToken($uspsto);
  2707.         $this->session->set('_security_main'serialize($uspsto));
  2708.         return $this->redirect($url);
  2709.     }
  2710.     /**
  2711.      * F-082 Muestra la pagina de suscripcion del telefono
  2712.      *
  2713.      * @Route("/suscripcion/{token}", name="next_suscribe_rgpd", options={"expose"=true})
  2714.      */
  2715.     public function suscripcionRgpd($token)
  2716.     {
  2717.         $key $this->getParameter('secret');
  2718.         $idj UtilStatic::desencriptar($token$key);
  2719.         $jugador $this->em->getRepository(Jugador::class)->find($idj);
  2720.         $clientes $this->em->getRepository(Cliente::class)->findFederaciones();     //findBy(['nombreCorto' => array("AM00", "LV05", "CM41")]);
  2721.         return $this->render("frontend/User/suscribe_rgpd.html.twig", [
  2722.             "idj" => $idj,
  2723.             "clientes" => $clientes,
  2724.             'jugadorRGPD' => $jugador->getPrivacidadAsArray(),
  2725.             'jugador' => $jugador
  2726.         ]);
  2727.     }
  2728.     /**
  2729.      * F-083 Guarda la configuracion de privacidad del jugador
  2730.      *
  2731.      * @Route("/realizar-suscripcion", name="next_realizar_suscripcion", options={"expose"=true}, methods={"POST"})
  2732.      */
  2733.     public function realizarSuscripcion(Request $requestEnvioSms $messagingUtilJugadores $util_jugadores)
  2734.     {
  2735.         $telefono $request->request->get('telefono');
  2736.         $idj $request->request->get('idj');
  2737.         $privacidad = array();
  2738.         //$clientes = $this->em->getRepository(Cliente::class)->findBy(['nombreCorto' => array("AM00", "LV05", "CM41")]);
  2739.         //$clientes = array("AM00", "LV05", "CM41");
  2740.         $clientes $this->em->getRepository(Cliente::class)->findFederaciones();
  2741.         $todas boolval($request->request->get('pTodas'));
  2742.         if ($todas) {
  2743.             foreach ($clientes as $cn) {
  2744.                 $c $cn->getNombreCorto();
  2745.                 $privacidad[$c] = true;
  2746.             }
  2747.         } else {
  2748.             foreach ($clientes as $cn) {
  2749.                 $c $cn->getNombreCorto();
  2750.                 $privacidad[$c] = boolval($request->request->get('p' $c));
  2751.             }
  2752.         }
  2753.         $jugador $this->em->getRepository(Jugador::class)->find($idj);
  2754.         if ($jugador) {
  2755.             $jpriv $jugador->getPrivacidadSimple();
  2756.             $tel $util_jugadores->getDatoPlanoDesdeJugador($jugador"Telefono");
  2757.             if ($telefono != $tel) {
  2758.                 $log_message "Cambio de telĆ©fono del Jugador " $jugador->getNombreCompleto() . " (" $jugador->getLicencia() . ") en el mĆ©todo " __METHOD__ ", de " . ($tel ?: "(vacio)") . " a " $telefono;
  2759.                 $jugador $util_jugadores->setDatoPlanoDesdeJugador($jugador"Telefono"$telefonofalse);
  2760.                 $log = new \App\Entity\Backend\Log('i'$log_messagenull);
  2761.                 $this->em->persist($log);
  2762.             }
  2763.             $new false;
  2764.             foreach ($privacidad as $key => $priv) {
  2765.                 if ($priv) {
  2766.                     if (isset($jpriv[$key])) {
  2767.                         $jugadorRGPD $this->em->getRepository(JugadorRGPD::class)->findBy(['jugador' => $jugador'aceptacion' => $key])[0];
  2768.                     } else {
  2769.                         $jugadorRGPD = new JugadorRGPD();
  2770.                         $jugadorRGPD->setCliente($this->em->getRepository(Cliente::class)->findOneBy(['nombreCorto' => $key]));
  2771.                         $jugadorRGPD->setAceptacion($key);
  2772.                         $jugadorRGPD->setJugador($jugador);
  2773.                         $new true;
  2774.                     }
  2775.                     $jugadorRGPD->setRgpdExtra($request->headers->get("user-agent"));
  2776.                     $jugadorRGPD->setRgpdIP($request->getClientIp());
  2777.                     $jugadorRGPD->setRgpd(true);
  2778.                     if ($new) {
  2779.                         $this->em->persist($jugadorRGPD);
  2780.                     }
  2781.                 }
  2782.             }
  2783.             $this->em->flush();
  2784.             $competi null;
  2785.             $api false;   //mandamos por la api segun corresponda
  2786.             //Buscamos la ultima competicion donde se ha inscrito. Lo normal es que llegue a suscripcion porque se ha inscrito y no tenemos el telefono
  2787.             $inscrito $this->em->getRepository(Inscrito::class)->findOneBy(['jugador' => $jugador], ["created_at" => "DESC"]);
  2788.             if ($inscrito) {
  2789.                 $competi $inscrito->getCompeticion();
  2790.                 $org $competi->getOrganizador()->getCliente()->getId();
  2791.                 $api = ($org >= 3);     //1-RFGA 2-LV05 3-FCG 4y5-FGM
  2792.             }
  2793.             $messaging->enviarSms($telefono"Bienvenido a Nextcaddy, " $jugador->getNombre() . ". " $this->generateUrl('bienvenido_nextcaddy', array('lic' => $jugador->getLicencia()), UrlGeneratorInterface::ABSOLUTE_URL), $competi5$api);
  2794.         }
  2795.         return new JsonResponse(true);
  2796.     }
  2797. // Se elimina esta funcion ya que desaparece el covid de la inscripcion NEX-1838
  2798. //     /**
  2799. //      * F-086 Guardado del FLP. Protocolo covid-19
  2800. //      *
  2801. //      * @Route("/formulario/{idc}", name="_formulario", options={"expose"=true}, methods={"POST"})
  2802. //      */
  2803. //     public function formularioCovid($idc, Request $request, KernelInterface $kernel) {
  2804. //         $competicion = $this->em->getRepository(Competicion::class)->find($idc);
  2805. //         $datos = [];
  2806. //         //$organizadorId = $competicion->getOrganizador()->getId();
  2807. //         /* if (!in_array($organizadorId, ["CM00", "AM00"])) {
  2808. //           return new JsonResponse(["error" => "La competición no estĆ” organizada por la Federación de Golf", "codigo" => false]);
  2809. //           } */
  2810. //         /*
  2811. //           //Se cambia segun tarea NEX-1447-5
  2812. //           if (strpos($competicion->getOrganizador()->getId(), "0") !== false) {
  2813. //           //if ('NEW-FORM' != $competicion->getCodigo() && $competicion->getOrganizador()->getId() != "CM00") {
  2814. //           return new JsonResponse(["error" => "La competición no tiene disponible esta funcionalidad", "codigo" => false]);
  2815. //           } */
  2816. //         $cliente = $competicion->getOrganizador()->getCliente();
  2817. //         $ruta_temporal = $kernel->getProjectDir() . "/public/uploads/inscritoCovid/$idc";
  2818. //         if (!file_exists($ruta_temporal)) {
  2819. //             mkdir($ruta_temporal, 0777, true);
  2820. //         }
  2821. //         $filenameid = sha1(uniqid(mt_rand(), true));
  2822. //         if ($request->request->get('riesgo', 0)) {
  2823. //             $filenameid .= "_x";
  2824. //         }
  2825. //         if (file_exists($ruta_temporal . '/' . $filenameid . '.pdf')) {
  2826. //             unlink($ruta_temporal . '/' . $filenameid . '.pdf');
  2827. //         }
  2828. //         if (in_array($cliente->getId(), [4, 5])) {
  2829. //             $datos['dni'] = $request->request->get('dni');
  2830. //             $params["vulnerable"] = $request->request->get('vulnerable', 0);
  2831. //             if (boolval($params["vulnerable"])) {
  2832. //                 $params["vulnerable_entidad"] = $request->request->get('vulnerable_entidad', "-");
  2833. //                 $params["vulnerable_actividades"] = $request->request->get('vulnerable_actividad', "-");
  2834. //                 $params["vulnerable_fecha"] = $request->request->get('vulnerable_fecha', "-");
  2835. //             }
  2836. //         } elseif (1 == $cliente->getId()) {
  2837. //             $datos['competicion'] = $request->request->get('competicion');
  2838. //             $datos['telefono'] = $request->request->get('telefono', "");
  2839. //             $datos['emailCovid'] = $request->request->get('emailCovid', "");
  2840. //             $datos['ciudad'] = $request->request->get('ciudad');
  2841. //             $params['contacto'] = $request->request->get('contacto');
  2842. //             $params['atencion'] = $request->request->get('atencion');
  2843. //             $params['ambiente'] = $request->request->get('ambiente');
  2844. //             $params['cercana'] = $request->request->get('cercana');
  2845. //             $params['viaje'] = $request->request->get('viaje');
  2846. //             $params['vivir'] = $request->request->get('vivir');
  2847. //             $params['detalles'] = $request->request->get('detalles');
  2848. // //            if(count($competicion->getJornadas()) > 1){
  2849. // //                $params['consciente'] = $request->request->get('detalles');
  2850. // //            }
  2851. //         }
  2852. //         $datos['nombre'] = $request->request->get('nombre');
  2853. //         $params['datos'] = $datos;
  2854. //         $params['firma'] = $request->request->get('firma', null);
  2855. //         $params["propio"] = $request->request->get('propio', 1);
  2856. //         if ($params["propio"] == 0) {
  2857. //             $interesado['nombre'] = $request->request->get('interesado-nombre');
  2858. //             $interesado['dni'] = $request->request->get('interesado-dni', "");
  2859. //         } else {
  2860. //             $interesado['nombre'] = "";
  2861. //             $interesado['dni'] = "";
  2862. //         }
  2863. //         $params['interesado'] = $interesado;
  2864. //         $params['flp'] = $request->request->get('flp', 0);
  2865. //         setlocale(LC_ALL, "es_ES");
  2866. //         $params['fecha'] = strftime("%A %d de %B del %Y");
  2867. //         $params['localidad'] = ucwords($request->request->get('localidad'));
  2868. //         $params['jornadas'] = $competicion->getJornadas();
  2869. //         $html = $this->render('frontend/Competicion/formulario_covid_' . strtolower(substr($cliente->getNombreCorto(), 0, 2)) . '.html.twig', $params);
  2870. //         $myfile = fopen($ruta_temporal . "/" . $filenameid . ".html", "w");
  2871. //         fwrite($myfile, $html);
  2872. //         fclose($myfile);
  2873. //         try {
  2874. //             $isProd = ($kernel->getEnvironment() == 'prod');
  2875. //             if ($_SERVER['SERVER_ADDR'] == "178.33.230.218") {
  2876. //                 $cmd = "/opt/plesk/node/8/bin/relaxed " . $ruta_temporal . "/" . $filenameid . ".html --bo";
  2877. //             } else {
  2878.     // La direccion ha quedado obsoleta
  2879. //                 $cmd = "relaxed " . $ruta_temporal . "/" . $filenameid . ".html --build-once";
  2880. //             }
  2881. //             exec($cmd);
  2882. //             if ($isProd) {
  2883. //                 //Borramos los ficheros temporales generados
  2884. //                 if (file_exists($ruta_temporal . '/' . $filenameid . '.html')) {
  2885. //                     unlink($ruta_temporal . '/' . $filenameid . '.html');
  2886. //                 }
  2887. //                 if (file_exists($ruta_temporal . '/' . $filenameid . '_temp.htm')) {
  2888. //                     unlink($ruta_temporal . '/' . $filenameid . '_temp.htm');
  2889. //                 }
  2890. //             }
  2891. //             $keyAge = $this->getParameter('age.key');
  2892. //             $rutaArchivo = $ruta_temporal . '/' . $filenameid . '.pdf';
  2893. //             if ($isProd) {
  2894. //                 $cmd = "/var/www/vhosts/nextcaddy.com/.linuxbrew/bin/age -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2895. //             } else {
  2896. //                 $cmd = "C:\age\age.exe -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2897. //             }
  2898. //             exec($cmd);
  2899. //             if (file_exists($rutaArchivo) && file_exists($rutaArchivo . ".age")) {
  2900. //                 unlink($rutaArchivo);
  2901. //             }
  2902. //         } catch (\Exception $excptn) {
  2903. //             return new JsonResponse(["error" => "Error generando el PDF", "codigo" => false]);
  2904. //         }
  2905. //         //$file = $ruta_temporal . "/" . $idc . "_formcovid.pdf";
  2906. //         //Si ya tenemos inscrito (es el formulario del horario) entonces aƱadimos el nuevo documento y lo marcamos como ya modificado
  2907. //         $idi = $request->request->get("idi", null);
  2908. //         if (!empty($idi)) {
  2909. //             try {
  2910. //                 $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  2911. //                 if ($inscrito) {
  2912. //                     $documento = new InscritoDocumento();
  2913. //                     $documento->setInscrito($inscrito);
  2914. //                     $documento->setDocumento($filenameid . ".pdf");
  2915. //                     $documento->setTipo(2);
  2916. //                     $inscrito->addDocumento($documento);
  2917. //                     //if (is_null($inscrito->getCovidModif())) {
  2918. //                     //    $inscrito->setCovidModif(0);
  2919. //                     //} else {
  2920. //                     $inscrito->setCovidModif(1);
  2921. //                     //}
  2922. //                     $this->em->flush();
  2923. //                 }
  2924. //             } catch (\Throwable $ex) {
  2925. //                 throw new NotFoundHttpException("Error generando el PDF");
  2926. //             }
  2927. //             //        // Segun la nota informativa del 28/03/2022 se comenta esta parte
  2928. //             //        } else {
  2929. //             //            try {
  2930. //             //                $certificado = $request->files->get("certificado", 0);
  2931. //             //
  2932. //             //                if ($certificado) {
  2933. //             //                    $certname = md5(rand() . "_" . uniqid('certCov19')) . ".pdf";
  2934. //             //
  2935. //             //                    $rutaCarpeta = __DIR__ . '/../../../../web/uploads/inscritoCovid/' . $idc;
  2936. //             //                    $rutaArchivo = $rutaCarpeta . "/" . $certname;
  2937. //             //
  2938. //             //                    $certificado->move($rutaCarpeta, $certname);
  2939. //             //
  2940. //             //                    $keyAge = $this->getParameter('age.key');
  2941. //             //                    $isProd = ($kernel->getEnvironment() == 'prod');
  2942. //             //                    if ($isProd) {
  2943. //             //                        $cmd = "/var/www/vhosts/nextcaddy.com/.linuxbrew/bin/age -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2944. //             //                    } else {
  2945. //             //                        $cmd = "C:\age\age.exe -r " . $keyAge . " " . $rutaArchivo . " > " . $rutaArchivo . ".age";
  2946. //             //                    }
  2947. //             //                    exec($cmd);
  2948. //             //
  2949. //             //                    if (file_exists($rutaArchivo) && file_exists($rutaArchivo . ".age")) {
  2950. //             //                        unlink($rutaArchivo);
  2951. //             //                    }
  2952. //             //                } else {
  2953. //             //                    $certname = 0;
  2954. //             //                }
  2955. //             //            } catch (\Throwable $ex) {
  2956. //             //                $log_message = "Error guardando fichero certificado covid " . $idc;
  2957. //             //                $log = new Log('i', $log_message, null);
  2958. //             //                $this->em->persist($log);
  2959. //             //                $this->em->flush();
  2960. //             //            }
  2961. //         }
  2962. //         $flp = $request->request->get("flp", 0);
  2963. //         if ($flp) {
  2964. //             $this->addFlash(
  2965. //                     'success', "Formulario rellenado correctamente");
  2966. //         }
  2967. //         return new JsonResponse(["file" => $filenameid . ".pdf", "codigo" => true /* , "certificado" => $certname */]);
  2968. //     }
  2969. // Se elimina esta funcion ya que desaparece el covid de la inscripcion NEX-1838
  2970.     // /**
  2971.     //  * F-087 Mostrar formulario FLP - Protocolo covid-19
  2972.     //  *
  2973.     //  * @Route("/flp/{idc}/{idi}", name="flp", options={"expose"=true})
  2974.     //  */
  2975.     // function formularioFLP($idc, $idi) {
  2976.     //     $competicion = $this->em->getRepository(Competicion::class)->find($idc);
  2977.     //     if (!$competicion) {
  2978.     //         $this->addFlash('error', "El torneo buscado no existe");
  2979.     //         return $this->redirect($this->generateUrl('portada'));
  2980.     //     }
  2981.     //     $inscrito = $this->em->getRepository(Inscrito::class)->find($idi);
  2982.     //     if (!$inscrito) {
  2983.     //         $this->addFlash('error', "No se ha encontrado al jugador solicitado");
  2984.     //         return $this->redirect($this->generateUrl('_tournament', array('id' => $idc)));
  2985.     //     }
  2986.     //     $secret = $this->getParameter('secret');
  2987.     //     return $this->render("frontend/Default/flp.html.twig", [
  2988.     //                 'competicion' => $competicion,
  2989.     //                 'jornadas'    => $competicion->getJornadas(),
  2990.     //                 'inscrito'    => $inscrito,
  2991.     //                 'secret'      => $secret
  2992.     //     ]);
  2993.     // }
  2994.     /**
  2995.      * F-158 - Mostrar url tokenizada de archivo
  2996.      *
  2997.      * @Route("/resource/{token}", name="resource", options={"expose"=true})
  2998.      *
  2999.      */
  3000.     public function mostrarArchivo($token): Response
  3001.     {
  3002.         try {
  3003.             $ruta explode("|"UtilStatic::desencriptarNew($token$this->getParameter('secret')));
  3004.             $response = new BinaryFileResponse($ruta[1]);
  3005.             switch ($ruta[2]) {
  3006.                 case 'txt':
  3007.                     $documento 'Documento.txt';
  3008.                     break;
  3009.                 case 'exe':
  3010.                     $documento 'Programa.exe';
  3011.                     break;
  3012.                 case 'zip':
  3013.                     $documento 'Programa.zip';
  3014.                     break;
  3015.                 case 'rar':
  3016.                     $documento 'Programa.rar';
  3017.                     break;
  3018.                 default:
  3019.                     $documento 'Documento.pdf';
  3020.                     break;
  3021.             }
  3022.             $response->setContentDisposition(
  3023.                 ResponseHeaderBag::DISPOSITION_INLINE$documento$documento
  3024.             );
  3025.         } catch (\Exception $e) {
  3026.             throw new \Exception("Error, no existe el documento");
  3027.         }
  3028.         return $response;
  3029.     }
  3030.     /**
  3031.      * @param \Symfony\Component\Form\FormInterface $form
  3032.      * @param EnvioCorreo $mailer
  3033.      * @return void
  3034.      */
  3035.     public function sendContact(\Symfony\Component\Form\FormInterface $formEnvioCorreo $mailer): bool
  3036.     {
  3037.         $formData $form->getData();
  3038.         $msg "<br>" $formData['message'];
  3039.         $msg .= "<br><br> [Nombre: " . ($formData['name'] ?? "Sin especificar") . ", Email: " . ($formData['email'] ?? "Sin especificar") . ", Club: " . ($formData['club'] ?? "Sin especificar") . ", License: " . ($formData['license'] ?? "Sin especificar") . "]";
  3040.         $emailStatus $mailer->enviarCorreo([
  3041.             "to" => "info@nextcaddy.com",
  3042.             "subject" => "Mensaje de contacto",
  3043.             "html" => $msg
  3044.         ]);
  3045.         if ($emailStatus) {
  3046.             $this->addFlash("success""Se ha enviado tu mensaje");
  3047.             return true;
  3048.         } else {
  3049.             $this->addFlash("error""No se ha podido enviar tu mensaje");
  3050.             return false;
  3051.         }
  3052.     }
  3053.     /**
  3054.      *
  3055.      * @Route("/lionsLanding", name="lions_landing", options={"expose"=true})
  3056.      *
  3057.      */
  3058.     public function lionsLanding(): Response
  3059.     {
  3060.         return $this->render('frontend/Landing/lions2026.html.twig');
  3061.     }
  3062.     //    /**
  3063.     //     * @Route("/livescoring-new-template", name="livescoring_new_template")
  3064.     //     */
  3065.     //    public function livescoringNewTemplate(): Response
  3066.     //    {
  3067.     //        return $this->render('frontend/Default/livescoring_new_template.html.twig');
  3068.     //    }
  3069. }