src/Controller/AgendaController.php line 525

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Agenda;
  4. use App\Entity\Especialidad;
  5. use App\Entity\AgendaArchivos;
  6. use App\Entity\ExamenOrden;
  7. use App\Entity\ExamenDetalle;
  8. use App\Entity\HistoriaClinica;
  9. use App\Entity\LogAgenda;
  10. use App\Entity\PacienteReferencia;
  11. use App\Entity\Unidad;
  12. use App\Entity\Preparacion;
  13. use App\Entity\Procedimientos;
  14. use App\Entity\User;
  15. use App\Entity\AgendaProcedimiento;
  16. use App\Entity\OrdenVentaDetalle;
  17. use App\Form\AgendaType;
  18. use App\Form\AgendaReunionType;
  19. use App\Form\PacienteReferenciaType;
  20. use App\Form\CotizacionType;
  21. use App\Form\ExamenOrdenTypeRecepcion;
  22. use App\Form\ExamenDetalleType;
  23. use App\Form\ExamenDetalleCotizacionType;
  24. use App\Form\AgendaTypeEdit;
  25. use App\Form\AgendaTypeConfirm;
  26. use App\Form\AgendaTypeAdmision;
  27. use App\Form\AgendaProcedimientoType;
  28. use App\Repository\AgendaRepository;
  29. use App\Repository\PacienteReferenciaRepository;
  30. use App\Repository\ProcedimientosRepository;
  31. use App\Repository\OrdenVentaRepository;
  32. use App\Repository\HistoriaClinicaRepository;
  33. use App\Repository\ExamenOrdenRepository;
  34. use App\Repository\PreparacionRepository;
  35. use App\Form\BuscaPreparacionType_pac_rpt_anuladas;
  36. use App\Repository\UserRepository;
  37. use App\Repository\TipoUsuarioRepository;
  38. use App\Repository\SeguroPrivadoRepository;
  39. use App\Repository\EmpresaRepository;
  40. use App\Repository\LabProtocoloRepository;
  41. use App\Repository\UnidadRepository;//RECUERDA QUE ES LA MISMA QUE LA ESPECIALIDAD
  42. use App\Repository\EspecialidadRepository;
  43. use App\Repository\RecetaRepository;
  44. use App\Repository\TurnoRepository;
  45. use App\Repository\PacienteRepository;
  46. use App\Repository\SalaRepository;
  47. use App\Repository\FormaPagoRepository;
  48. use App\Repository\MaestroDocumentosRepository;
  49. use App\Repository\AgendaArchivosRepository;
  50. use App\Repository\LogAgendaRepository;
  51. use App\Repository\OrdenVentaDetalleRepository;
  52. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  53. use Symfony\Component\HttpFoundation\Request;
  54. use Symfony\Component\HttpFoundation\Response;
  55. use Symfony\Component\Routing\Annotation\Route;
  56. use Symfony\Component\Security\Core\Security;
  57. use Symfony\Component\Filesystem\Filesystem;
  58. use Knp\Component\Pager\PaginatorInterface;
  59. use App\Form\BuscaPreparacionType;
  60. use App\Form\BuscaPreparacionType_pac;
  61. use App\Form\BuscaPreparacionType_pac_rpt;
  62. use App\Form\BuscaPreparacionType_pac_rpt_laboratorio;
  63. use App\Form\AgendaTypeEditReunion;
  64. use App\Form\BuscaPreparacionType_seguros;
  65. use App\Form\BuscaPreparacionType_segurosCorte;
  66. use Dompdf\Dompdf;
  67. use Dompdf\Options;
  68. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  69. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  70. use PhpOffice\PhpSpreadsheet\Writer\Xls;
  71. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  72. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  73. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  74. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  75. use PhpOffice\PhpSpreadsheet\Style\Fill;
  76. use PhpOffice\PhpSpreadsheet\Style\Border;
  77. use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
  78. use Symfony\Component\HttpFoundation\JsonResponse;
  79. $ordenVentaRepository;
  80. /**
  81.  * @Route("/agenda")
  82.  */
  83. class AgendaController extends AbstractController
  84. {
  85.     /**
  86.      * @var Security
  87.      */
  88.     private $security;
  89.     public function __construct(Security $security)
  90.     {
  91.        date_default_timezone_set("America/Guayaquil");
  92.        $this->security $security;
  93.     }
  94.     
  95.     /**
  96.      * @Route("/", name="agenda_index", methods={"GET"})
  97.      */
  98.     public function index(AgendaRepository $agendaRepositorySalaRepository $salaRepositoryRequest $requestUnidadRepository $unidadRepositoryTurnoRepository $turnoRepository): Response
  99.     {
  100.         //$salas = $salaRepository->findBy(['estado' => '1']);
  101.         $unidades $unidadRepository->findBy(['estado' => '1']);
  102.         $session $request->getSession();
  103.         $session->set('fecha_pos',date("Y-m-d"));
  104.         $turno $turnoRepository->find(1);
  105.                
  106.         return $this->render('agenda/index.html.twig', [
  107.             'unidades' => $unidades,
  108.             'turno'    => $turno
  109.         ]);
  110.     }
  111.     
  112.     /**
  113.      * @Route("/gastro/procs", name="agenda_index_gastro", methods={"GET"})
  114.      */
  115.     public function index_gastro(AgendaRepository $agendaRepositorySalaRepository $salaRepositoryRequest $requestUnidadRepository $unidadRepositoryTurnoRepository $turnoRepository): Response
  116.     {
  117.         //$salas = $salaRepository->findBy(['estado' => '1']);
  118.         $unidades $unidadRepository->findBy(['nombre' => 'PROCEDIMIENTOS ENDOSCOPICOS']);
  119.         $session $request->getSession();
  120.         $session->set('fecha_pos',date("Y-m-d"));
  121.         $turno $turnoRepository->find(1);
  122.                
  123.         return $this->render('agenda/index.html.twig', [
  124.             'unidades' => $unidades,
  125.             'turno'    => $turno
  126.         ]);
  127.     }
  128.     
  129.      /**
  130.      * @Route("/quirofano/procs", name="agenda_index_quirofano", methods={"GET"})
  131.      */
  132.     public function index_quirofano(AgendaRepository $agendaRepositorySalaRepository $salaRepositoryRequest $requestUnidadRepository $unidadRepositoryTurnoRepository $turnoRepository): Response
  133.     {
  134.         //$salas = $salaRepository->findBy(['estado' => '1']);
  135.         $unidades $unidadRepository->findBy(['nombre' => 'HOSPITAL DEL DIA']);
  136.         $session $request->getSession();
  137.         $session->set('fecha_pos',date("Y-m-d"));
  138.         $turno $turnoRepository->find(1);
  139.                
  140.         return $this->render('agenda/index.html.twig', [
  141.             'unidades' => $unidades,
  142.             'turno'    => $turno
  143.         ]);
  144.     }
  145.     
  146.     /**
  147.      * @Route("/calendar/{id_sala}", name="agenda_calendar", methods={"GET"})
  148.      */
  149.     public function calendar($id_salaRequest $requestEmpresaRepository $empresaRepositorySalaRepository $salaRepository): Response
  150.     {
  151.         $session $request->getSession();
  152.         $session->set('tipo_cal','0');
  153.         $session->set('id_sala',$id_sala);
  154.         $empresa $empresaRepository->find(1);
  155.         
  156.         $sala $salaRepository->find($id_sala);
  157.         
  158.         return $this->render('agenda/calendar.html.twig',['id_sala' => $id_sala'empresa' => $empresa'sala' => $sala]);
  159.     }
  160.     
  161.     /**
  162.      * @Route("/calendar/unidad/{id}", name="agenda_calendar_unidad", methods={"GET"})
  163.      */
  164.     public function calendar_unidad(Request $requestEmpresaRepository $empresaRepositoryUnidad $unidad): Response
  165.     {
  166.         $session $request->getSession();
  167.         $session->set('tipo_cal',$unidad->getId());
  168.         $empresa $empresaRepository->find(1);
  169.         if($unidad->getId()=='1'){
  170.             $id_sala '20';    
  171.         }else{
  172.             $id_sala '33';
  173.         }
  174.         
  175.         $user $this->security->getUser();
  176.         if($user->getId() == '2'){
  177.             //$id_sala = '1';
  178.         }
  179.         if($user->getId() == '12'){
  180.             //$id_sala = '11';
  181.         }
  182.         $session->set('id_sala',$id_sala);
  183.         
  184.         $session->set('fecha_pos',date("Y-m-d"));
  185.         
  186.         return $this->render('agenda/calendar_unidad.html.twig',['unidad' => $unidad'tipo' => null]);
  187.     }
  188.     
  189.     /**
  190.      * @Route("/calendar/unidad/tipo/{id}", name="agenda_calendar_unidad_tipo", methods={"GET"})
  191.      */
  192.     public function calendar_unidad_tipo(Request $requestEmpresaRepository $empresaRepositoryUnidad $unidad): Response
  193.     {
  194.         $session $request->getSession();
  195.         $session->set('tipo_cal',$unidad->getId());
  196.         $empresa $empresaRepository->find(1);
  197.         if($unidad->getId()=='1'){
  198.             $id_sala '20';    
  199.         }else{
  200.             $id_sala '33';
  201.         }
  202.         
  203.         $user $this->security->getUser();
  204.         if($user->getId() == '2'){
  205.             //$id_sala = '1';
  206.         }
  207.         if($user->getId() == '12'){
  208.             //$id_sala = '11';
  209.         }
  210.         $session->set('id_sala',$id_sala);
  211.         
  212.         $session->set('fecha_pos',date("Y-m-d"));
  213.         
  214.         return $this->render('agenda/calendar_unidad.html.twig',['unidad' => $unidad'tipo' => 'privado']);
  215.     }
  216.     /**
  217.      * @Route("/new", name="agenda_new", methods={"GET","POST"})
  218.      */
  219.     public function new(Request $request): Response
  220.     {
  221.         $agenda = new Agenda();
  222.         $form $this->createForm(AgendaType::class, $agenda);
  223.        
  224.         $form->handleRequest($request);
  225.         //dd($agenda);
  226.         if ($form->isSubmitted() && $form->isValid()) {
  227.             $entityManager $this->getDoctrine()->getManager();
  228.             $entityManager->persist($agenda);
  229.             $entityManager->flush();
  230.             return $this->redirectToRoute('agenda_index');
  231.         }
  232.         //dd($form->createView());
  233.         return $this->render('agenda/new.html.twig', [
  234.             'agenda' => $agenda,
  235.             'form' => $form->createView(),
  236.         ]);
  237.     }
  238.     /**
  239.      * @Route("/new_modal", name="agenda_new_modal", methods={"GET"})
  240.      */
  241.     public function new_modal(Request $requestPacienteRepository $pacienteRepositorySalaRepository $salaRepositoryUserRepository $userRepositoryEspecialidadRepository $especialidadRepository): Response
  242.     {
  243.         $agenda      = new Agenda();
  244.         $session     $request->getSession();
  245.         //dd($session->get('tipo_cal'), $session->get('id_sala'));
  246.         if($session->get('tipo_cal') == '0'){//VIENE POR MEDICO
  247.         }
  248.         $id_sala     $session->get('id_sala');
  249.         $id_paciente $session->get('id_paciente');
  250.         $paciente    $pacienteRepository->find($id_paciente);
  251.         $sala        $salaRepository->find($id_sala);//dd($sala);
  252.         $sala_doctor 0;$especialidad null$nunidad null;
  253.         $nunidad $sala->getUnidad()->getNombre();
  254.         $doctor null;
  255.         if($sala->getIdDoctor()!=null){//dd($sala->getIdDoctor());
  256.             $sala_doctor $sala->getIdDoctor();
  257.             $doctor $userRepository->find($sala_doctor);//dd($doctor);
  258.             $especialidad $doctor->getEspecialidad();
  259.         }else{
  260.             if($sala->getUnidad()->getId()=='1'){
  261.                 $especialidad $especialidadRepository->find('1'); 
  262.             }else{
  263.                 $especialidad $especialidadRepository->find('17'); 
  264.             }
  265.         }
  266.         //dd($nunidad, $sala_doctor,$doctor,$especialidad->getNombre());
  267.         $agenda->setEspecialidad($especialidad);
  268.         $agenda->setSeguro($paciente->getSeguro());
  269.         //dd($sala->getUnidad(),$sala_doctor, $especialidad, $nunidad);
  270.         if($sala->getUnidad()->getId()== '1' and $doctor == null){
  271.             $doctor $userRepository->find(2);//dd($doctor);
  272.             $agenda->setDoctor($doctor);
  273.             $especialidad $doctor->getEspecialidad();
  274.             $agenda->setEspecialidad($especialidad);
  275.         }
  276.         if($sala->getUnidad()->getId()== '2' and $doctor == null){
  277.             $doctor $userRepository->find(12);//dd($doctor);
  278.             $agenda->setDoctor($doctor);
  279.             $especialidad $doctor->getEspecialidad();
  280.             $agenda->setEspecialidad($especialidad);
  281.             //dd($especialidad);
  282.         }
  283.         //dd($agenda);
  284.         $form $this->createForm(AgendaType::class, $agenda, ['doctor' => $sala_doctor'especialidad' => $especialidad->getId(), 'unidad' => $nunidad'paciente' => $paciente ]);
  285.         //dd($form);
  286.         $form->handleRequest($request);
  287.         /*if ($form->isSubmitted() && $form->isValid()) {
  288.             $entityManager = $this->getDoctrine()->getManager();
  289.             $entityManager->persist($agenda);
  290.             $entityManager->flush();
  291.             return $this->redirectToRoute('agenda_index');
  292.         }*/
  293.         return $this->render('agenda/new_modal.html.twig', [
  294.             'agenda'   => $agenda,
  295.             'form'     => $form->createView(),
  296.             'paciente' => $paciente,
  297.             'sala'     => $sala
  298.         ]);
  299.     }
  300.     
  301.     /**
  302.      * @Route("/new_modal/storage", name="agenda_new_modal_storage", methods={"POST"})
  303.      */
  304.     public function new_modal_storage(Request $requestPacienteRepository $pacienteRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroRepositoryEspecialidadRepository $unidadRepositoryUserRepository $userRepositoryEspecialidadRepository $especialidadRepository): Response
  305.     {
  306.         $hoy         = new \DateTime("now");
  307.         $logagenda   = new LogAgenda();
  308.         $ip          $request->getClientIp();
  309.         $agenda      = new Agenda();
  310.         $session     $request->getSession();
  311.         $id_sala     $session->get('id_sala');
  312.         $id_paciente $session->get('id_paciente');
  313.         $paciente    $pacienteRepository->find($id_paciente);
  314.         $sala        $salaRepository->find($id_sala);
  315.         $sala_doctor 0;$especialidad null$nunidad null;
  316.         $nunidad $sala->getUnidad()->getNombre();
  317.         if($sala->getIdDoctor()!=null){
  318.             $sala_doctor $sala->getIdDoctor();
  319.             $doctor $userRepository->find($sala_doctor);
  320.             $especialidad $doctor->getEspecialidad();
  321.     
  322.         }else{        
  323.             if($sala->getUnidad()->getId()=='1'){  
  324.                 $especialidad $especialidadRepository->find('1'); 
  325.             }else{
  326.                 $especialidad $especialidadRepository->find('17');                 
  327.             }
  328.         }
  329.         $agenda->setEspecialidad($especialidad);
  330.         $form $this->createForm(AgendaType::class, $agenda, ['doctor' => $sala_doctor'especialidad' => $especialidad'unidad' => $nunidad'paciente' => $paciente ]);
  331.         $form->handleRequest($request);
  332.         if($id_sala == '20' || $id_sala == '33'){
  333.             $sala        $salaRepository->findOneBy(['id_doctor' => $agenda->getDoctor()->getId()]);
  334.             $session->set('id_sala',$sala->getId());
  335.         }
  336.         $session   $request->getSession();
  337.         $fecha_pos date_format($form->get('inicio')->getData(),'Y-m-d');
  338.         $hoy       date_format($hoy,'Y-m-d');
  339.         $session->set('fecha_pos',$fecha_pos);
  340.         $user $this->security->getUser();
  341.         
  342.         //dd($form->getErrors(true));
  343.         if ($form->isSubmitted() && $form->isValid()) {
  344.             //dd($form->get('procedimiento')->getData());
  345.             $xprocedimientos $form->get('procedimiento')->getData();
  346.             $inicio $form->get('inicio')->getData();
  347.             // ✅ Validación de duplicados
  348.             $agendaExistente $this->getDoctrine()->getManager()
  349.                 ->getRepository(Agenda::class)
  350.                 ->findOneBy([
  351.                     'sala'     => $sala,
  352.                     'paciente' => $paciente,
  353.                     'inicio'   => $inicio,
  354.                     'estado'   => '1'
  355.                 ]);
  356.             $adm 'no';
  357.             if ($agendaExistente) {
  358.                 return $this->json(['estado' => 'no''agenda' => $agenda->getId(), 'admision' => $adm'msn' => 'Ya existe una agenda para este paciente']);
  359.             }
  360.             $entityManager $this->getDoctrine()->getManager();
  361.             $agenda->setEstado(1);
  362.             $agenda->setPaciente($paciente);
  363.             $agenda->setSala($sala);
  364.             $agenda->setIpCrea($ip);
  365.             $agenda->setIpModifica($ip);
  366.             
  367.             if($fecha_pos<=$hoy){
  368.                 $agenda->setEstadoAgenda(2);
  369.                 $adm 'ok';
  370.             }else{
  371.                 $agenda->setEstadoAgenda(2);
  372.                 $adm 'no';
  373.             }
  374.             //dd($adm);
  375.             $agenda->setUserCrea($user->getId());
  376.             $agenda->setUserModifica($user->getId());
  377.             //$logagenda = $agenda->getLogAgendas();
  378.             $logagenda->setSala($sala);
  379.             $logagenda->setIpCrea($ip);
  380.             $logagenda->setIpModifica($ip);
  381.             $logagenda->setEstadoAgenda(2);
  382.             $logagenda->setUserCrea($user->getId());
  383.             $logagenda->setUserModifica($user->getId());
  384.             $inicio          $form->get('inicio')->getData();
  385.             $fin             $form->get('fin')->getData();
  386.             $observacion     $form->get('observacion')->getData();
  387.             $descripcion     'CREAR AGENDA';
  388.             $id_seguro       $form->get('seguro')->getData();
  389.             $seguro          $seguroRepository->find($id_seguro);
  390.             $id_especialidad $form->get('especialidad')->getData();
  391.             $especialidad    $unidadRepository->find($id_especialidad);
  392.             $id_doctor       $form->get('doctor')->getData();
  393.             $doctor          $userRepository->find($id_doctor);
  394.             $logagenda->setInicio($inicio);
  395.             $logagenda->setFin($fin);
  396.             $logagenda->setObservacion($observacion);
  397.             $logagenda->setAgenda($agenda);
  398.             $logagenda->setSeguro($seguro);
  399.             $logagenda->setEspecialidad($especialidad);
  400.             $logagenda->setDoctor($doctor);
  401.             $logagenda->setDescripcion($descripcion);
  402.             $paciente->setSeguro($seguro);
  403.             $xcont 0;
  404.             foreach($xprocedimientos as $xp){
  405.                 if($xcont == 0){
  406.                     $agenda->setProcedimiento($xp);    
  407.                 }
  408.                 $xcont ++;         
  409.             }
  410.             $entityManager->persist($agenda);
  411.             //dd($agenda, $adm);
  412.             //$xcont = 0;
  413.             /*foreach($xprocedimientos as $xp){
  414.                 if($xcont > 0){
  415.                     $agendaProcedimiento = new AgendaProcedimiento();
  416.                     $agendaProcedimiento->setAgenda($agenda);
  417.                     $agendaProcedimiento->setProcedimiento($xp);
  418.                     $agendaProcedimiento->setIpCrea($ip);
  419.                     $agendaProcedimiento->setIpModifica($ip);
  420.                     $agendaProcedimiento->setUserCrea($user->getId());
  421.                     $agendaProcedimiento->setUserModifica($user->getId());
  422.                     $entityManager->persist($agendaProcedimiento);
  423.                 }
  424.                 $xcont ++;         
  425.             }*/
  426.             $entityManager->persist($logagenda);
  427.             $entityManager->persist($paciente);
  428.             $entityManager->flush();
  429.             ///////////////////
  430.             /*$preparacion = $agenda->getPreparacion();
  431.             if($preparacion==null){
  432.                 $preparacion = new Preparacion();
  433.                 $entityManager = $this->getDoctrine()->getManager();
  434.                 $preparacion->setEstado('2');
  435.                 $preparacion->setIpCrea($ip);
  436.                 $preparacion->setIpModifica($ip);
  437.                 $preparacion->setEstatura(1);
  438.                 $preparacion->setPeso(1);
  439.                 $preparacion->setUserCrea($user->getId());
  440.                 $preparacion->setUserModifica($user->getId());
  441.                 $preparacion->setFrecuenciaRespiratoria('0');
  442.                 $preparacion->setSaturacionDeOxigeno('0');
  443.                 $preparacion->setAgenda($agenda);
  444.                 $entityManager->persist($preparacion);
  445.                 $entityManager->flush();
  446.             }    */
  447.             /////////////////////
  448.             $xcont 0;
  449.             // Tomamos la hora base
  450.             $inicioBase = clone $agenda->getInicio();
  451.             $finBase    = clone $agenda->getFin();
  452.             foreach ($xprocedimientos as $xp) {
  453.                 if ($xcont == 0) {
  454.                     $agenda->setReferencia($agenda);
  455.                     $entityManager->persist($agenda);
  456.                     $entityManager->flush();
  457.                 } else {
  458.                     // 👉 Calcular nuevo horario (+30 min por cada procedimiento)
  459.                     $inicioNuevo = (clone $inicioBase)->modify('+' . (30 $xcont) . ' minutes');
  460.                     $finNuevo    = (clone $finBase)->modify('+' . (30 $xcont) . ' minutes');
  461.                     $agendaNueva = new Agenda();
  462.                     $agendaNueva->setInicio($inicioNuevo);
  463.                     $agendaNueva->setFin($finNuevo);
  464.                     $agendaNueva->setPaciente($agenda->getPaciente());
  465.                     $agendaNueva->setSala($agenda->getSala());
  466.                     $agendaNueva->setDoctor($agenda->getDoctor());
  467.                     $agendaNueva->setEspecialidad($agenda->getEspecialidad());
  468.                     $agendaNueva->setSeguro($agenda->getSeguro());
  469.                     $agendaNueva->setProcedimiento($xp);
  470.                     $agendaNueva->setEstado($agenda->getEstado());
  471.                     $agendaNueva->setEstadoAgenda($agenda->getEstadoAgenda());
  472.                     $agendaNueva->setIpCrea($ip);
  473.                     $agendaNueva->setIpModifica($ip);
  474.                     $agendaNueva->setUserCrea($user->getId());
  475.                     $agendaNueva->setUserModifica($user->getId());
  476.                     $agendaNueva->setReferencia($agenda);
  477.                     
  478.                     $entityManager->persist($agendaNueva);
  479.                     // 🔹 Log por cada agenda creada
  480.                     $logagendaNuevo = new LogAgenda();
  481.                     $logagendaNuevo->setAgenda($agendaNueva);
  482.                     $logagendaNuevo->setSala($agendaNueva->getSala());
  483.                     $logagendaNuevo->setInicio($inicioNuevo);
  484.                     $logagendaNuevo->setFin($finNuevo);
  485.                     $logagendaNuevo->setSeguro($agendaNueva->getSeguro());
  486.                     $logagendaNuevo->setEspecialidad($agendaNueva->getEspecialidad());
  487.                     $logagendaNuevo->setDoctor($agendaNueva->getDoctor());
  488.                     $logagendaNuevo->setDescripcion('CREAR AGENDA (PROCEDIMIENTO ADICIONAL)');
  489.                     $logagendaNuevo->setEstadoAgenda(2);
  490.                     $logagendaNuevo->setIpCrea($ip);
  491.                     $logagendaNuevo->setIpModifica($ip);
  492.                     $logagendaNuevo->setUserCrea($user->getId());
  493.                     $logagendaNuevo->setUserModifica($user->getId());
  494.                     $entityManager->persist($logagendaNuevo);
  495.                     $entityManager->flush();
  496.                 }
  497.                 $xcont++;
  498.             }
  499.             return $this->json(['estado' => 'ok''agenda' => $agenda->getId(), 'admision' => $adm'msn' => 'Agenda Guardada con exito']);
  500.         }else{
  501.             //dd($this->getFormErrors($form));
  502.         }
  503.         return $this->json(['estado' => 'no''agenda' => $agenda->getId(), 'admision' => $adm'msn' => 'No guardado con error']);
  504.     }
  505.     
  506.     
  507.     /**
  508.      * @Route("reunion/new_modal/storage", name="agenda_reunion_modal_storage", methods={"POST"})
  509.      */
  510.     public function agenda_reunion_modal_storage(Request $requestPacienteRepository $pacienteRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroRepositoryEspecialidadRepository $unidadRepositoryUserRepository $userRepositoryEspecialidadRepository $especialidadRepositoryProcedimientosRepository $procedimientosRepository): Response
  511.     {
  512.         $hoy         = new \DateTime("now");
  513.         $logagenda   = new LogAgenda();
  514.         $ip          $request->getClientIp();
  515.         $agenda      = new Agenda();
  516.         $session     $request->getSession();
  517.         $id_sala     $session->get('id_sala');
  518.         $paciente    $pacienteRepository->findOneBy(['cedula' => 'REUNION' ]);
  519.         $procedimiento $procedimientosRepository->findOneBy(['nombre'=>'REUNION']);
  520.         $sala        $salaRepository->find($id_sala);
  521.         $sala_doctor 0;$especialidad null$nunidad null;
  522.         $nunidad $sala->getUnidad()->getNombre();
  523.         if($sala->getIdDoctor()!=null){
  524.             $sala_doctor $sala->getIdDoctor();
  525.             $doctor $userRepository->find($sala_doctor);
  526.             $especialidad $doctor->getEspecialidad();
  527.         }else{
  528.             if($sala->getUnidad()->getId()=='1'){
  529.                 $especialidad $especialidadRepository->find('1'); 
  530.             }else{
  531.                 $especialidad $especialidadRepository->find('17'); 
  532.             }            
  533.         }
  534.         $agenda->setEspecialidad($especialidad);
  535.         $seguro $seguroRepository->find(1);
  536.         $form $this->createForm(AgendaReunionType::class, $agenda, ['doctor' => $sala_doctor'especialidad' => $especialidad'unidad' => $nunidad ]);
  537.         $form->handleRequest($request);
  538.         $session   $request->getSession();
  539.         $fecha_pos date_format($form->get('inicio')->getData(),'Y-m-d');
  540.         $hoy       date_format($hoy,'Y-m-d');
  541.         $session->set('fecha_pos',$fecha_pos);
  542.         $user $this->security->getUser();
  543.         //dd($form->getErrors(true));
  544.         if ($form->isSubmitted() && $form->isValid()) {
  545.             $entityManager $this->getDoctrine()->getManager();
  546.             $agenda->setEstado(2);
  547.             $agenda->setPaciente($paciente);
  548.             $agenda->setSeguro($seguro);
  549.             //$agenda->setSala($sala);
  550.             $agenda->setIpCrea($ip);
  551.             $agenda->setIpModifica($ip);
  552.             $agenda->setProcedimiento($procedimiento);
  553.             if($fecha_pos<=$hoy){
  554.                 $agenda->setEstadoAgenda(1);
  555.                 $adm 'ok';
  556.             }else{
  557.                 $agenda->setEstadoAgenda(0);
  558.                 $adm 'no';
  559.             }
  560.             $agenda->setUserCrea($user->getId());
  561.             $agenda->setUserModifica($user->getId());
  562.             //$logagenda = $agenda->getLogAgendas();
  563.             $logagenda->setSala($sala);
  564.             $logagenda->setIpCrea($ip);
  565.             $logagenda->setIpModifica($ip);
  566.             $logagenda->setEstadoAgenda(0);
  567.             $logagenda->setUserCrea($user->getId());
  568.             $logagenda->setUserModifica($user->getId());
  569.             $inicio          $form->get('inicio')->getData();
  570.             $fin             $form->get('fin')->getData();
  571.             $observacion     $form->get('observacion')->getData();
  572.             $descripcion     'CREAR AGENDA';
  573.             
  574.             $id_doctor       $form->get('doctor')->getData();
  575.             $doctor          $userRepository->find($id_doctor);
  576.             $sala            $salaRepository->findOneBy(['id_doctor' => $id_doctor]);
  577.             $agenda->setSala($sala);//dd($agenda);
  578.             $logagenda->setInicio($inicio);
  579.             $logagenda->setFin($fin);
  580.             $logagenda->setObservacion($observacion);
  581.             $logagenda->setAgenda($agenda);
  582.             $logagenda->setSeguro($seguro);
  583.             $logagenda->setEspecialidad($especialidad);
  584.             $logagenda->setDoctor($doctor);
  585.             $logagenda->setDescripcion($descripcion);
  586.             $entityManager->persist($agenda);
  587.             $entityManager->persist($logagenda);
  588.             $entityManager->flush();
  589.             return $this->json(['estado' => 'ok''agenda' => $agenda->getId(), 'admision' => $adm]);
  590.         }else{
  591.             dd($this->getFormErrors($form));
  592.         }
  593.         return $this->json(['estado' => 'no''agenda' => $agenda->getId(), 'admision' => $adm]);
  594.         
  595.         
  596.     }
  597.     
  598.     private function getFormErrors($form)
  599.     {
  600.         $errors = [];
  601.         foreach ($form->getErrors(truetrue) as $error) {
  602.             // Obtén el nombre del campo que causó el error.
  603.             $fieldName $error->getOrigin()->getName();
  604.     
  605.             // Obtén el mensaje de error.
  606.             $errorMessage $error->getMessage();
  607.     
  608.             // Almacena el error junto con el nombre del campo.
  609.             $errors[$fieldName] = $errorMessage;
  610.         }
  611.         return $errors;
  612.     }
  613.     /**
  614.      * @Route("/{id}", name="agenda_show", methods={"GET"})
  615.      */
  616.     public function show(Agenda $agenda): Response
  617.     {
  618.         return $this->render('agenda/show.html.twig', [
  619.             'agenda' => $agenda,
  620.         ]);
  621.     }
  622.     /**
  623.      * @Route("/{id}/edit", name="agenda_edit", methods={"GET","POST"})
  624.      */
  625.     public function edit(Request $requestAgenda $agendaUserRepository $userRepositoryPacienteReferenciaRepository $pacienteReferenciaRepositorySessionInterface $session): Response
  626.     {
  627.         //dd($agenda->getPaciente()->getRegion());
  628.         $pacienteReferencia = new PacienteReferencia();
  629.         $form_referencia $this->createForm(PacienteReferenciaType::class, $pacienteReferencia);
  630.         $form_referencia->handleRequest($request);
  631.         
  632.         $agendaProcedimiento = new AgendaProcedimiento();
  633.         $form_ap $this->createForm(AgendaProcedimientoType::class, $agendaProcedimiento);
  634.         $form_ap->handleRequest($request);
  635.         
  636.         // Obtén la URL actual
  637.         $currentUrl $request->getRequestUri();
  638.         // Guarda la URL actual en la sesión
  639.         $session->set('previous_url'$currentUrl);
  640.         
  641.         $logs = [];$i 0;
  642.         foreach ($agenda->getLogAgendas() as $value) {
  643.             $i++;
  644.             $user $userRepository->find($value->getUserCrea());
  645.             $logs[$i] = [
  646.                 'usuario'     => $user->getUserName(),
  647.                 'observacion' => $value->getObservacion(),
  648.                 'fecha'       => $value->getCreatedAt(), 
  649.                 'descripcion' => $value->getDescripcion(),
  650.                 'seguro'      => $value->getSeguro()->getNombre(),
  651.                 'inicio'      => $value->getInicio(),
  652.             ];
  653.         }
  654.         //dd($logs[1]['usuario']);
  655.         $procedimientoPrincipal $agenda->getProcedimiento(); // el principal
  656.         $procedimientosSecundarios        $agenda->getAgendaProcedimientos();
  657.         // Construimos un array con los IDs
  658.         $procedimientosSeleccionados = [];
  659.         
  660.         if ($procedimientoPrincipal) {
  661.             $procedimientosSeleccionados[] = $procedimientoPrincipal;
  662.         }
  663.         
  664.         foreach ($procedimientosSecundarios as $ap) {
  665.             $procedimientosSeleccionados[] = $ap->getProcedimiento();
  666.         }
  667.         //dd($procedimientosSeleccionados);
  668.         /////
  669.         $nunidad $agenda->getSala()->getUnidad()->getNombre();
  670.         $form $this->createForm(AgendaTypeEdit::class, $agenda,[ 'unidad' => $nunidad'procedimientos_seleccionados' => $procedimientosSeleccionados ]);
  671.         $form->handleRequest($request);
  672.         
  673.         //////RECOMENDADO Y RED SOCIAL
  674.         $paciente $agenda->getPaciente();
  675.         $recomen  $agenda->getRecomendado();//dd($recomen);
  676.         if($recomen == null){
  677.             $recomen $paciente->getRecomendado();//dd($recomen);
  678.             $form->get('recomendado')->setData($recomen);    
  679.         }
  680.         $red  $agenda->getRedsocial();
  681.         if($red == null){
  682.             $red $paciente->getRedsocial();
  683.             $form->get('redsocial')->setData($red);    
  684.         }
  685.         
  686.         //////////////SALUD
  687.         /*$saludProducto  = $agenda->getSaludProducto();
  688.         if($saludProducto == null){
  689.             $saludProducto = $paciente->getSaludProducto();
  690.             $form->get('salud_producto')->setData($saludProducto);    
  691.         }
  692.         $saludNropersona  = $agenda->getSaludNropersona();
  693.         if($saludNropersona == null){
  694.             $saludNropersona = $paciente->getSaludNropersona();
  695.             $form->get('salud_nropersona')->setData($saludNropersona);    
  696.         }
  697.         $saludNivel  = $agenda->getSaludNivel();
  698.         if($saludNivel == null){
  699.             $saludNivel = $paciente->getSaludNivel();
  700.             $form->get('salud_nivel')->setData($saludNivel);    
  701.         }*/
  702.         //////////////////////////////
  703.         /*$form->get('contrato')->setData($agenda->getPaciente()->getContrato());
  704.         $form->get('region')->setData($agenda->getPaciente()->getRegion());*/
  705.         
  706.         $form->get('fecha_nacimiento')->setData($agenda->getPaciente()->getFechaNacimiento());
  707.         $form->get('sexo')->setData($agenda->getPaciente()->getSexo());
  708.         if($agenda->getPaciente()->getEstadoCivil() != null){
  709.             $form->get('estado_civil')->setData($agenda->getPaciente()->getEstadoCivil());    
  710.         }else{
  711.             $form->get('estado_civil')->setData('Soltero');    
  712.         }
  713.         
  714.         $form->get('hijos')->setData($agenda->getPaciente()->getHijos());
  715.         $form->get('telefono')->setData($agenda->getPaciente()->getTelefono());
  716.         $form->get('ciudad')->setData($agenda->getPaciente()->getCiudad());
  717.         $form->get('email')->setData($agenda->getPaciente()->getEmail());
  718.         $form->get('recomendacion')->setData($agenda->getPaciente()->getRecomendacion());
  719.         $form->get('alias')->setData($agenda->getPaciente()->getAlias());
  720.         $form->get('observacion_paciente')->setData($agenda->getPaciente()->getObservacion());
  721.         
  722.         //$form->get('paciente_endoscopias')->setData($agenda->getPaciente()->getPacienteEndoscopias());
  723.         //$form->get('paciente_bariatrico')->setData($agenda->getPaciente()->getPacienteBariatrico());
  724.         
  725.         $referencias $pacienteReferenciaRepository->findBy(['paciente' => $agenda->getPaciente()]);
  726.         /*if ($form->isSubmitted() && $form->isValid()) {
  727.             $this->getDoctrine()->getManager()->flush();
  728.             return $this->redirectToRoute('agenda_index');
  729.         }*/
  730.         return $this->render('agenda/edit.html.twig', [
  731.             'agenda' => $agenda,
  732.             'form'   => $form->createView(),
  733.             'logs'   => $logs,
  734.             'form_referencia' => $form_referencia->createView(),
  735.             'referencias' => $referencias,
  736.             'form_ap' => $form_ap->createView(),
  737.         ]);
  738.     }
  739.     
  740.     /**
  741.      * @Route("/reunion/{id}/edit", name="agenda_reunion_edit", methods={"GET"})
  742.      */
  743.     public function reunion_edit(Request $requestAgenda $agendaUserRepository $userRepositoryPacienteReferenciaRepository $pacienteReferenciaRepositorySessionInterface $session): Response
  744.     {
  745.         $pacienteReferencia = new PacienteReferencia();
  746.         $form_referencia $this->createForm(PacienteReferenciaType::class, $pacienteReferencia);
  747.         $form_referencia->handleRequest($request);
  748.         
  749.         // Obtén la URL actual
  750.         $currentUrl $request->getRequestUri();
  751.         // Guarda la URL actual en la sesión
  752.         $session->set('previous_url'$currentUrl);
  753.         
  754.         $logs = [];$i 0;
  755.         foreach ($agenda->getLogAgendas() as $value) {
  756.             $i++;
  757.             $user $userRepository->find($value->getUserCrea());
  758.             $logs[$i] = [
  759.                 'usuario'     => $user->getUserName(),
  760.                 'observacion' => $value->getObservacion(),
  761.                 'fecha'       => $value->getCreatedAt(), 
  762.                 'descripcion' => $value->getDescripcion(),
  763.                 'seguro'      => $value->getSeguro()->getNombre(),
  764.             ];
  765.         }
  766.         //dd($logs[1]['usuario']);
  767.         $nunidad $agenda->getSala()->getUnidad()->getNombre();
  768.         $form $this->createForm(AgendaTypeEditReunion::class, $agenda,[ 'unidad' => $nunidad ]);
  769.         $form->handleRequest($request);
  770.         
  771.         $referencias $pacienteReferenciaRepository->findBy(['paciente' => $agenda->getPaciente()]);
  772.         /*if ($form->isSubmitted() && $form->isValid()) {
  773.             $this->getDoctrine()->getManager()->flush();
  774.             return $this->redirectToRoute('agenda_index');
  775.         }*/
  776.         return $this->render('agenda/reunion_edit.html.twig', [
  777.             'agenda' => $agenda,
  778.             'form'   => $form->createView(),
  779.             'logs'   => $logs,
  780.             'form_referencia' => $form_referencia->createView(),
  781.             'referencias' => $referencias,
  782.         ]);
  783.     }
  784.     /**
  785.      * @Route("/{id}/edit/update", name="agenda_update", methods={"GET","POST"})
  786.      */
  787.     public function update(Request $requestAgenda $agendaPacienteRepository $pacienteRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroRepositoryEspecialidadRepository $unidadRepositoryUserRepository $userRepositoryOrdenVentaRepository $ordenVentaRepositoryOrdenVentaDetalleRepository $ordenVentaDetalleRepository): Response
  788.     {
  789.         
  790.         $confirma_anterior $agenda->getConfirma();
  791.         $nunidad $agenda->getSala()->getUnidad()->getNombre();
  792.         //return $this->json(['form' => $form]);
  793.         $ip   $request->getClientIp();
  794.         $user $this->security->getUser();
  795.         $form $this->createForm(AgendaTypeEdit::class, $agenda, ['unidad' => $nunidad'procedimientos_seleccionados' => [] ]);
  796.         $form->handleRequest($request);
  797.         $logagenda   = new LogAgenda();
  798.         if ($form->isSubmitted() && $form->isValid()) {
  799.             
  800.             ////
  801.             $entityManager $this->getDoctrine()->getManager();
  802.             $procedimientosSecundarios        $agenda->getAgendaProcedimientos();
  803.             foreach($procedimientosSecundarios as $xp){
  804.                 $entityManager->remove($xp);    
  805.             }
  806.             $entityManager->flush();
  807.             ////
  808.             $id_sala         $form->get('sala')->getData();
  809.             $sala            $salaRepository->find($id_sala);
  810.             $logagenda->setSala($sala);
  811.             $logagenda->setIpCrea($ip);
  812.             $logagenda->setIpModifica($ip);
  813.             $logagenda->setEstadoAgenda(0);
  814.             $logagenda->setUserCrea($user->getId());
  815.             $logagenda->setUserModifica($user->getId());
  816.             $inicio          $form->get('inicio')->getData();
  817.             $fin             $form->get('fin')->getData();
  818.             $observacion     $form->get('observacion')->getData();
  819.             $descripcion     'ACTUALIZACION';
  820.             
  821.             //dd($agenda->getConfirma(), $confirma_anterior);
  822.             if(! $agenda->getConfirma() ){
  823.                 
  824.                 if( $confirma_anterior ){
  825.                     $descripcion .= ' QUITA CONFIRMACION';
  826.                     //dd($descripcion);
  827.                 }    
  828.             }
  829.             if( $agenda->getConfirma() ){
  830.                 if( ! $confirma_anterior ){
  831.                     $descripcion .= ' CONFIRMA';
  832.                     //dd($descripcion);
  833.                 }    
  834.             }
  835.            
  836.             $id_seguro       $form->get('seguro')->getData();
  837.             $seguro          $seguroRepository->find($id_seguro);
  838.             $id_especialidad $form->get('especialidad')->getData();
  839.             $especialidad    $unidadRepository->find($id_especialidad);
  840.             $id_doctor       $form->get('doctor')->getData();
  841.             $doctor          $userRepository->find($id_doctor);
  842.             //$region          = $form->get('region')->getData();
  843.             $region null;
  844.             //$contrato        = $form->get('contrato')->getData();
  845.             $contrato null;
  846.             
  847.             /*$saludProducto   = $form->get('salud_producto')->getData();
  848.             $saludNropersona = $form->get('salud_nropersona')->getData();
  849.             $saludNivel      = $form->get('salud_nivel')->getData();*/
  850.             $saludProducto null;
  851.             $saludNropersona null;
  852.             $saludNivel null;
  853.             //dd($region);
  854.             $logagenda->setInicio($inicio);
  855.             $logagenda->setFin($fin);
  856.             $logagenda->setObservacion($observacion);
  857.             $logagenda->setAgenda($agenda);
  858.             $logagenda->setSeguro($seguro);
  859.             $logagenda->setEspecialidad($especialidad);
  860.             $logagenda->setDoctor($doctor);
  861.             $logagenda->setDescripcion($descripcion);
  862.             $paciente $agenda->getPaciente();
  863.             $paciente->setSeguro($seguro);
  864.             $paciente->setContrato($contrato);
  865.             $paciente->setRegion($region);
  866.             $paciente->setSaludProducto($saludProducto);
  867.             $paciente->setSaludNropersona($saludNropersona);
  868.             $paciente->setSaludNivel($saludNivel);
  869.             
  870.             $fechaNacimiento $form->get('fecha_nacimiento')->getData();
  871.             $sexo $form->get('sexo')->getData();
  872.             $estadoCivil $form->get('estado_civil')->getData();
  873.             $hijos $form->get('hijos')->getData();
  874.             $telefono $form->get('telefono')->getData();
  875.             $ciudad $form->get('ciudad')->getData();
  876.             $email $form->get('email')->getData();
  877.             $recomendacion $form->get('recomendacion')->getData();
  878.             $alias $form->get('alias')->getData();
  879.             $recomendado $form->get('recomendado')->getData();
  880.             $redsocial $form->get('redsocial')->getData();
  881.             $observacion_paciente $form->get('observacion_paciente')->getData();
  882.             $paciente_endoscopias null;
  883.             $paciente_bariatrico null;
  884.             /*$paciente_endoscopias = $form->get('paciente_endoscopias')->getData();
  885.             $paciente_bariatrico = $form->get('paciente_bariatrico')->getData();*/
  886.             
  887.             $paciente->setFechaNacimiento($fechaNacimiento);
  888.             $paciente->setSexo($sexo);
  889.             $paciente->setEstadoCivil($estadoCivil);
  890.             $paciente->setHijos($hijos);
  891.             $paciente->setTelefono($telefono);
  892.             $paciente->setCiudad($ciudad);
  893.             $paciente->setEmail($email);
  894.             $paciente->setRecomendacion($recomendacion);
  895.             $paciente->setAlias($alias);
  896.             $paciente->setRecomendado($recomendado);
  897.             $paciente->setRedsocial($redsocial);
  898.             $paciente->setObservacion($observacion_paciente);
  899.             $paciente->setPacienteEndoscopias($paciente_endoscopias);
  900.             $paciente->setPacienteBariatrico($paciente_bariatrico);
  901.             //////////////////
  902.             $xprocedimientos $form->get('procedimiento')->getData();
  903.             $xcont 0;
  904.             foreach($xprocedimientos as $xp){
  905.                 if($xcont == 0){
  906.                     $agenda->setProcedimiento($xp);    
  907.                 }
  908.                 $xcont ++;         
  909.             }
  910.             $xcont 0;
  911.             foreach($xprocedimientos as $xp){
  912.                 if($xcont 0){
  913.                     $agendaProcedimiento = new AgendaProcedimiento();
  914.                     $agendaProcedimiento->setAgenda($agenda);
  915.                     $agendaProcedimiento->setProcedimiento($xp);
  916.                     $agendaProcedimiento->setIpCrea($ip);
  917.                     $agendaProcedimiento->setIpModifica($ip);
  918.                     $agendaProcedimiento->setUserCrea($user->getId());
  919.                     $agendaProcedimiento->setUserModifica($user->getId());
  920.                     $entityManager->persist($agendaProcedimiento);
  921.                 }
  922.                 $xcont ++;         
  923.             }
  924.             ////////////
  925.             $entityManager->persist($logagenda);
  926.             $entityManager->persist($paciente);
  927.             $entityManager->flush();
  928.             
  929.             ///////////////////
  930.             $preparacion $agenda->getPreparacion();
  931.             if($preparacion==null){
  932.                 $preparacion = new Preparacion();
  933.                 $entityManager $this->getDoctrine()->getManager();
  934.                 $preparacion->setEstado('2');
  935.                 $preparacion->setIpCrea($ip);
  936.                 $preparacion->setIpModifica($ip);
  937.                 $preparacion->setEstatura(1);
  938.                 $preparacion->setPeso(1);
  939.                 $preparacion->setUserCrea($user->getId());
  940.                 $preparacion->setUserModifica($user->getId());
  941.                 $preparacion->setFrecuenciaRespiratoria('0');
  942.                 $preparacion->setSaturacionDeOxigeno('0');
  943.                 $preparacion->setAgenda($agenda);
  944.                 $entityManager->persist($preparacion);
  945.                 $entityManager->flush();
  946.             }
  947.             /////////////////////
  948.             $productos = [];
  949.             $xcant 0;
  950.             $orden  $ordenVentaRepository->findOneBy(['id_agenda' => $agenda->getId(), 'tipo' => 'AGENDA']);
  951.             //dd($orden);
  952.             if($orden != null){
  953.                 //////
  954.                 foreach($xprocedimientos as $xp){
  955.                     if($xp->getProducto() != null){
  956.                         $productos[$xcant] = $xp->getProducto();     
  957.                         $xcant++;
  958.                     }    
  959.                 }
  960.             
  961.             }//dd($productos);
  962.             $t 0;
  963.             foreach($productos as $producto){$t++;
  964.                 $existe_detalle $ordenVentaDetalleRepository->findOneBy(['producto' => $producto'orden_venta' => $orden]);
  965.                 //if($t>1){ dd($productos, $t, $producto, $existe_detalle); }
  966.                 if($existe_detalle == null){
  967.                     $detalle = new OrdenVentaDetalle();
  968.                     $detalle->setDescripcion($producto->getNombre());
  969.                     $detalle->setCantidad(1);
  970.                     $detalle->setPrecio($producto->getPrecio());
  971.                     $detalle->setIva(0);
  972.                     $detalle->setValorIva(0);
  973.                     $detalle->setEstado(1);
  974.                     $detalle->setIpCrea($ip);
  975.                     $detalle->setIpModifica($ip);
  976.                     $detalle->setUserCrea($user->getId());
  977.                     $detalle->setUserModifica($user->getId());
  978.                     $detalle->setProducto($producto);
  979.                     $detalle->setDescuento(0);
  980.                     $detalle->setOrdenVenta($orden);
  981.                     $valor_subtotal $producto->getPrecio();
  982.                     $detalle->setsubtotal($valor_subtotal);
  983.                     $detalle->setPctOda(0);
  984.                     $detalle->setOda(0);
  985.                     $entityManager->persist($detalle);
  986.                     $entityManager->flush();
  987.                 }
  988.                     
  989.             }
  990.             
  991.             ///////////////////////
  992.             return $this->json(['estado' => 'ok''agenda' => $agenda->getId()]);
  993.         }
  994.         else{
  995.             dd($this->getFormErrors($form));
  996.         }
  997.         return $this->json(['estado' => 'no''agenda' => $agenda->getId()]);
  998.     }
  999.     
  1000.     
  1001.      /**
  1002.      * @Route("/reunion/{id}/edit/update", name="agenda_reunion_update", methods={"GET","POST"})
  1003.      */
  1004.     public function agenda_reunion_update(Request $requestAgenda $agendaPacienteRepository $pacienteRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroRepositoryEspecialidadRepository $unidadRepositoryUserRepository $userRepository): Response
  1005.     {
  1006.         $nunidad $agenda->getSala()->getUnidad()->getNombre();
  1007.         //return $this->json(['form' => $form]);
  1008.         $ip   $request->getClientIp();
  1009.         $user $this->security->getUser();
  1010.         $form $this->createForm(AgendaTypeEditReunion::class, $agenda, ['unidad' => $nunidad ]);
  1011.         $form->handleRequest($request);
  1012.         $logagenda   = new LogAgenda();
  1013.         if ($form->isSubmitted() && $form->isValid()) {
  1014.            
  1015.             $id_sala         $form->get('sala')->getData();
  1016.             $sala            $salaRepository->find($id_sala);
  1017.             $logagenda->setSala($sala);
  1018.             $logagenda->setIpCrea($ip);
  1019.             $logagenda->setIpModifica($ip);
  1020.             $logagenda->setEstadoAgenda(0);
  1021.             $logagenda->setUserCrea($user->getId());
  1022.             $logagenda->setUserModifica($user->getId());
  1023.             $inicio          $form->get('inicio')->getData();
  1024.             $fin             $form->get('fin')->getData();
  1025.             $observacion     $form->get('observacion')->getData();
  1026.             $descripcion     'ACTUALIZACION';
  1027.             //$id_seguro       = $form->get('seguro')->getData();
  1028.             //$seguro          = $seguroRepository->find($id_seguro);
  1029.             
  1030.             $id_doctor       $form->get('doctor')->getData();
  1031.             $doctor          $userRepository->find($id_doctor);
  1032.             $logagenda->setInicio($inicio);
  1033.             $logagenda->setFin($fin);
  1034.             $logagenda->setObservacion($observacion);
  1035.             $logagenda->setAgenda($agenda);
  1036.             $logagenda->setSeguro($agenda->getSeguro());
  1037.             $logagenda->setEspecialidad($agenda->getEspecialidad());
  1038.             $logagenda->setDoctor($doctor);
  1039.             $logagenda->setDescripcion($descripcion);
  1040.             $entityManager $this->getDoctrine()->getManager();
  1041.             $entityManager->persist($logagenda);
  1042.             $entityManager->flush();
  1043.             return $this->json(['estado' => 'ok''agenda' => $agenda->getId()]);
  1044.         }
  1045.         else{
  1046.             dd($this->getFormErrors($form));
  1047.         }
  1048.         return $this->json(['estado' => 'no''agenda' => $agenda->getId()]);
  1049.     }
  1050.     /**
  1051.      * @Route("new_modal/{id}/edit", name="agenda_modal_edit", methods={"GET","POST"})
  1052.      */
  1053.     public function edit_modal(Request $requestAgenda $agenda): Response
  1054.     {
  1055.         $form $this->createForm(AgendaType::class, $agenda);
  1056.         $form->handleRequest($request);
  1057.         if ($form->isSubmitted() && $form->isValid()) {
  1058.             $this->getDoctrine()->getManager()->flush();
  1059.             return $this->redirectToRoute('agenda_index');
  1060.         }
  1061.         return $this->render('agenda/edit_modal.html.twig', [
  1062.             'agenda' => $agenda,
  1063.             'form' => $form->createView(),
  1064.         ]);
  1065.     }
  1066.     /**
  1067.      * @Route("/{id}", name="agenda_delete", methods={"DELETE"})
  1068.      */
  1069.     public function delete(Request $requestAgenda $agenda): Response
  1070.     {
  1071.         if ($this->isCsrfTokenValid('delete'.$agenda->getId(), $request->request->get('_token'))) {
  1072.             $entityManager $this->getDoctrine()->getManager();
  1073.             $entityManager->remove($agenda);
  1074.             $entityManager->flush();
  1075.         }
  1076.         return $this->redirectToRoute('agenda_index');
  1077.     }
  1078.     /**
  1079.      * @Route("/confirmar/edit/{id}", name="agenda_confirmar", methods={"GET","POST"})
  1080.      */
  1081.     public function confirmar(Request $requestAgenda $agenda): Response
  1082.     {
  1083.         
  1084.         $form $this->createForm(AgendaTypeConfirm::class, $agenda);
  1085.         //dd($form);
  1086.         $form->handleRequest($request);
  1087.         /*if ($form->isSubmitted() && $form->isValid()) {
  1088.             $entityManager = $this->getDoctrine()->getManager();
  1089.             $entityManager->persist($agenda);
  1090.             $entityManager->flush();
  1091.             return $this->redirectToRoute('agenda_index');
  1092.         }*/
  1093.         
  1094.         return $this->render('agenda/edit_confirm.html.twig', [
  1095.             'agenda'   => $agenda,
  1096.             'form'     => $form->createView(),
  1097.         ]);
  1098.     }
  1099.     /**
  1100.      * @Route("/confirmar/edit/{id}/update", name="agenda_confirmar_update", methods={"GET","POST"})
  1101.      */
  1102.     public function confirmar_update(Request $requestAgenda $agendaPacienteRepository $pacienteRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroRepositoryEspecialidadRepository $unidadRepositoryUserRepository $userRepository): Response
  1103.     {
  1104.         
  1105.         $ip   $request->getClientIp();
  1106.         $user $this->security->getUser();
  1107.         $form $this->createForm(AgendaTypeConfirm::class, $agenda);
  1108.         $form->handleRequest($request);
  1109.         $logagenda   = new LogAgenda();
  1110.         //dd($form->isValid());
  1111.         if ($form->isSubmitted() && $form->isValid()) {
  1112.             $sala         $agenda->getSala();
  1113.             
  1114.             $logagenda->setSala($sala);
  1115.             $logagenda->setIpCrea($ip);
  1116.             $logagenda->setIpModifica($ip);
  1117.             $agenda->setEstadoAgenda(2);
  1118.             $logagenda->setEstadoAgenda(2);
  1119.             $logagenda->setUserCrea($user->getId());
  1120.             $logagenda->setUserModifica($user->getId());
  1121.             $inicio          $agenda->getInicio();
  1122.             $fin             $agenda->getFin();
  1123.             $observacion     $form->get('observacion')->getData();
  1124.             $descripcion     'CONFIRMACION';
  1125.             $seguro          $agenda->getSeguro();
  1126.             $especialidad    $agenda->getEspecialidad();
  1127.             $doctor          $agenda->getDoctor();
  1128.             $logagenda->setInicio($inicio);
  1129.             $logagenda->setFin($fin);
  1130.             $logagenda->setObservacion($observacion);
  1131.             $logagenda->setAgenda($agenda);
  1132.             $logagenda->setSeguro($seguro);
  1133.             $logagenda->setEspecialidad($especialidad);
  1134.             $logagenda->setDoctor($doctor);
  1135.             $logagenda->setDescripcion($descripcion);
  1136.             $entityManager $this->getDoctrine()->getManager();
  1137.             $entityManager->persist($logagenda);
  1138.             $entityManager->flush();
  1139.             return $this->json(['estado' => 'ok''agenda' => $agenda->getId()]);
  1140.         }
  1141.         return $this->json(['estado' => 'no''agenda' => $agenda->getId()]);
  1142.     }
  1143.     /**
  1144.      * @Route("/admision/edit/{id}", name="agenda_admision", methods={"GET","POST"})
  1145.      */
  1146.     public function admision(Request $requestAgenda $agendaPreparacionRepository $preparacionRepository ): Response
  1147.     {
  1148.      
  1149.         $preparaciones $preparacionRepository->buscaPreparacionxPaciente($agenda->getPaciente()->getId())->getResult();
  1150.         
  1151.         
  1152.         $form $this->createForm(AgendaTypeAdmision::class, $agenda);
  1153.         //dd($form);
  1154.         $form->handleRequest($request);
  1155.         $estadocivil $agenda->getPaciente()->getEstadoCivil();
  1156.         $form->get('estado_civil')->setData($estadocivil);
  1157.         $ciudad $agenda->getPaciente()->getCiudad();
  1158.         $form->get('ciudad')->setData($ciudad);
  1159.         $lugar_nacimiento $agenda->getPaciente()->getLugarNacimiento();
  1160.         $form->get('lugar_nacimiento')->setData($lugar_nacimiento);
  1161.         /*$referido = $agenda->getPaciente()->getReferido();
  1162.         $form->get('referido')->setData($referido);*/
  1163.         $recomendacion $agenda->getPaciente()->getRecomendacion();
  1164.         $peso 0;$talla 0;$peso 0;
  1165.         if($agenda->getPreparacion() != null){
  1166.             $peso $agenda->getPreparacion()->getPeso();
  1167.             $talla $agenda->getPreparacion()->getEstatura();
  1168.         }
  1169.         $form->get('recomendacion')->setData($recomendacion);
  1170.         $form->get('peso')->setData($peso);
  1171.         $form->get('estatura')->setData($talla);
  1172.         
  1173.         if($peso == '1'){
  1174.             if(isset($preparaciones[1])){
  1175.                 $peso $preparaciones[1]['peso'];
  1176.                 $talla $preparaciones[1]['estatura'];
  1177.                 if($peso '1'){
  1178.                     $form->get('peso')->setData($peso);
  1179.                     $form->get('estatura')->setData($talla);
  1180.                 }
  1181.                 
  1182.             }
  1183.         }
  1184.         
  1185.             
  1186.         
  1187.         $cedula_familiar $agenda->getPaciente()->getCedulaFamiliar();
  1188.         $form->get('cedula_familiar')->setData($cedula_familiar);
  1189.         $parentesco $agenda->getPaciente()->getParentesco();
  1190.         $form->get('parentesco')->setData($parentesco);
  1191.         $nombres_familiar $agenda->getPaciente()->getNombresFamiliar();
  1192.         $form->get('nombres_familiar')->setData($nombres_familiar);
  1193.         $telefono_familiar $agenda->getPaciente()->getTelefonoFamiliar();
  1194.         $form->get('telefono_familiar')->setData($telefono_familiar);
  1195.         $pais $agenda->getPaciente()->getPais();
  1196.         if($pais==null){
  1197.             $pais 'ECUADOR';
  1198.         }
  1199.         $form->get('pais')->setData($pais);
  1200.         $parroquia_residencia $agenda->getPaciente()->getParroquiaResidencia();
  1201.         $form->get('parroquia_residencia')->setData($parroquia_residencia);
  1202.         $provincia_residencia $agenda->getPaciente()->getProvinciaresidencia();
  1203.         $form->get('provincia_residencia')->setData($provincia_residencia);
  1204.         $telefono $agenda->getPaciente()->getTelefono();
  1205.         $form->get('telefono')->setData($telefono);
  1206.         $direccion $agenda->getPaciente()->getDireccion();
  1207.         $form->get('direccion')->setData($direccion);
  1208.         $ocupacion $agenda->getPaciente()->getOcupacion();
  1209.         $form->get('ocupacion')->setData($ocupacion);
  1210.         /*if ($form->isSubmitted() && $form->isValid()) {
  1211.             $entityManager = $this->getDoctrine()->getManager();
  1212.             $entityManager->persist($agenda);
  1213.             $entityManager->flush();
  1214.             return $this->redirectToRoute('agenda_index');
  1215.         }*/
  1216.         
  1217.         return $this->render('agenda/edit_admision.html.twig', [
  1218.             'agenda'   => $agenda,
  1219.             'form'     => $form->createView(),
  1220.         ]);
  1221.     }
  1222.     /**
  1223.      * @Route("/admin/edit/{id}/update", name="agenda_admin_update", methods={"GET","POST"})
  1224.     */
  1225.     public function admin_update(Request $requestAgenda $agendaPacienteRepository $pacienteRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroRepositoryEspecialidadRepository $unidadRepositoryUserRepository $userRepository): Response
  1226.     {
  1227.         $ip   $request->getClientIp();
  1228.         $user $this->security->getUser();
  1229.         $form $this->createForm(AgendaTypeAdmision::class, $agenda);
  1230.         $form->handleRequest($request);
  1231.         $logagenda   = new LogAgenda();
  1232.         if ($form->isSubmitted() && $form->isValid()) {
  1233.             $sala         $agenda->getSala();
  1234.             /*$brochureFile = $form->get('cedula_paciente')->getData();
  1235.             if ($brochureFile) {
  1236.                 $originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
  1237.                 $cedula = $agenda->getPaciente()->getCedula();
  1238.                 // this is needed to safely include the file name as part of the URL
  1239.                 //$safeFilename = $slugger->slug($originalFilename);
  1240.                 $safeFilename ='cedula_'.$cedula.'_'.date("YmdHis");
  1241.                 //$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
  1242.                 $newFilename = $safeFilename.'.'.$brochureFile->guessExtension();
  1243.                 // Move the file to the directory where brochures are stored
  1244.                 try {
  1245.                     $brochureFile->move(
  1246.                         $this->getParameter('brochures_directory'),
  1247.                         $newFilename
  1248.                     );
  1249.                 } catch (FileException $e) {
  1250.                     // ... handle exception if something happens during file upload
  1251.                 }
  1252.                 // updates the 'brochureFilename' property to store the PDF file name
  1253.                 // instead of its contents
  1254.                 $agenda->getPaciente()->setCopiaCedula($newFilename);
  1255.                 //$product->setBrochureFilename($newFilename);
  1256.             }  */
  1257.             //$brochureFile = $form->get('archivo053')->getData();
  1258.             /*if ($brochureFile) {
  1259.                 $originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
  1260.                 $cedula = $agenda->getPaciente()->getCedula();
  1261.                 // this is needed to safely include the file name as part of the URL
  1262.                 //$safeFilename = $slugger->slug($originalFilename);
  1263.                 $safeFilename ='f053_'.$cedula;
  1264.                 //$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
  1265.                 $newFilename = $safeFilename.'.'.$brochureFile->guessExtension();
  1266.                 // Move the file to the directory where brochures are stored
  1267.                 try {
  1268.                     $brochureFile->move(
  1269.                         $this->getParameter('brochures_directory'),
  1270.                         $newFilename
  1271.                     );
  1272.                 } catch (FileException $e) {
  1273.                     // ... handle exception if something happens during file upload
  1274.                 }
  1275.                 // updates the 'brochureFilename' property to store the PDF file name
  1276.                 // instead of its contents
  1277.                 $agenda->setArchivo053($newFilename);
  1278.                 //$product->setBrochureFilename($newFilename);
  1279.             }   */
  1280.                 ///////////////////
  1281.             $preparacion $agenda->getPreparacion();
  1282.             if($preparacion==null){
  1283.                 $preparacion = new Preparacion();
  1284.                 $entityManager $this->getDoctrine()->getManager();
  1285.                 $preparacion->setEstado('2');
  1286.                 $preparacion->setIpCrea($ip);
  1287.                 $preparacion->setIpModifica($ip);
  1288.                 $preparacion->setEstatura(1);
  1289.                 $preparacion->setPeso(1);
  1290.                 $preparacion->setUserCrea($user->getId());
  1291.                 $preparacion->setUserModifica($user->getId());
  1292.                 $preparacion->setFrecuenciaRespiratoria('0');
  1293.                 $preparacion->setSaturacionDeOxigeno('0');
  1294.                 $preparacion->setAgenda($agenda);
  1295.                 $entityManager->persist($preparacion);
  1296.                 $entityManager->flush();
  1297.             }
  1298.             /////////////////////
  1299.             
  1300.             $logagenda->setSala($sala);
  1301.             $logagenda->setIpCrea($ip);
  1302.             $logagenda->setIpModifica($ip);
  1303.             $agenda->setEstadoAgenda(2);
  1304.             $logagenda->setEstadoAgenda(2);
  1305.             $logagenda->setUserCrea($user->getId());
  1306.             $logagenda->setUserModifica($user->getId());
  1307.             $inicio          $agenda->getInicio();
  1308.             $fin             $agenda->getFin();
  1309.             $observacion     $form->get('observacion')->getData();
  1310.             $descripcion     'ADMISION';
  1311.             $seguro          $agenda->getSeguro();
  1312.             $especialidad    $agenda->getEspecialidad();
  1313.             $doctor          $agenda->getDoctor();
  1314.             $estadocivil     $form->get('estado_civil')->getData();
  1315.             $ciudad          $form->get('ciudad')->getData();
  1316.             $pais                  $form->get('pais')->getData();
  1317.             $parroquia_residencia  $form->get('parroquia_residencia')->getData();
  1318.             $provincia_residencia  $form->get('provincia_residencia')->getData();
  1319.             $telefono  $form->get('telefono')->getData();
  1320.             $direccion  $form->get('direccion')->getData();
  1321.             $lugarnacimiento $form->get('lugar_nacimiento')->getData();
  1322.             $ocupacion $form->get('ocupacion')->getData();
  1323.             //$referido        = $form->get('referido')->getData();
  1324.             $recomendacion   $form->get('recomendacion')->getData();
  1325.             $peso            $form->get('peso')->getData();
  1326.             $talla            $form->get('estatura')->getData();
  1327.             $cedulafamiliar  $form->get('cedula_familiar')->getData();
  1328.             $parentesco      $form->get('parentesco')->getData();
  1329.             $nombresfamiliar $form->get('nombres_familiar')->getData();
  1330.             $telefonofamiliar$form->get('telefono_familiar')->getData();
  1331.             $logagenda->setInicio($inicio);
  1332.             $logagenda->setFin($fin);
  1333.             $logagenda->setObservacion($observacion);
  1334.             $logagenda->setAgenda($agenda);
  1335.             $logagenda->setSeguro($seguro);
  1336.             $logagenda->setEspecialidad($especialidad);
  1337.             $logagenda->setDoctor($doctor);
  1338.             $logagenda->setDescripcion($descripcion);
  1339.             $agenda->getPaciente()->setEstadoCivil($estadocivil);
  1340.             $agenda->getPaciente()->setCiudad(strtoupper($ciudad));
  1341.             $agenda->getPaciente()->setOcupacion(strtoupper($ocupacion));
  1342.             $agenda->getPaciente()->setLugarNacimiento(strtoupper($lugarnacimiento));
  1343.             //$agenda->getPaciente()->setReferido(strtoupper($referido));
  1344.             $agenda->getPaciente()->setCedulaFamiliar(strtoupper($cedulafamiliar));
  1345.             $agenda->getPaciente()->setParentesco(strtoupper($parentesco));
  1346.             $agenda->getPaciente()->setNombresFamiliar(strtoupper($nombresfamiliar));
  1347.             $agenda->getPaciente()->setTelefonoFamiliar(strtoupper($telefonofamiliar));
  1348.             $agenda->getPaciente()->setPais(strtoupper($pais));
  1349.             $agenda->getPaciente()->setParroquiaResidencia(strtoupper($parroquia_residencia));
  1350.             $agenda->getPaciente()->setProvinciaResidencia(strtoupper($provincia_residencia));
  1351.             $agenda->getPaciente()->setDireccion(strtoupper($direccion));
  1352.             $agenda->getPaciente()->setTelefono($telefono);
  1353.             $agenda->getPaciente()->setRecomendacion($recomendacion);
  1354.             if($agenda->getPreparacion() != null){
  1355.                 $agenda->getPreparacion()->setPeso($peso);
  1356.                 $agenda->getPreparacion()->setEstatura($talla);
  1357.             }
  1358.             $entityManager $this->getDoctrine()->getManager();
  1359.             $entityManager->persist($logagenda);
  1360.             //$entityManager->persist($agenda);
  1361.             //$entityManager->persist($agenda->getPaciente());
  1362.             $entityManager->flush();
  1363.             return $this->json(['estado' => 'ok''agenda' => $agenda->getId()]);
  1364.         }
  1365.         return $this->json(['estado' => 'no''agenda' => $agenda->getId()]);
  1366.     }
  1367.     /**
  1368.      * @Route("/pantalla/control", name="agenda_control", methods={"GET","POST"})
  1369.      */
  1370.     public function index_control(HistoriaClinicaRepository $historiaClinicaRepositoryAgendaRepository $agendaRepositoryPaginatorInterface $paginatorRequest $requestTurnoRepository $turnoRepository): Response
  1371.     {
  1372.         $turno $turnoRepository->find(1);
  1373.         date_default_timezone_set("America/Guayaquil");
  1374.         $agenda = new Agenda();
  1375.         $form $this->createForm(BuscaPreparacionType::class,$agenda);
  1376.         $form->handleRequest($request);
  1377.         $fecha $form->get('inicio')->getData();
  1378.         $session $request->getSession();
  1379.         $session->set('paciente',null);
  1380.         
  1381.         if($fecha==null){
  1382.             $fecha = new \DateTime("now");
  1383.             $form->get('inicio')->setData($fecha);  
  1384.         }    
  1385.         $query $agendaRepository->findByAdmisionadas(date_format($fecha,'Y-m-d'),date_format($fecha,'Y-m-d'));
  1386.         //dd($query->getResult());
  1387.         $agendas $paginator->paginate(
  1388.             $query,
  1389.             $request->query->getInt('page',1),
  1390.             30
  1391.         );
  1392.         return $this->render('historia_clinica/index_control.html.twig', [ 'agendas' => $agendas'form' => $form->createView(), 'turno' => $turno ]);
  1393.     }
  1394.     /**
  1395.      * @Route("/recepcion/agenda/listado/dia", name="agenda_listado", methods={"GET","POST"})
  1396.      */
  1397.     public function index_listado(AgendaRepository $agendaRepositoryPaginatorInterface $paginatorRequest $requestEmpresaRepository $empresaRepositoryOrdenVentaRepository $ordenVentaRepositoryFormaPagoRepository $formaPagoRepository): Response
  1398.     {
  1399.         $empresa $empresaRepository->find(1);
  1400.         date_default_timezone_set("America/Guayaquil");
  1401.         $agenda = new Agenda();
  1402.         $form $this->createForm(BuscaPreparacionType_pac_rpt::class,$agenda);
  1403.         $form->handleRequest($request);
  1404.         $seguro $form->get('seguro')->getData();
  1405.         $unidad $form->get('unidad')->getData();
  1406.         $fecha $form->get('inicio')->getData();
  1407.         $hasta $form->get('hasta')->getData();
  1408.         $paciente $form->get('paciente')->getData();
  1409.         $doctor $form->get('doctor')->getData();
  1410.         $session $request->getSession();
  1411.         $session->set('paciente',null);
  1412.         if($form->isSubmitted()){
  1413.             if($fecha!=null){
  1414.                 //$session = $request->getSession();
  1415.                 $session->set('fecha_busqueda'$fecha);
  1416.             }
  1417.             if($hasta!=null){
  1418.                 //$session = $request->getSession();
  1419.                 $session->set('fecha_hasta'$hasta);
  1420.             }
  1421.             if($fecha==null){
  1422.                 $fecha = new \DateTime("now");
  1423.                 $form->get('inicio')->setData($fecha);
  1424.                 $session->set('fecha_busqueda'$fecha);  
  1425.             }
  1426.             if($hasta==null){
  1427.                 $hasta = new \DateTime("now");
  1428.                 $form->get('hasta')->setData($hasta);
  1429.                 $session->set('fecha_hasta'$hasta);  
  1430.             } 
  1431.         }else{
  1432.             $fecha $session->get('fecha_busqueda'); 
  1433.             if($fecha==null){
  1434.                 $fecha = new \DateTime("now");  
  1435.             }  
  1436.             $form->get('inicio')->setData($fecha);    
  1437.             $hasta $session->get('fecha_hasta'); 
  1438.             if($hasta==null){
  1439.                 $hasta = new \DateTime("now");  
  1440.             }  
  1441.             $form->get('hasta')->setData($hasta);
  1442.         }     
  1443.         //$query = $agendaRepository->findByAdmisionadas_paciente(date_format($fecha,'Y-m-d'),date_format($fecha,'Y-m-d'),$paciente);
  1444.         $query $agendaRepository->findByAdmisionadas_rpt(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente,$unidad,$doctor);
  1445.         $query2 $agendaRepository->findByAnuladas(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente);
  1446.         $query_doc $agendaRepository->findByEstadistico_Doctor($unidaddate_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'))->getResult();//dd($query_doc);
  1447.         $query_doc2 $agendaRepository->findByEstadistico_Doctor_2($unidaddate_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'))->getResult();//dd($query_doc, $query_doc2);
  1448.         $qSalud $agendaRepository->findByAdmisionadas_Salud(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente,$unidad,$doctor);
  1449.         $arr_doc = [];$arr_fp = [];$arr_final = [];
  1450.         foreach($query_doc2 as $doc){
  1451.             $arr_doc[$doc['nombres']] = ['valor' => $doc['valor'] , 'color' => $doc['color']];                
  1452.         }
  1453.         foreach($query_doc as $doc){
  1454.             $arr_fp[$doc['forma_pago']] = '1';
  1455.             //$arr_doc[$doc['nombres']] = '1';    
  1456.             $arr_final[$doc['nombres']][$doc['forma_pago']] = $doc['valor'];
  1457.         }
  1458.         //dd($arr_doc, $arr_fp, $arr_final);
  1459.         //dd($query->getResult());
  1460.         if ($form->getClickedButton() === $form->get('Reporte')){
  1461.             return $this->reporte_xls$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1462.         }
  1463.         if ($form->getClickedButton() === $form->get('Reporte_Admin')){
  1464.             return $this->reporte_xls_admi$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1465.         }
  1466.         if ($form->getClickedButton() === $form->get('Anuladas')){
  1467.             return $this->reporte_xls2$query2$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1468.         }
  1469.         if ($form->getClickedButton() === $form->get('SALUDSA')){
  1470.             return $this->reporteSaludSA$qSalud$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1471.         }
  1472.         $agendas $paginator->paginate(
  1473.             $query,
  1474.             $request->query->getInt('page',1),
  1475.             100
  1476.         );
  1477.         return $this->render('historia_clinica/index_listado.html.twig', [ 'agendas' => $agendas'form' => $form->createView(), 'empresa' => $empresa'fecha' => $fecha'hasta' => $hasta'arr_doc' => $arr_doc'arr_fp' => $arr_fp'arr_final' => $arr_final'unidad' => $unidad ]);
  1478.     }
  1479.     
  1480.     /**
  1481.      * @Route("/recepcion/agenda/listado/dia/cop", name="agenda_listado_cop", methods={"GET","POST"})
  1482.      */
  1483.     public function index_listado_cop(AgendaRepository $agendaRepositoryPaginatorInterface $paginatorRequest $requestEmpresaRepository $empresaRepositoryOrdenVentaRepository $ordenVentaRepositoryFormaPagoRepository $formaPagoRepository): Response
  1484.     {
  1485.         $empresa $empresaRepository->find(1);
  1486.         date_default_timezone_set("America/Guayaquil");
  1487.         $agenda = new Agenda();
  1488.         $form $this->createForm(BuscaPreparacionType_pac_rpt::class,$agenda);
  1489.         $form->handleRequest($request);
  1490.         $seguro $form->get('seguro')->getData();
  1491.         $unidad $form->get('unidad')->getData();
  1492.         $fecha $form->get('inicio')->getData();
  1493.         $hasta $form->get('hasta')->getData();
  1494.         $paciente $form->get('paciente')->getData();
  1495.         $doctor $form->get('doctor')->getData();
  1496.         
  1497.         $session $request->getSession();
  1498.         $session->set('paciente',null);
  1499.         if($form->isSubmitted()){
  1500.             if($fecha!=null){
  1501.                 //$session = $request->getSession();
  1502.                 $session->set('fecha_busqueda'$fecha);
  1503.             }
  1504.             if($hasta!=null){
  1505.                 //$session = $request->getSession();
  1506.                 $session->set('fecha_hasta'$hasta);
  1507.             }
  1508.             
  1509.             if($fecha==null){
  1510.                 $fecha = new \DateTime("now");
  1511.                 $form->get('inicio')->setData($fecha);
  1512.                 $session->set('fecha_busqueda'$fecha);  
  1513.             }
  1514.             if($hasta==null){
  1515.                 $hasta = new \DateTime("now");
  1516.                 $form->get('hasta')->setData($hasta);
  1517.                 $session->set('fecha_hasta'$hasta);  
  1518.             } 
  1519.         }else{
  1520.             $fecha $session->get('fecha_busqueda'); 
  1521.             if($fecha==null){
  1522.                 $fecha = new \DateTime("now");  
  1523.             }  
  1524.             $form->get('inicio')->setData($fecha);    
  1525.             $hasta $session->get('fecha_hasta'); 
  1526.             if($hasta==null){
  1527.                 $hasta = new \DateTime("now");  
  1528.             }  
  1529.             $form->get('hasta')->setData($hasta);
  1530.         }     
  1531.   
  1532.         //$query = $agendaRepository->findByAdmisionadas_paciente(date_format($fecha,'Y-m-d'),date_format($fecha,'Y-m-d'),$paciente);
  1533.         $query $agendaRepository->findByAdmisionadas_rpt(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente,$unidad,$doctor);
  1534.         $query2 $agendaRepository->findByAnuladas(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente);
  1535.         $query_doc $agendaRepository->findByEstadistico_Doctor($unidaddate_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'))->getResult();//dd($query_doc);
  1536.         $query_doc2 $agendaRepository->findByEstadistico_Doctor_2($unidaddate_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'))->getResult();//dd($query_doc);
  1537.         
  1538.         $arr_doc = [];$arr_fp = [];$arr_final = [];
  1539.         foreach($query_doc2 as $doc){
  1540.             
  1541.             $arr_doc[$doc['nombres']] = ['valor' => $doc['valor'] , 'color' => $doc['color']];    
  1542.             
  1543.         }
  1544.         foreach($query_doc as $doc){
  1545.             $arr_fp[$doc['forma_pago']] = '1';
  1546.             //$arr_doc[$doc['nombres']] = '1';    
  1547.             $arr_final[$doc['nombres']][$doc['forma_pago']] = $doc['valor'];
  1548.         }
  1549.         //dd($arr_doc, $arr_fp, $arr_final);
  1550.         
  1551.         //dd($query->getResult());
  1552.         if ($form->getClickedButton() === $form->get('Reporte')){
  1553.             return $this->reporte_xls$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1554.         }
  1555.         
  1556.         if ($form->getClickedButton() === $form->get('Reporte_Admin')){
  1557.             return $this->reporte_xls_admi$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1558.         }
  1559.         
  1560.         if ($form->getClickedButton() === $form->get('Anuladas')){
  1561.             return $this->reporte_xls2$query2$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1562.         }
  1563.         
  1564.         
  1565.         $agendas $paginator->paginate(
  1566.             $query,
  1567.             $request->query->getInt('page',1),
  1568.             100
  1569.         );
  1570.         return $this->render('historia_clinica/index_listado_cop.html.twig', [ 'agendas' => $agendas'form' => $form->createView(), 'empresa' => $empresa'fecha' => $fecha'hasta' => $hasta'arr_doc' => $arr_doc'arr_fp' => $arr_fp'arr_final' => $arr_final'unidad' => $unidad ]);
  1571.     }
  1572.     /**
  1573.      * @Route("/recepcion/agenda/listado/dia/anuladas", name="agenda_listado_anuladas", methods={"GET","POST"})
  1574.      */
  1575.     public function index_listado_anuladas(AgendaRepository $agendaRepositoryPaginatorInterface $paginatorRequest $requestEmpresaRepository $empresaRepositoryOrdenVentaRepository $ordenVentaRepositoryFormaPagoRepository $formaPagoRepositoryLogAgendaRepository $logAgendaRepositoryUserRepository $userRepository): Response
  1576.     {
  1577.         $empresa $empresaRepository->find(1);
  1578.         date_default_timezone_set("America/Guayaquil");
  1579.         $agenda = new Agenda();
  1580.         $form $this->createForm(BuscaPreparacionType_pac_rpt_anuladas::class,$agenda);
  1581.         $form->handleRequest($request);
  1582.         $seguro $form->get('seguro')->getData();
  1583.         $fecha $form->get('inicio')->getData();
  1584.         $hasta $form->get('hasta')->getData();
  1585.         $paciente $form->get('paciente')->getData();
  1586.         
  1587.         $session $request->getSession();
  1588.         $session->set('paciente',null);
  1589.         if($form->isSubmitted()){
  1590.             if($fecha!=null){
  1591.                 //$session = $request->getSession();
  1592.                 $session->set('fecha_busqueda'$fecha);
  1593.             }
  1594.             if($hasta!=null){
  1595.                 //$session = $request->getSession();
  1596.                 $session->set('fecha_hasta'$hasta);
  1597.             }
  1598.             
  1599.             if($fecha==null){
  1600.                 $fecha = new \DateTime("now");
  1601.                 $form->get('inicio')->setData($fecha);
  1602.                 $session->set('fecha_busqueda'$fecha);  
  1603.             }
  1604.             if($hasta==null){
  1605.                 $hasta = new \DateTime("now");
  1606.                 $form->get('hasta')->setData($hasta);
  1607.                 $session->set('fecha_hasta'$hasta);  
  1608.             } 
  1609.         }else{
  1610.             $fecha $session->get('fecha_busqueda'); 
  1611.             if($fecha==null){
  1612.                 $fecha = new \DateTime("now");  
  1613.             }  
  1614.             $form->get('inicio')->setData($fecha);    
  1615.             $hasta $session->get('fecha_hasta'); 
  1616.             if($hasta==null){
  1617.                 $hasta = new \DateTime("now");  
  1618.             }  
  1619.             $form->get('hasta')->setData($hasta);
  1620.         }     
  1621.   
  1622.         $query $agendaRepository->findByAnuladas(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente);
  1623.         
  1624.         if ($form->getClickedButton() === $form->get('Anuladas')){
  1625.             return $this->reporte_xls2$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa );
  1626.         }
  1627.         
  1628.         
  1629.         $agendas $paginator->paginate(
  1630.             $query,
  1631.             $request->query->getInt('page',1),
  1632.             100
  1633.         );
  1634.         return $this->render('historia_clinica/index_listado_anuladas.html.twig', [ 'agendas' => $agendas'form' => $form->createView(), 'empresa' => $empresa'fecha' => $fecha'hasta' => $hasta'userRepository' => $userRepository ]);
  1635.     }
  1636.     public function reporte_xls$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa ){
  1637.         $agendas $query->getResult();
  1638.         $spreadsheet = new Spreadsheet();
  1639.         $sheet $spreadsheet->getActiveSheet();
  1640.         $formas_pago $formaPagoRepository->findAll();
  1641.         $sheet->setTitle("Atenciones del día");
  1642.         $titulo 'ATENCION DE CONSULTAS Y PROCEDIMIENTOS DESDE:'.date_format($fecha,'Y-m-d').' HASTA:'.date_format($hasta,'Y-m-d');
  1643.         $sheet->setCellValue('A1'$empresa->getNombreCorto())->mergeCells('A1:J1');
  1644.         $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  1645.         $sheet->setCellValue('A2'$titulo )->mergeCells('A2:J2');
  1646.         $sheet->getStyle('A1:J3')->getFont()->setBold(true);
  1647.         $sheet->setCellValue('A3''FECHA');
  1648.         //$sheet->setCellValue('B3', 'HORA');
  1649.         $sheet->setCellValue('B3''CEDULA');
  1650.         $sheet->setCellValue('C3''PACIENTE');
  1651.         $sheet->setCellValue('D3''TIPO DE SERVICIO');
  1652.         $sheet->setCellValue('E3''DOCTOR');
  1653.         $sheet->setCellValue('F3''ESPECIALIDAD');
  1654.         //$sheet->setCellValue('H3', 'ESTADO');
  1655.         $sheet->setCellValue('G3''SEGURO');
  1656.         $sheet->setCellValue('H3''OBSERVACION');
  1657.         $sheet->setCellValue('I3''SUBTOTAL');
  1658.         $sheet->setCellValue('J3''FEE');
  1659.         $sheet->setCellValue('K3''DESCUENTO');
  1660.         $sheet->setCellValue('L3''TOTAL FACTURA');
  1661.         $sheet->setCellValue('M3''DETALLE');
  1662.         $sheet->setCellValue('N3''BANCO');
  1663.         $sheet->setCellValue('O3''DETALLE PAGO');
  1664.         
  1665.         $arr = ['P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS'];$it 0;
  1666.         foreach($formas_pago as $fp){
  1667.             $sheet->setCellValue($arr[$it].'3'$fp->getNombre());
  1668.             $it ++;
  1669.         }
  1670.         $sheet->setCellValue($arr[$it].'3''ODA');$it ++;
  1671.         $sheet->getStyle('A3:'.$arr[$it+3].'3')->getFont()->setBold(true);
  1672.         //$sheet->setCellValue($arr[$it].'3', 'TELEFONOS');$it ++;
  1673.         //$sheet->setCellValue($arr[$it].'3', 'DIRECCION');$it ++;
  1674.         //$sheet->setCellValue($arr[$it].'3', 'MAIL');
  1675.         $sheet->setCellValue($arr[$it].'3''RETENCION');$it++;
  1676.         $i 4;$arr_pago = [];$total_oda 0;
  1677.         foreach($formas_pago as $fp){
  1678.             $arr_pago[$fp->getId()] = 0;            
  1679.         }    
  1680.         foreach ($agendas as $value) {
  1681.             $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $value['agenda']->getId()]);
  1682.             $pagos = [];
  1683.             if(!is_null($orden)){
  1684.                 $pagos $orden->getOrdenVentaDetallePagos();    
  1685.             }
  1686.             $subtotal 0$descuento 0$total 0;$odetalle "";$fi 0;
  1687.             if(!is_null($orden)){
  1688.                 $subtotal   $orden->getSubtotal();
  1689.                 $descuento  $orden->getDescuento();
  1690.                 $fi         $orden->getFi();
  1691.                 $total      $orden->getTotal();
  1692.                 $ov_detalles $orden->getOrdenVentaDetalles();
  1693.                 foreach($ov_detalles as $od){
  1694.                     $odetalle.= $od->getDescripcion().'--';
  1695.                 }
  1696.             }
  1697.             //dd($orden);
  1698.             $sheet->setCellValue('A'.$idate_format($value['inicio'], 'd/m/Y'));
  1699.             //$sheet->setCellValue('B'.$i, date_format($value['inicio'], 'H:i:s'));
  1700.             $sheet->setCellValue('B'.$i$value['agenda']->getPaciente()->getCedula());
  1701.             $sheet->getStyle('B'.$i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  1702.             $sheet->setCellValue('C'.$i$value['paciente']);
  1703.             $sheet->setCellValue('D'.$i$value['agenda']->getProcedimiento()->getNombre());
  1704.             $sheet->setCellValue('E'.$i$value['doctor']);
  1705.             if($value['agenda']->getPreparacion()==null){
  1706.                 if($value['agenda']->getEstadoAgenda() < 2){
  1707.                     $estado 'NO ADMISIONADA';    
  1708.                 }else{
  1709.                      $estado 'PENDIENTE PREPARACION';   
  1710.                 }               
  1711.             }else{
  1712.                 if($value['agenda']->getPreparacion()->getEstado()==1){
  1713.                     $estado 'PASE A PREPARACION';
  1714.                 }elseif($value['agenda']->getPreparacion()->getEstado()==2){
  1715.                     if($value['agenda']->getHistoriaClinica()==null){
  1716.                         $estado 'PREPARACION LISTA';   
  1717.                     }else{ 
  1718.                         if($value['agenda']->getHistoriaClinica()->getEstado()==1){
  1719.                             $estado 'PASAR A CONSULTA';
  1720.                         }else{ 
  1721.                             $estado 'ATENDIDO';
  1722.                         } 
  1723.                     }
  1724.                 }           
  1725.             }
  1726.             $sheet->setCellValue('F'.$i$value['agenda']->getEspecialidad());
  1727.             //$sheet->setCellValue('H'.$i, $estado);
  1728.             $sheet->setCellValue('G'.$i$value['agenda']->getSeguro());
  1729.             $sheet->setCellValue('H'.$i$value['agenda']->getObservacion());
  1730.             $sheet->setCellValue('I'.$i$subtotal);
  1731.             $sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1732.             $sheet->setCellValue('J'.$i$fi);
  1733.             $sheet->getStyle('J'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1734.             $sheet->setCellValue('K'.$i$descuento);
  1735.             $sheet->getStyle('K'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1736.             $sheet->setCellValue('L'.$i$total);
  1737.             $sheet->getStyle('L'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1738.             $sheet->setCellValue('M'.$i$odetalle);
  1739.             $txt_pagos '';$it 0;$bancos ' ';$detalle_pago ' ';
  1740.             foreach($formas_pago as $fp){
  1741.                 $sheet->setCellValue($arr[$it].$i0); 
  1742.                 $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1743.                 $total_pago 0;
  1744.                 if(!is_null($orden)){
  1745.                     $pagos $orden->pagos_por_forma($fp);
  1746.                     foreach($pagos as $pago){
  1747.                         if($pago->getBanco() != null){
  1748.                             $bancos $bancos.' '.$pago->getBanco()->getNombre();
  1749.                         }
  1750.                         if($pago->getNumTransaccion() != null){
  1751.                             $detalle_pago $detalle_pago.' '.$pago->getNumTransaccion();
  1752.                         }
  1753.                         $total_pago += $pago->getValor() + $pago->getValorFi();
  1754.                     }
  1755.                 }
  1756.                 $arr_pago[$fp->getId()] += $total_pago;
  1757.                 $sheet->setCellValue($arr[$it].$i$total_pago);
  1758.                 $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1759.                 $it++;
  1760.             }  
  1761.             $sheet->setCellValue('N'.$i$bancos);
  1762.             $sheet->setCellValue('O'.$i$detalle_pago);
  1763.             $oda 0;
  1764.             if(!is_null($orden)){
  1765.                 $total_oda += $orden->getOda();
  1766.                 $oda $orden->getOda();
  1767.                 $sheet->setCellValue($arr[$it].$i$orden->getOda() );
  1768.             }else{
  1769.                 $sheet->setCellValue($arr[$it].$i);
  1770.             }    
  1771.             $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');$it ++;
  1772.             //$sheet->setCellValue($arr[$it].$i, $value['agenda']->getPaciente()->getTelefono() );$it ++;
  1773.             //$sheet->setCellValue($arr[$it].$i, $value['agenda']->getPaciente()->getDireccion());$it ++;
  1774.             //$sheet->setCellValue($arr[$it].$i, $value['agenda']->getPaciente()->getEmail());
  1775.             if($oda 0){
  1776.                 $sheet->setCellValue($arr[$it].$i$subtotal 0.275);    
  1777.             }else{
  1778.                 $sheet->setCellValue($arr[$it].$i0);    
  1779.             }
  1780.             $i++;
  1781.         }
  1782.         $it 0;
  1783.         $sheet->setCellValue('M'.$i"TOTAL");
  1784.         foreach($formas_pago as $fp){
  1785.             $sheet->setCellValue($arr[$it].$i$arr_pago[$fp->getId()]);
  1786.             $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1787.             $it++;
  1788.         }
  1789.         $sheet->setCellValue($arr[$it].$i$total_oda);
  1790.         $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1791.         $sheet->getStyle('M'.$i.':'.$arr[$it].$i)->getFont()->setBold(true);
  1792.         
  1793.         $it 0;
  1794.         foreach($formas_pago as $fp){
  1795.             $it ++;
  1796.         }
  1797.         $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
  1798.         $sheet->getPageSetup()->setFitToWidth(1);
  1799.         $sheet->getPageSetup()->setFitToHeight(1);
  1800.         $highestColumn $sheet->getHighestColumn(); // Última columna con datos
  1801.         $highestRow $sheet->getHighestRow(); // Última fila con datos
  1802.         $printArea 'A1:' $highestColumn $highestRow;
  1803.         $sheet->getPageSetup()->setPrintArea($printArea);
  1804.         // Ajustar tamaño de columnas automáticamente
  1805.         foreach (range('A'$highestColumn) as $col) {
  1806.             $sheet->getColumnDimension($col)->setAutoSize(true);
  1807.         }
  1808.         // Configurar márgenes mínimos para maximizar el espacio
  1809.         $sheet->getPageMargins()->setTop(0.2);
  1810.         $sheet->getPageMargins()->setRight(0.2);
  1811.         $sheet->getPageMargins()->setLeft(0.2);
  1812.         $sheet->getPageMargins()->setBottom(0.2);
  1813.         // Create your Office 2007 Excel (XLSX Format)
  1814.         $writer = new Xlsx($spreadsheet);
  1815.         // Create a Temporary file in the system
  1816.         $fileName 'AGENDA_DEL_DIA_'.date('Y-m-d').'.xlsx';
  1817.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  1818.         // Create the excel file in the tmp directory of the system
  1819.         if (ob_get_length()) {
  1820.             ob_end_clean();
  1821.         }
  1822.         $writer->save($temp_file);
  1823.         // Return the excel file as an attachment
  1824.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  1825.     }
  1826.     
  1827.     public function reporte_xls_admi$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa ){
  1828.         $agendas $query->getResult();
  1829.             
  1830.         $spreadsheet = new Spreadsheet();
  1831.         $sheet $spreadsheet->getActiveSheet();
  1832.         $formas_pago $formaPagoRepository->findBy(['ip_crea'=>'RP'],['user_crea'=>'ASC']);
  1833.         $sheet->setTitle("Atenciones del día");
  1834.         $titulo 'ATENCION DE CONSULTAS Y PROCEDIMIENTOS DESDE:'.date_format($fecha,'Y-m-d').' HASTA:'.date_format($hasta,'Y-m-d');
  1835.         $sheet->setCellValue('A1'$empresa->getNombreCorto())->mergeCells('A1:J1');
  1836.         $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  1837.         $sheet->setCellValue('A2'$titulo )->mergeCells('A2:J2');
  1838.         $sheet->getStyle('A1:J3')->getFont()->setBold(true);
  1839.         $sheet->setCellValue('A3''FECHA');
  1840.         //$sheet->setCellValue('B3', 'HORA');
  1841.         $sheet->setCellValue('B3''PACIENTE');
  1842.         $sheet->setCellValue('C3''TIPO DE SERVICIO');
  1843.         $sheet->setCellValue('D3''DOCTOR');
  1844.         $sheet->setCellValue('E3''SEGURO');
  1845.         $sheet->setCellValue('F3''DETALLE');
  1846.         $sheet->setCellValue('G3''OBSERVACION');
  1847.         $sheet->setCellValue('H3''SUBTOTAL');
  1848.         $sheet->setCellValue('I3''TOTAL FACTURA');
  1849.         $sheet->setCellValue('J3''BANCO');
  1850.         //$sheet->setCellValue('K3', 'DETALLE TRANSACCION');
  1851.         
  1852.         $arr = ['K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN'];$it 0;
  1853.         foreach($formas_pago as $fp){
  1854.             $sheet->setCellValue($arr[$it].'3'$fp->getNombre());
  1855.             $it ++;
  1856.         }
  1857.         $sheet->setCellValue($arr[$it].'3''ODA');$it ++;
  1858.         $sheet->getStyle('A3:'.$arr[$it+3].'3')->getFont()->setBold(true);
  1859.         
  1860.         $i 4;$arr_pago = [];$total_oda 0;
  1861.         foreach($formas_pago as $fp){
  1862.         
  1863.             $arr_pago[$fp->getId()] = 0;
  1864.             
  1865.         }   
  1866.         //$it++;
  1867.         $sheet->setCellValue($arr[$it].'3''DERIVADO');$it ++;
  1868.         $sheet->setCellValue($arr[$it].'3''RED/SEG');$it ++;
  1869.         $sheet->setCellValue($arr[$it].'3''RECOMENDACION');$it ++;
  1870.         
  1871.         $stotal 0$ttotal 0;
  1872.         foreach ($agendas as $value) {
  1873.             $pxs $value['agenda']->getAgendaProcedimientos();
  1874.             $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $value['agenda']->getId()]);
  1875.             $pagos = [];
  1876.             if(!is_null($orden)){
  1877.                 $pagos $orden->getOrdenVentaDetallePagos();    
  1878.             }
  1879.             
  1880.             
  1881.             $subtotal 0$descuento 0$total 0;$odetalle "";$fi 0;
  1882.             if(!is_null($orden)){
  1883.                 $subtotal   $orden->getSubtotal();
  1884.                 $descuento  $orden->getDescuento();
  1885.                 $fi         $orden->getFi();
  1886.                 $total      $orden->getTotal();
  1887.                 $ov_detalles $orden->getOrdenVentaDetalles();
  1888.                 foreach($ov_detalles as $od){
  1889.                     $odetalle.= $od->getDescripcion().'--';
  1890.                 }
  1891.             }
  1892.           
  1893.             $sheet->setCellValue('A'.$idate_format($value['inicio'], 'd/m'));
  1894.             //$sheet->setCellValue('B'.$i, date_format($value['inicio'], 'H:i:s'));
  1895.             //$sheet->getStyle('B'.$i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  1896.             $sheet->setCellValue('B'.$i$value['paciente']);
  1897.             $txt_proc $value['agenda']->getProcedimiento()->getNombre()."-> ";
  1898.             foreach($pxs as $px){
  1899.                 $txt_proc .= $px->getProcedimiento()->getNombre()."-> ";
  1900.             }
  1901.             $sheet->setCellValue('C'.$i$txt_proc);
  1902.             $sheet->setCellValue('D'.$i$value['doctor']);
  1903.             $txt_color $value['agenda']->getDoctor()->getColor();
  1904.             $txt_color substr($txt_color,1);
  1905.             $sheet->getStyle('D'.$i)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF'.$txt_color); // Color hexadecimal (azul)
  1906.             if($value['agenda']->getPreparacion()==null){
  1907.                 if($value['agenda']->getEstadoAgenda() < 2){
  1908.                     $estado 'NO ADMISIONADA';    
  1909.                 }else{
  1910.                      $estado 'PENDIENTE PREPARACION';   
  1911.                 }
  1912.                
  1913.             }else{
  1914.                 if($value['agenda']->getPreparacion()->getEstado()==1){
  1915.                     $estado 'PASE A PREPARACION';
  1916.                 }elseif($value['agenda']->getPreparacion()->getEstado()==2){
  1917.                     if($value['agenda']->getHistoriaClinica()==null){
  1918.                         $estado 'PREPARACION LISTA';   
  1919.                     }else{ 
  1920.                         if($value['agenda']->getHistoriaClinica()->getEstado()==1){
  1921.                             $estado 'PASAR A CONSULTA';
  1922.                         }else{ 
  1923.                             $estado 'ATENDIDO';
  1924.                         } 
  1925.                     }
  1926.                 }           
  1927.             }
  1928.             $sheet->setCellValue('E'.$i$value['agenda']->getSeguro());
  1929.             $sheet->setCellValue('F'.$i$odetalle);
  1930.             $sheet->setCellValue('G'.$i$value['agenda']->getObservacion());
  1931.             $sheet->setCellValue('H'.$i$subtotal);$stotal += $subtotal;
  1932.             $sheet->setCellValue('I'.$i$total);$ttotal += $total;
  1933.             $sheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1934.             $sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1935.             
  1936.             
  1937.             
  1938.             $txt_pagos '';$it 0;$bancos ' ';$detalle_txt ' ';
  1939.             foreach($formas_pago as $fp){
  1940.                 $sheet->setCellValue($arr[$it].$i0); 
  1941.                 $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1942.                 $total_pago 0;
  1943.                 if(!is_null($orden)){
  1944.                     $pagos $orden->pagos_por_forma($fp);
  1945.                     foreach($pagos as $pago){
  1946.                         if($pago->getBanco() != null){
  1947.                             $bancos $bancos.' '.$pago->getBanco()->getNombre();
  1948.                         }
  1949.                         if($pago->getNumTransaccion() != null){
  1950.                             $detalle_txt $detalle_txt.' '.$pago->getNumTransaccion();
  1951.                         }
  1952.                         $total_pago += $pago->getValor() + $pago->getValorFi();
  1953.                         
  1954.                     }
  1955.                 }
  1956.                 $arr_pago[$fp->getId()] += $total_pago;
  1957.                 $sheet->setCellValue($arr[$it].$i$total_pago);
  1958.                 $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  1959.                 $it++;
  1960.             } 
  1961.             $sheet->setCellValue('J'.$i$bancos);
  1962.             //$sheet->setCellValue('K'.$i, $detalle_txt);
  1963.             $oda 0;
  1964.             if(!is_null($orden)){
  1965.                 $total_oda += $orden->getOda();
  1966.                 $oda $orden->getOda();
  1967.                 $sheet->setCellValue($arr[$it].$i$orden->getOda() );
  1968.             }else{
  1969.                 $sheet->setCellValue($arr[$it].$i);
  1970.             }    
  1971.             $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');$it ++;
  1972.             //$sheet->setCellValue($arr[$it].$i, $value['agenda']->getPaciente()->getTelefono() );$it ++;
  1973.             //$sheet->setCellValue($arr[$it].$i, $value['agenda']->getPaciente()->getDireccion());$it ++;
  1974.             //$sheet->setCellValue($arr[$it].$i, $value['agenda']->getPaciente()->getEmail());
  1975.             if($oda 0){
  1976.                 //$sheet->setCellValue($arr[$it].$i, $subtotal * 0.275);    
  1977.             }else{
  1978.                 //$sheet->setCellValue($arr[$it].$i, 0);    
  1979.             }
  1980.             
  1981.             if($value['agenda']->getCobrado() == '1'){
  1982.                 //$sheet->setCellValue($arr[$it].$i, 'COBRAD' );    
  1983.             }//$it++;
  1984.             $deri "";
  1985.             if( $value['agenda']->getRecomendado() != null){
  1986.                 $deri $value['agenda']->getRecomendado()->getDr()." ".$value['agenda']->getRecomendado()->getNombre1()." ".$value['agenda']->getRecomendado()->getNombre2()." ".$value['agenda']->getRecomendado()->getApellido1()." ".$value['agenda']->getRecomendado()->getApellido2();
  1987.             }
  1988.             $sheet->setCellValue($arr[$it].$i$deri );
  1989.             $it++;$red ' ';
  1990.             if($value['agenda']->getRedsocial() != null){
  1991.                 $red =  $value['agenda']->getRedsocial()->getNombre(); 
  1992.             }
  1993.             $sheet->setCellValue($arr[$it].$i$red );
  1994.             $it++;
  1995.             $sheet->setCellValue($arr[$it].$i$value['agenda']->getPaciente()->getRecomendacion() );
  1996.             $it++;
  1997.             $i++;
  1998.             
  1999.         }
  2000.         
  2001.         $it 0;
  2002.         $sheet->setCellValue('G'.$i"TOTAL");
  2003.         $sheet->setCellValue('H'.$i$stotal); 
  2004.         $sheet->setCellValue('I'.$i$ttotal);
  2005.         $sheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2006.         $sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2007.         $sheet->getStyle('J'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2008.         $acum_fp 0;
  2009.         foreach($formas_pago as $fp){
  2010.             $acum_fp += $arr_pago[$fp->getId()];
  2011.             $sheet->setCellValue($arr[$it].$i$arr_pago[$fp->getId()]);
  2012.             $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2013.             $it++;
  2014.         }
  2015.         $sheet->setCellValue($arr[$it].$i$total_oda);
  2016.         $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2017.         $sheet->getStyle('H'.$i.':'.$arr[$it].$i)->getFont()->setBold(true);
  2018.         $sheet->getStyle('I'.$i.':'.$arr[$it].$i)->getFont()->setBold(true);
  2019.         $sheet->getStyle('A1:'.$arr[$it 3].$i)->getFont()->setSize(7);
  2020.         $it++;
  2021.         $acum_fp += $total_oda;
  2022.         //$sheet->setCellValue($arr[$it].$i, $acum_fp);
  2023.         $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2024.          $sheet->getStyle('I'.$i.':'.$arr[$it].$i)->getFont()->setBold(true);
  2025.          
  2026.         $sheet->getStyle('A'.$i.':'.$arr[$it 3].$i)->getFont()->setSize(9); 
  2027.         
  2028.         
  2029.         /*$sheet->getColumnDimension('A')->setWidth(7);
  2030.         $sheet->getColumnDimension('B')->setWidth(7);
  2031.         $sheet->getColumnDimension('C')->setWidth(20);
  2032.         $sheet->getColumnDimension('D')->setWidth(20);
  2033.         $sheet->getColumnDimension('E')->setWidth(7);
  2034.         $sheet->getColumnDimension('F')->setWidth(7);
  2035.         $sheet->getColumnDimension('G')->setWidth(25);
  2036.         $sheet->getColumnDimension('H')->setWidth(8);
  2037.         $sheet->getColumnDimension('I')->setWidth(8);
  2038.         $sheet->getColumnDimension('J')->setWidth(7);
  2039.         $sheet->getColumnDimension('K')->setWidth(7);
  2040.         $sheet->getColumnDimension('L')->setWidth(7);
  2041.         $sheet->getColumnDimension('M')->setWidth(7);
  2042.         $sheet->getColumnDimension('N')->setWidth(7);
  2043.         $sheet->getColumnDimension('O')->setWidth(7);*/
  2044.         $it 0;
  2045.         foreach($formas_pago as $fp){
  2046.              //$sheet->getColumnDimension($arr[$it])->setWidth(7);
  2047.             $it ++;
  2048.         }
  2049.         //$sheet->getColumnDimension($arr[$it])->setWidth(7);$it ++;
  2050.         //$sheet->getColumnDimension($arr[$it])->setWidth(7);$it ++;
  2051.         //$sheet->getColumnDimension($arr[$it])->setWidth(40);
  2052.         
  2053.         $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
  2054.         
  2055.         $sheet->getPageSetup()->setFitToWidth(1);
  2056.         $sheet->getPageSetup()->setFitToHeight(1);
  2057.         
  2058.         // Definir un área de impresión automática basada en los datos
  2059.         $highestColumn $sheet->getHighestColumn(); // Última columna con datos
  2060.         $highestRow $sheet->getHighestRow(); // Última fila con datos
  2061.         $printArea 'A1:' $highestColumn $highestRow;
  2062.         $sheet->getPageSetup()->setPrintArea($printArea);
  2063.         
  2064.         // Ajustar tamaño de columnas automáticamente
  2065.         foreach (range('A'$highestColumn) as $col) {
  2066.             $sheet->getColumnDimension($col)->setAutoSize(true);
  2067.         }
  2068.         
  2069.         // Configurar márgenes mínimos para maximizar el espacio
  2070.         $sheet->getPageMargins()->setTop(0.2);
  2071.         $sheet->getPageMargins()->setRight(0.2);
  2072.         $sheet->getPageMargins()->setLeft(0.2);
  2073.         $sheet->getPageMargins()->setBottom(0.2);
  2074.         // Create your Office 2007 Excel (XLSX Format)
  2075.         $writer = new Xlsx($spreadsheet);
  2076.         
  2077.         // Create a Temporary file in the system
  2078.         $fileName 'AGENDA_DEL_DIA_'.date('Y-m-d').'.xlsx';
  2079.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  2080.         
  2081.         // Create the excel file in the tmp directory of the system
  2082.         $writer->save($temp_file);
  2083.         
  2084.         // Return the excel file as an attachment
  2085.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  2086.     }
  2087.     
  2088.     public function reporte_xls2$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa ){
  2089.         $agendas $query->getResult();
  2090.             
  2091.         $spreadsheet = new Spreadsheet();
  2092.         $sheet $spreadsheet->getActiveSheet();
  2093.         $formas_pago $formaPagoRepository->findAll();
  2094.         $sheet->setTitle("Atenciones del día");
  2095.         $titulo 'ATENCION DE CONSULTAS Y PROCEDIMIENTOS ANULADOS DESDE:'.date_format($fecha,'Y-m-d').' HASTA:'.date_format($hasta,'Y-m-d');
  2096.         $sheet->setCellValue('A1'$empresa->getNombreCorto())->mergeCells('A1:J1');
  2097.         $sheet->setCellValue('A2'$titulo )->mergeCells('A1:J1');
  2098.         $sheet->setCellValue('A2'$titulo )->mergeCells('A2:J2');
  2099.         $sheet->getStyle('A1:K3')->getFont()->setBold(true);
  2100.         $sheet->getStyle('A1:J2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  2101.         $sheet->setCellValue('A3''FECHA');
  2102.         $sheet->setCellValue('B3''HORA');
  2103.         $sheet->setCellValue('C3''CEDULA');
  2104.         $sheet->setCellValue('D3''PACIENTE');
  2105.         $sheet->setCellValue('E3''TIPO DE SERVICIO');
  2106.         $sheet->setCellValue('F3''DOCTOR');
  2107.         $sheet->setCellValue('G3''ESTADO');
  2108.         $sheet->setCellValue('H3''OBSERVACION');
  2109.         $sheet->setCellValue('I3''TELEFONOS');
  2110.         $sheet->setCellValue('J3''DIRECCION');
  2111.         $sheet->setCellValue('K3''MAIL');    
  2112.         /*$sheet->setCellValue('H2', 'TOTAL');
  2113.         $sheet->setCellValue('I2', 'DESCUENTO');
  2114.         $sheet->setCellValue('J2', 'FACTURADO');
  2115.         
  2116.         $arr = ['K','L','M','N','O','P','Q'];$it = 0;
  2117.         foreach($formas_pago as $fp){
  2118.             $sheet->setCellValue($arr[$it].'2', $fp->getNombre());
  2119.             $it ++;
  2120.         }
  2121.         $sheet->getStyle('A2:'.$arr[$it].'2')->getFont()->setBold(true);*/
  2122.             
  2123.         
  2124.         
  2125.         $i 4;
  2126.         foreach ($agendas as $value) {
  2127.             $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $value['agenda']->getId()]);
  2128.             $pagos = [];
  2129.             if(!is_null($orden)){
  2130.                 $pagos $orden->getOrdenVentaDetallePagos();    
  2131.             }
  2132.             
  2133.             
  2134.             $subtotal 0$descuento 0$total 0;
  2135.             if(!is_null($orden)){
  2136.                 $subtotal $orden->getSubtotal();
  2137.                 $descuento $orden->getDescuento();
  2138.                 $total $orden->getTotal();
  2139.             }
  2140.             //dd($orden);
  2141.             $sheet->setCellValue('A'.$idate_format($value['inicio'], 'd/m/Y'));
  2142.             $sheet->setCellValue('B'.$idate_format($value['inicio'], 'H:i:s'));
  2143.             $sheet->setCellValue('C'.$i$value['agenda']->getPaciente()->getCedula());
  2144.             $sheet->getStyle('C'.$i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  2145.             $sheet->setCellValue('D'.$i$value['paciente']);
  2146.             $sheet->setCellValue('E'.$i$value['agenda']->getProcedimiento()->getNombre());
  2147.             $sheet->setCellValue('F'.$i$value['doctor']);
  2148.             if($value['agenda']->getPreparacion()==null){
  2149.                 $estado 'PENDIENTE PREPARACION';
  2150.             }else{
  2151.                 if($value['agenda']->getPreparacion()->getEstado()==1){
  2152.                     $estado 'PASE A PREPARACION';
  2153.                 }elseif($value['agenda']->getPreparacion()->getEstado()==2){
  2154.                     if($value['agenda']->getHistoriaClinica()==null){
  2155.                         $estado 'PREPARACION LISTA';   
  2156.                     }else{ 
  2157.                         if($value['agenda']->getHistoriaClinica()->getEstado()==1){
  2158.                             $estado 'PASAR A CONSULTA';
  2159.                         }else{ 
  2160.                             $estado 'ATENDIDO';
  2161.                         } 
  2162.                     }
  2163.                 }           
  2164.             }    
  2165.             $sheet->setCellValue('G'.$i$estado);
  2166.             $sheet->setCellValue('H'.$i$value['agenda']->getObservacion());
  2167.             $sheet->setCellValue('I'.$i$value['agenda']->getPaciente()->getTelefono() );
  2168.             $sheet->setCellValue('J'.$i$value['agenda']->getPaciente()->getDireccion());
  2169.             $sheet->setCellValue('K'.$i$value['agenda']->getPaciente()->getEmail());
  2170.             /*$sheet->setCellValue('H'.$i, $subtotal);
  2171.             $sheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2172.             $sheet->setCellValue('I'.$i, $descuento);
  2173.             $sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2174.             $sheet->setCellValue('J'.$i, $total);
  2175.             $sheet->getStyle('J'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2176.             $txt_pagos = '';$it = 0;
  2177.             foreach($formas_pago as $fp){
  2178.                 foreach($pagos as $pago){
  2179.                     if($fp->getId() == $pago->getFormapago()->getId()){
  2180.                         
  2181.                         $sheet->setCellValue($arr[$it].$i, $pago->getValor());
  2182.                         $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2183.                     }else{
  2184.                         $sheet->setCellValue($arr[$it].$i, 0); 
  2185.                         $sheet->getStyle($arr[$it].$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  2186.                     }
  2187.                     //$txt_pagos = $txt_pagos.'-'.$pago->getFormaPago()->getNombre();
  2188.                 }$it++;
  2189.             } */   
  2190.             
  2191.             $i++;
  2192.         }
  2193.         
  2194.         $sheet->getColumnDimension('A')->setWidth(15);
  2195.         $sheet->getColumnDimension('B')->setWidth(15);
  2196.         $sheet->getColumnDimension('C')->setWidth(20);
  2197.         $sheet->getColumnDimension('D')->setWidth(40);
  2198.         $sheet->getColumnDimension('E')->setWidth(30);
  2199.         $sheet->getColumnDimension('F')->setWidth(25);
  2200.         $sheet->getColumnDimension('G')->setWidth(30);
  2201.         $sheet->getColumnDimension('H')->setWidth(40);
  2202.         $sheet->getColumnDimension('I')->setWidth(15);
  2203.         $sheet->getColumnDimension('J')->setWidth(40);
  2204.         $sheet->getColumnDimension('K')->setWidth(40);
  2205.         $it 0;
  2206.         /*foreach($formas_pago as $fp){
  2207.              $sheet->getColumnDimension($arr[$it])->setWidth(20);
  2208.             $it ++;
  2209.         }*/
  2210.         // Create your Office 2007 Excel (XLSX Format)
  2211.         $writer = new Xlsx($spreadsheet);
  2212.         
  2213.         // Create a Temporary file in the system
  2214.         $fileName 'AGENDA_DEL_DIA.xlsx';
  2215.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  2216.         
  2217.         // Create the excel file in the tmp directory of the system
  2218.         $writer->save($temp_file);
  2219.         
  2220.         // Return the excel file as an attachment
  2221.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  2222.     }
  2223.     
  2224.     
  2225.     
  2226.     public function reporteSaludSA$query$ordenVentaRepository$fecha$hasta$formaPagoRepository$empresa ){
  2227.         $agendas $query->getResult();//dd($agendas);
  2228.             
  2229.         $spreadsheet = new Spreadsheet();
  2230.         $sheet $spreadsheet->getActiveSheet();
  2231.         $formas_pago $formaPagoRepository->findAll();
  2232.         $sheet->setTitle("Atenciones del día");
  2233.         
  2234.         $listado = [
  2235.             "REGION",
  2236.             "PRODUCTO",
  2237.             "CONTRATO",
  2238.             "CEDULA CLIENTE",
  2239.             "NUM PERSONA",
  2240.             "FECHA RECEPCIÓN/FECHA INCURRENCIA",
  2241.             "DX1 CODIGO CIE10",
  2242.             "DX2 CODIGO CIE10",
  2243.             "DX3 CODIGO CIE10",
  2244.             "SERVICIO",
  2245.             "CÓDIGO HOMOLOGACION/CÓDIGO PROCEDIMIENTO",
  2246.             "PRESTACION/NOMBRE BENEFICIO",
  2247.             "CANTIDAD",
  2248.             "TOTAL - VALOR CONVENIO",
  2249.             "VALOR FEE",
  2250.             "VALOR COPAGO (VALOR QUE PAGA EL CLIENTE)",
  2251.             "VALOR NO CUBIERTO",
  2252.             "VALOR COBRAR A SALUD",
  2253.             "NOMBRE PACIENTE",
  2254.             "FECHA ORDEN",
  2255.             "FECHA IMPRESIÓN",
  2256.             "NIVEL",
  2257.             "PRECIO FIRMADO EN CONVENIO",
  2258.             "DIFERENCIA",
  2259.             "AUDITORIA"
  2260.         ];
  2261.         $letras range('A''Z');
  2262.         
  2263.         $sheet->getStyle('A1:E1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF52be80');
  2264.         $sheet->getStyle('F1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFebdef0');
  2265.         $sheet->getStyle('G1:I1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF00FF');
  2266.         $sheet->getStyle('J1:N1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFebdef0');
  2267.         $sheet->getStyle('O1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF00FF');
  2268.         $sheet->getStyle('P1:R1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFebdef0');
  2269.         $sheet->getStyle('S1:V1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF52be80');
  2270.         $sheet->getStyle('W1:Y1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF0000');
  2271.         
  2272.         
  2273.         $sheet->getRowDimension(1)->setRowHeight(50);
  2274.         $cant 0;
  2275.         foreach($listado as $list){
  2276.             $sheet->setCellValue($letras[$cant].'1'$list );
  2277.             $sheet->getStyle($letras[$cant].'1')->getAlignment()->setVertical(Alignment::VERTICAL_TOP)->setWrapText(true); 
  2278.             $cant ++;            
  2279.         }
  2280.         //dd($agendas);
  2281.         $i 2;$total 0;
  2282.         foreach ($agendas as $value) {
  2283.             //dd($value);
  2284.             $agenda   $value['agenda'];
  2285.             $paciente $agenda->getPaciente();
  2286.             $historia $agenda->getHistoriaClinica();
  2287.             //dd($agenda);
  2288.             if($historia != null){
  2289.                 //dd($historia);
  2290.                 $dxs      $historia->getDiagnosticosHistoriaClinicas();
  2291.                 $txt_code "CIE10 ";
  2292.                 if(isset($dxs[0])){
  2293.                 $txt_code $txt_code.' '.$dxs[0]->getCie10()->getCodigo();
  2294.             }
  2295.                 $txt_servicio "";
  2296.                 if (str_contains($agenda->getProcedimiento()->getNombre(), "CONSULTA")) {
  2297.                 $txt_servicio "CONSULTA MEDICA";
  2298.             }
  2299.                 if (str_contains($agenda->getProcedimiento()->getNombre(), "ECOGR")) {
  2300.                 $txt_servicio "IMAGENOLOGIA";
  2301.             }
  2302.             
  2303.                 $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $agenda->getId()]);
  2304.                 if($orden != null){
  2305.                     //dd($orden);
  2306.                     $detalles $orden->getOrdenVentaDetalles();
  2307.                     
  2308.                     foreach($detalles as $detalle){
  2309.                         $total_salud $detalle->getSubtotal() - $detalle->getOda();
  2310.                         $total += $total_salud;
  2311.                         $body = [
  2312.                             $paciente->getRegion(),
  2313.                             $agenda->getSaludProducto(),
  2314.                             $paciente->getContrato(),
  2315.                             $paciente->getCedula(),
  2316.                             $agenda->getSaludNropersona(),
  2317.                             date_format($agenda->getInicio(), 'd/m/Y'),
  2318.                             $txt_code,
  2319.                             "",
  2320.                             "",
  2321.                             $txt_servicio,
  2322.                             "",
  2323.                             $detalle->getDescripcion(),
  2324.                             $detalle->getCantidad(),
  2325.                             $detalle->getPrecio(),
  2326.                             "",
  2327.                             $total_salud,
  2328.                             "",
  2329.                             $detalle->getOda(),
  2330.                             $paciente->getApellido1().' '.$paciente->getApellido2().' '.$paciente->getNombre1().' '.$paciente->getNombre2(),
  2331.                             date_format($agenda->getInicio(), 'd/m/Y'),
  2332.                             date_format($agenda->getInicio(), 'd/m/Y'),
  2333.                             $agenda->getSaludNivel(),
  2334.                             "",
  2335.                             "",
  2336.                             ""
  2337.                         ];        
  2338.                         
  2339.                         $cant 0;
  2340.                         foreach($body as $bod){
  2341.                             $sheet->setCellValue($letras[$cant].$i$bod );
  2342.                                                 
  2343.                             $cant ++;            
  2344.                         }   
  2345.                         $sheet->getStyle('D'.$i)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  2346.                         $i++;
  2347.                         
  2348.                     }
  2349.                 
  2350.                 }
  2351.             }
  2352.             
  2353.         }    
  2354.             
  2355.         $sheet->setCellValue("W".$i'VALOR PRESENTADO' );
  2356.         $sheet->setCellValue("X".$i$total );
  2357.         $i++;
  2358.         $sheet->setCellValue("W".$i'VALOR OBSERVADO POR AUDITORIA ' );
  2359.         $sheet->setCellValue("X".$i'' );
  2360.         $i++;
  2361.         $sheet->setCellValue("W".$i'VALOR A FACTURAR  ' );
  2362.         $sheet->setCellValue("X".$i$total );
  2363.         
  2364.         $sheet->getStyle('A1:Y'.$i)->getBorders()->applyFromArray([
  2365.             'allBorders' => [
  2366.                 'borderStyle' => Border::BORDER_THIN// Tipo de borde
  2367.                 'color' => ['argb' => 'FF000000'],    // Color negro
  2368.             ],
  2369.         ]);
  2370.         $sheet->getColumnDimension('A')->setWidth(15);
  2371.         $sheet->getColumnDimension('B')->setWidth(15);
  2372.         $sheet->getColumnDimension('C')->setWidth(15);
  2373.         $sheet->getColumnDimension('D')->setWidth(15);
  2374.         $sheet->getColumnDimension('E')->setWidth(15);
  2375.         $sheet->getColumnDimension('F')->setWidth(25);
  2376.         $sheet->getColumnDimension('G')->setWidth(30);
  2377.         $sheet->getColumnDimension('H')->setWidth(30);
  2378.         $sheet->getColumnDimension('I')->setWidth(30);
  2379.         $sheet->getColumnDimension('J')->setWidth(30);
  2380.         $sheet->getColumnDimension('K')->setWidth(30);
  2381.         $sheet->getColumnDimension('L')->setWidth(30);
  2382.         $sheet->getColumnDimension('M')->setWidth(30);
  2383.         $sheet->getColumnDimension('N')->setWidth(30);
  2384.         $sheet->getColumnDimension('O')->setWidth(30);
  2385.         $sheet->getColumnDimension('P')->setWidth(30);
  2386.         $sheet->getColumnDimension('Q')->setWidth(30);
  2387.         $sheet->getColumnDimension('R')->setWidth(30);
  2388.         $sheet->getColumnDimension('S')->setWidth(50);
  2389.         $sheet->getColumnDimension('T')->setWidth(30);
  2390.         $sheet->getColumnDimension('U')->setWidth(30);
  2391.         $sheet->getColumnDimension('V')->setWidth(30);
  2392.         $sheet->getColumnDimension('W')->setWidth(30);
  2393.         $sheet->getColumnDimension('X')->setWidth(30);
  2394.         $sheet->getColumnDimension('Y')->setWidth(30);
  2395.         $sheet->getColumnDimension('Z')->setWidth(30);
  2396.         $it 0;
  2397.         
  2398.         // Create your Office 2007 Excel (XLSX Format)
  2399.         $writer = new Xlsx($spreadsheet);
  2400.         
  2401.         // Create a Temporary file in the system
  2402.         $fileName 'SALUD.xlsx';
  2403.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  2404.         
  2405.         // Create the excel file in the tmp directory of the system
  2406.         $writer->save($temp_file);
  2407.         
  2408.         // Return the excel file as an attachment
  2409.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  2410.     }
  2411.     /**
  2412.      * @Route("/suspender/{id}", name="agenda_suspender", methods={"GET","POST"})
  2413.      */
  2414.     public function suspender(Request $requestAgenda $agenda): Response
  2415.     {
  2416.         //dd($request->request);
  2417.         $motivo $request->request->get('motivo');
  2418.         $ip   $request->getClientIp();
  2419.         $user $this->security->getUser();
  2420.         $nunidad $agenda->getSala()->getUnidad()->getNombre();
  2421.         if( $agenda->getEstado() == ){
  2422.             //$form = $this->createForm(AgendaTypeEdit::class, $agenda,[ 'unidad' => $nunidad ]);
  2423.         }else{
  2424.             //$form = $this->createForm(AgendaTypeEditReunion::class, $agenda,[ 'unidad' => $nunidad ]);
  2425.         }
  2426.         //dd($form);
  2427.         //$form->handleRequest($request);
  2428.         $logagenda   = new LogAgenda();
  2429.         //if ($form->isSubmitted() && $form->isValid()) {
  2430.             $entityManager $this->getDoctrine()->getManager();
  2431.             $sala         $agenda->getSala();
  2432.             $logagenda->setSala($sala);
  2433.             $logagenda->setIpCrea($ip);
  2434.             $logagenda->setIpModifica($ip);
  2435.             $agenda->setEstado(0);
  2436.             $agenda->setEstadoAgenda(3);
  2437.             $agenda->setIpModifica($ip);
  2438.             $agenda->setUserModifica($user->getId());
  2439.             $logagenda->setEstadoAgenda(3);
  2440.             $logagenda->setUserCrea($user->getId());
  2441.             $logagenda->setUserModifica($user->getId());
  2442.             $inicio          $agenda->getInicio();
  2443.             $fin             $agenda->getFin();
  2444.             $seguro          $agenda->getSeguro();
  2445.             $especialidad    $agenda->getEspecialidad();
  2446.             $doctor          $agenda->getDoctor();
  2447.             $observacion     $motivo;
  2448.             $descripcion     'SUSPENDER';
  2449.             $logagenda->setInicio($inicio);
  2450.             $logagenda->setFin($fin);
  2451.             $logagenda->setObservacion($observacion);
  2452.             $logagenda->setAgenda($agenda);
  2453.             $logagenda->setSeguro($seguro);
  2454.             $logagenda->setEspecialidad($especialidad);
  2455.             $logagenda->setDoctor($doctor);
  2456.             $logagenda->setDescripcion($descripcion);
  2457.             //$entityManager = $this->getDoctrine()->getManager();
  2458.             $entityManager->persist($logagenda);
  2459.             //$entityManager->persist($agenda);
  2460.             $entityManager->flush();
  2461.             //return $this->redirectToRoute('agenda_index');
  2462.             return $this->json(['estado' => 'ok']);
  2463.         //}
  2464.         
  2465.         //return $this->json(['estado' => 'error']);
  2466.     }
  2467.     /**
  2468.      * @Route("/laboratorio/orden/new/{id_paciente}", name="agenda_laboratorio_orden_new", methods={"GET"})
  2469.      */
  2470.     public function laboratorio_orden_new(Request $request$id_pacientePacienteRepository $pacienteRepositoryUserRepository $userRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroPrivadoRepositoryEspecialidadRepository $especialidadRepositoryProcedimientosRepository $procedimientosRepository): Response
  2471.     {
  2472.         $ip     $request->getClientIp();
  2473.         $user   $this->security->getUser();
  2474.         
  2475.         $agenda = new Agenda;
  2476.         $session     $request->getSession();
  2477.     
  2478.         $id_paciente $session->get('id_paciente');
  2479.         $paciente $pacienteRepository->find($id_paciente);
  2480.         $doctor $userRepository->findOneBy(['cedula' => 'EXTERNO']);
  2481.         $sala $salaRepository->findOneBy(['nombre' => 'LABORATORIO']);
  2482.         $seguro $seguroPrivadoRepository->find(1);
  2483.         $especialidad $especialidadRepository->findOneBy(['nombre' => 'LABORATORIO']);
  2484.         $procedimiento $procedimientosRepository->findOneBy(['nombre' => 'LABORATORIO']);
  2485.         $entityManager $this->getDoctrine()->getManager();
  2486.         $fecha = new \DateTime("now");
  2487.         $agenda->setInicio($fecha);
  2488.         $agenda->setFin($fecha);
  2489.         $agenda->setPaciente($paciente);
  2490.         $agenda->setDoctor($doctor);
  2491.         $agenda->setSala($sala);
  2492.         $agenda->setEstado(1);
  2493.         $agenda->setIpCrea($ip);
  2494.         $agenda->setIpModifica($ip);
  2495.         $agenda->setUserCrea($user->getId());
  2496.         $agenda->setUserModifica($user->getId()); 
  2497.         $agenda->setSeguro($seguro);
  2498.         $agenda->setEspecialidad($especialidad);
  2499.         $agenda->setEstadoAgenda(2);
  2500.         $agenda->setProcedimiento($procedimiento);
  2501.         $entityManager->persist($agenda);
  2502.         $entityManager->flush(); 
  2503.         $historia = new HistoriaClinica;
  2504.         $historia->setAgenda($agenda);
  2505.         $historia->setIpCrea($ip);
  2506.         $historia->setIpModifica($ip);
  2507.         $historia->setUserCrea($user->getId());
  2508.         $historia->setUserModifica($user->getId()); 
  2509.         $historia->setPaciente($paciente);
  2510.         $historia->setEstado(1);
  2511.         $entityManager->persist($historia);
  2512.         $entityManager->flush(); 
  2513.         $orden = new ExamenOrden();
  2514.         $orden->setDoctor($historia->getAgenda()->getDoctor());
  2515.         $orden->setEstado(1);
  2516.         $orden->setPaciente($historia->getPaciente());
  2517.         $orden->setHistoria($historia);
  2518.         $orden->setSeguro($historia->getAgenda()->getSeguro());
  2519.         $orden->setFechaOrden($fecha);
  2520.         $orden->setIpCrea($ip);
  2521.         $orden->setIpModifica($ip);
  2522.         $orden->setUserCrea($user->getId());
  2523.         $orden->setUserModifica($user->getId()); 
  2524.         $orden->setCantidad(0);
  2525.         $orden->setDescuento(0);
  2526.         $orden->setDescuentoValor(0);
  2527.         $orden->setRecargo(0);
  2528.         $orden->setAgendado(0);
  2529.         $orden->setRecargoValor(0);
  2530.         $orden->setValor(0); 
  2531.         $orden->setTotalValor(0);
  2532.         $entityManager->persist($orden);
  2533.         $entityManager->flush(); 
  2534.         return $this->json(['id_orden' => $orden->getId()]);
  2535.         return $this->redirectToRoute('laboratorio_examen_orden_edit',[
  2536.             'id_orden'         => $orden->getId(),
  2537.         ]); 
  2538.         
  2539.     }
  2540.     /**
  2541.      * @Route("/laboratorio/edit/{id_orden}", name="laboratorio_examen_orden_edit", methods={"GET"})
  2542.      */
  2543.     public function laboratorio_edit(Request $request$id_ordenExamenOrdenRepository $examenOrdenRepositoryOrdenVentaRepository $ordenVentaRepositoryLabProtocoloRepository $labProtocoloRepository): Response
  2544.     {
  2545.         $examenOrden $examenOrdenRepository->find($id_orden);
  2546.         $detalle = new ExamenDetalle();
  2547.         $form $this->createForm(ExamenDetalleType::class, $detalle);
  2548.         $form2 $this->createForm(ExamenOrdenTypeRecepcion::class, $examenOrden, ['doctor' => $examenOrden->getDoctor()]);
  2549.         $form->handleRequest($request);
  2550.         $form2->handleRequest($request);
  2551.         $form->get('orden')->setData($examenOrden->getId());
  2552.         $fecha_orden  $examenOrden->getFechaOrden();
  2553.         $id_paciente  $examenOrden->getPaciente()->getId();
  2554.         $historia     $examenOrden->getHistoria();
  2555.         //$dxs          = $historia->getDiagnosticosHistoriaClinicas();
  2556.         $protocolos   $labProtocoloRepository->findBy(['estado' => 2]);
  2557.         //dd($protocolos);
  2558.         
  2559.         return $this->render('agenda/laboratorio_edit.html.twig', [
  2560.             'examenOrden'    => $examenOrden,
  2561.             'form'     => $form->createView(),
  2562.             'form2'     => $form2->createView(),
  2563.             'detalles'   => $examenOrden->getExamenDetalles(),
  2564.             'ordenVentaRepository' => $ordenVentaRepository,
  2565.             'protocolos' => $protocolos,
  2566.             //'dxs'        => $dxs,
  2567.         ]);
  2568.     }
  2569.     
  2570.     /**
  2571.      * @Route("/cotizacion/laboratorio/new/", name="cotizacion_laboratorio_new", methods={"GET"})
  2572.      */
  2573.     public function cotizacion_orden_new(Request $requestPacienteRepository $pacienteRepositoryUserRepository $userRepositorySalaRepository $salaRepositorySeguroPrivadoRepository $seguroPrivadoRepositoryEspecialidadRepository $especialidadRepositoryProcedimientosRepository $procedimientosRepositoryTipoUsuarioRepository $tipoUsuarioRepository,): Response
  2574.     {
  2575.         $ip     $request->getClientIp();
  2576.         $user   $this->security->getUser();
  2577.         
  2578.         $agenda = new Agenda;
  2579.         $session     $request->getSession();
  2580.         //$id_paciente = '0922290691';
  2581.         $id_paciente '0922290697';
  2582.         $paciente $pacienteRepository->findOneBy(['cedula' => $id_paciente]);
  2583.         $entityManager $this->getDoctrine()->getManager();
  2584.         $doctor $userRepository->findOneBy(['cedula' => 'EXTERNO']);
  2585.             if(is_null($doctor)){
  2586.                 $doctor = new User();
  2587.                 $doctor->setUsername('EXTERNO');
  2588.                 $doctor->setApellido1('EXTERNO');
  2589.                 $doctor->setApellido2('EXTERNO');  // nullable, pero tú tienes valor
  2590.                 $doctor->setNombre1('DOCTOR');
  2591.                 $doctor->setNombre2('DOCTOR');     // nullable
  2592.                 // roles es JSON en DB, en Symfony normalmente es array
  2593.                 $doctor->setRoles(['ROLE_USER']);
  2594.                 // ✅ Opción A: usar el hash que ya tienes (tal cual lo pegaste)
  2595.                 $doctor->setPassword('$argon2id$v=19$m=65536,t=4,p=1$LzVWdmoyUkczam5mSi9KZw$0uoSD1a1qKhvTMkeYTHifTLVbJvRWadk5Ne3pSG401A');
  2596.                 $tipoUsuario $tipoUsuarioRepository->find(3);
  2597.                 $doctor->setTipousuario($tipoUsuario);
  2598.                 $doctor->setCedula('EXTERNO');
  2599.                 $doctor->setEstado(1);
  2600.                 $entityManager->persist($doctor);
  2601.                 $entityManager->flush();
  2602.             }
  2603.         $sala $salaRepository->findOneBy(['nombre' => 'LABORATORIO']);
  2604.         $seguro $seguroPrivadoRepository->find(1);
  2605.         $especialidad $especialidadRepository->findOneBy(['nombre' => 'LABORATORIO']);
  2606.         
  2607.         if(is_null($especialidad)){
  2608.             $especialidad = new Especialidad();
  2609.             $especialidad->setNombre('LABORATORIO');
  2610.             $especialidad->setEstado(1); // o 1 según tu entidad
  2611.             $especialidad->setIpCrea($ip);
  2612.             $especialidad->setIpModifica($ip);
  2613.             $especialidad->setUserCrea($user->getId());
  2614.             $especialidad->setUserModifica($user->getId());
  2615.             $now = new \DateTimeImmutable();
  2616.             $especialidad->setCreatedAt($now);
  2617.             $especialidad->setUpdatedAt($now);
  2618.             $entityManager->persist($especialidad);
  2619.             $entityManager->flush();
  2620.         }
  2621.         $procedimiento $procedimientosRepository->findOneBy(['nombre' => 'LABORATORIO']);
  2622.         if(is_null($procedimiento))
  2623.         {
  2624.             $procedimiento = new Procedimientos(); 
  2625.             $procedimiento->setNombre('LABORATORIO');
  2626.             $procedimiento->setObservacion('Procedimiento creado automáticamente');
  2627.             $procedimiento->setEstado(1);
  2628.             $procedimiento->setIpCrea($ip);
  2629.             $procedimiento->setIpModifica($ip);
  2630.             $procedimiento->setUserCrea($user->getId());
  2631.             $procedimiento->setUserModifica($user->getId());
  2632.             $now = new \DateTimeImmutable();
  2633.             $procedimiento->setCreatedAt($now);
  2634.             $procedimiento->setUpdatedAt($now);
  2635.             $entityManager->persist($procedimiento);
  2636.             $entityManager->flush();
  2637.         }
  2638.         $fecha = new \DateTime("now");
  2639.         $agenda->setInicio($fecha);
  2640.         $agenda->setFin($fecha);
  2641.         $agenda->setPaciente($paciente);
  2642.         $agenda->setDoctor($doctor);
  2643.         $agenda->setSala($sala);
  2644.         $agenda->setEstado(0);
  2645.         $agenda->setIpCrea($ip);
  2646.         $agenda->setIpModifica($ip);
  2647.         $agenda->setUserCrea($user->getId());
  2648.         $agenda->setUserModifica($user->getId()); 
  2649.         $agenda->setSeguro($seguro);
  2650.         $agenda->setEspecialidad($especialidad);
  2651.         $agenda->setEstadoAgenda(0);
  2652.         $agenda->setProcedimiento($procedimiento);
  2653.         $entityManager->persist($agenda);
  2654.         $entityManager->flush(); 
  2655.         $historia = new HistoriaClinica;
  2656.         $historia->setAgenda($agenda);
  2657.         $historia->setIpCrea($ip);
  2658.         $historia->setIpModifica($ip);
  2659.         $historia->setUserCrea($user->getId());
  2660.         $historia->setUserModifica($user->getId()); 
  2661.         $historia->setPaciente($paciente);
  2662.         $historia->setEstado(0);
  2663.         $entityManager->persist($historia);
  2664.         $entityManager->flush(); 
  2665.         $orden = new ExamenOrden();
  2666.         $orden->setDoctor($historia->getAgenda()->getDoctor());
  2667.         $orden->setEstado(0);
  2668.         $orden->setPaciente($historia->getPaciente());
  2669.         $orden->setHistoria($historia);
  2670.         $orden->setSeguro($historia->getAgenda()->getSeguro());
  2671.         $orden->setFechaOrden($fecha);
  2672.         $orden->setIpCrea($ip);
  2673.         $orden->setIpModifica($ip);
  2674.         $orden->setUserCrea($user->getId());
  2675.         $orden->setUserModifica($user->getId()); 
  2676.         $orden->setCantidad(0);
  2677.         $orden->setDescuento(0);
  2678.         $orden->setDescuentoValor(0);
  2679.         $orden->setRecargo(0);
  2680.         $orden->setAgendado(0);
  2681.         $orden->setRecargoValor(0);
  2682.         $orden->setValor(0); 
  2683.         $orden->setTotalValor(0);
  2684.         $entityManager->persist($orden);
  2685.         $entityManager->flush(); 
  2686.         //return $this->json(['id_orden' => $orden->getId()]);
  2687.         return $this->redirectToRoute('laboratorio_cotizar',[
  2688.             'id_orden'         => $orden->getId(),
  2689.         ]); 
  2690.         
  2691.     }
  2692.     /**
  2693.      * @Route("/laboratorio/cotizar/orden/{id_orden}", name="laboratorio_cotizar", methods={"GET"})
  2694.      */
  2695.     public function laboratorio_cotizar(Request $request$id_ordenExamenOrdenRepository $examenOrdenRepository): Response
  2696.     {
  2697.         $examenOrden $examenOrdenRepository->find($id_orden);
  2698.         $detalle = new ExamenDetalle();
  2699.         $form $this->createForm(ExamenDetalleCotizacionType::class, $detalle);
  2700.         //$form2 = $this->createForm(ExamenOrdenTypeRecepcion::class, $examenOrden, ['doctor' => $examenOrden->getDoctor()]);
  2701.         $form2 $this->createForm(CotizacionType::class, $examenOrden);
  2702.         $form->handleRequest($request);
  2703.         $form2->handleRequest($request);
  2704.         $form->get('orden')->setData($examenOrden->getId());
  2705.         $fecha_orden  $examenOrden->getFechaOrden();
  2706.         $id_paciente  $examenOrden->getPaciente()->getId();
  2707.         $historia     $examenOrden->getHistoria();
  2708.         //$dxs          = $historia->getDiagnosticosHistoriaClinicas();
  2709.         return $this->render('agenda/laboratorio_cotizacion.html.twig', [
  2710.             'examenOrden'    => $examenOrden,
  2711.             'form'     => $form->createView(),
  2712.             'form2'     => $form2->createView(),
  2713.             'detalles'   => $examenOrden->getExamenDetalles(),
  2714.             //'dxs'        => $dxs,
  2715.         ]);
  2716.     }
  2717.     
  2718.      /**
  2719.      * @Route("/control/documentos/{id}", name="agenda_control_documentos", methods={"GET"})
  2720.      */
  2721.     public function agenda_control_documentos(Request $requestAgenda $agendaMaestroDocumentosRepository $maestroDocumentosRepositoryAgendaArchivosRepository $agendaArchivosRepository): Response
  2722.     {
  2723.         
  2724.         $documentos $maestroDocumentosRepository->findBy(['estado' => 1'departamento' => 'RECEPCION']);
  2725.         return $this->render('agenda/control_documentos.html.twig', [
  2726.             'agenda'                        => $agenda,
  2727.             'maestroDocumentosRepository'   => $maestroDocumentosRepository,
  2728.             'documentos'                    => $documentos,
  2729.             'agendaArchivosRepository'      => $agendaArchivosRepository
  2730.         ]);
  2731.     }
  2732.     /**
  2733.      * @Route("/control/documentos/guardar/{id}/{id_doc}", name="agenda_control_documentos_guardar", methods={"GET", "POST"})
  2734.      */
  2735.     public function agenda_control_documentos_guardar(Request $requestAgenda $agendaMaestroDocumentosRepository $maestroDocumentosRepository$id_docAgendaArchivosRepository $agendaArchivosRepository): Response
  2736.     {
  2737.         $ip     $request->getClientIp();
  2738.         $user   $this->security->getUser();
  2739.         $documento $maestroDocumentosRepository->find($id_doc);
  2740.         $brochureFile $request->files->get('doc'.$id_doc);
  2741.          //dd($brochureFile);
  2742.             
  2743.         if ($brochureFile) {
  2744.             $originalFilename pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
  2745.             $cedula $agenda->getPaciente()->getCedula();
  2746.                 
  2747.             // this is needed to safely include the file name as part of the URL
  2748.             //$safeFilename = $slugger->slug($originalFilename);
  2749.             $safeFilename ='c'.$cedula.'d'.$id_doc.date("YmdHis");
  2750.             //$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
  2751.             $newFilename $safeFilename.'.'.$brochureFile->guessExtension();
  2752.             // Move the file to the directory where brochures are stored
  2753.             try {
  2754.                 $brochureFile->move(
  2755.                     $this->getParameter('agenda'),
  2756.                     $newFilename
  2757.                 );
  2758.             } catch (FileException $e) {
  2759.             // ... handle exception if something happens during file upload
  2760.             }
  2761.             // updates the 'brochureFilename' property to store the PDF file name
  2762.             // instead of its contents
  2763.             //$agenda->getPaciente()->setCopiaCedula($newFilename);
  2764.             $agendaArchivo $agendaArchivosRepository->findOneBy(['agenda' => $agenda'estado' => 1'maestro_documentos' => $documento]);
  2765.             if($agendaArchivo == null){
  2766.                 $agendaArchivo = new AgendaArchivos();
  2767.             }
  2768.             //dd($agendaArchivo);
  2769.             $agendaArchivo->setAgenda($agenda);
  2770.             $agendaArchivo->setMaestroDocumentos($documento);
  2771.             $agendaArchivo->setOrden($documento->getOrden());
  2772.             $agendaArchivo->setEstado(1);
  2773.             $agendaArchivo->setTipo($documento->getTipo());
  2774.             $agendaArchivo->setRutaArchivo($newFilename);
  2775.             $agendaArchivo->setIpCrea($ip);
  2776.             $agendaArchivo->setIpModifica($ip);
  2777.             $agendaArchivo->setUserCrea($user->getId());
  2778.             $agendaArchivo->setUserModifica($user->getId()); 
  2779.             $entityManager $this->getDoctrine()->getManager();
  2780.             $entityManager->persist($agendaArchivo);
  2781.             $entityManager->flush();
  2782.             return $this->json(['estado' => 'ok']);
  2783.         }
  2784.         return $this->json(['estado' => 'error']);
  2785.     }
  2786.     
  2787.     /**
  2788.      * @Route("/cobertura/{cedula}", name="agenda_imprimir_cobertura", methods={"GET"})
  2789.      */
  2790.     public function imprimir_cobertura($cedula): Response
  2791.     {
  2792.         $options = array(
  2793.             CURLOPT_RETURNTRANSFER => true// return web page
  2794.             CURLOPT_HEADER         => false// don't return headers
  2795.             CURLOPT_FOLLOWLOCATION => true// follow redirects
  2796.             CURLOPT_ENCODING       => ""// handle all encodings
  2797.             CURLOPT_USERAGENT      => "spider"// who am i
  2798.             CURLOPT_AUTOREFERER    => true// set referer on redirect
  2799.             CURLOPT_CONNECTTIMEOUT => 120// timeout on connect
  2800.             CURLOPT_TIMEOUT        => 120// timeout on response
  2801.             CURLOPT_MAXREDIRS      => 10// stop after 10 redirects
  2802.             CURLOPT_SSL_VERIFYPEER => false,
  2803.         );
  2804.         
  2805.         //dd($options);
  2806.         $ch curl_init('https://coresalud.msp.gob.ec/coresalud/app.php/publico/rpis/afiliacion/consulta/' $cedula '/' date('d-m-Y'));
  2807.         curl_setopt_array($ch$options);
  2808.         $content curl_exec($ch);
  2809.         $err     curl_errno($ch);
  2810.         $errmsg  curl_error($ch);
  2811.         $header  curl_getinfo($ch);
  2812.         curl_close($ch);
  2813.         //dd($content);
  2814.         
  2815.         $pdfOptions = new Options();
  2816.         $pdfOptions->set('defaultFont''Arial');
  2817.         $pdfOptions->set('isRemoteEnabled'TRUE);
  2818.         $pdfOptions->set('isHtml5ParserEnabled'TRUE);
  2819.         //$pdfOptions->set('tempDir', 'C:\xampp\htdocs\sy_liquidacion2\public\assets\images');
  2820.         // Crea una instancia de Dompdf con nuestras opciones
  2821.         $dompdf = new Dompdf($pdfOptions);
  2822.         
  2823.         $arrContextOptions = array(
  2824.             "ssl" => array(
  2825.                 "verify_peer"      => false,
  2826.                 "verify_peer_name" => false,
  2827.             ),
  2828.         );//dd($arrContextOptions);
  2829.         $path   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/refresh.jpg';
  2830.         $type   pathinfo($pathPATHINFO_EXTENSION);
  2831.         $data   file_get_contents($pathfalsestream_context_create($arrContextOptions));
  2832.         $base64 'data:image/' $type ';base64,' base64_encode($data);
  2833.         
  2834.         $path_2   'https://coresalud.msp.gob.ec/coresalud/app.php/publico/registrousuario/captcha/new';
  2835.         $type_2   pathinfo($path_2PATHINFO_EXTENSION);
  2836.         $data_2   file_get_contents($path_2falsestream_context_create($arrContextOptions));
  2837.         $base64_2 'data:image/' $type_2 ';base64,' base64_encode($data_2);
  2838.         
  2839.         $content str_replace('<span class="label label-success">''<span class="label label-success"  >'$content);
  2840.         
  2841.         $content str_replace('#045FB4''black'$content);
  2842.         $content str_replace('btn-info''btn-info btn-info_2'$content);
  2843.         
  2844.         $path_msp   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/logomsp.png';
  2845.         $type_msp   pathinfo($path_mspPATHINFO_EXTENSION);
  2846.         $data_msp   file_get_contents($path_mspfalsestream_context_create($arrContextOptions));
  2847.         $base64_msp 'data:image/' $type_msp ';base64,' base64_encode($data_msp);
  2848.         
  2849.         $path_interior   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/mininterior.png';
  2850.         $type_interior   pathinfo($path_interiorPATHINFO_EXTENSION);
  2851.         $data_interior   file_get_contents($path_interiorfalsestream_context_create($arrContextOptions));
  2852.         $base64_interior 'data:image/' $type_interior ';base64,' base64_encode($data_interior);
  2853.         
  2854.         $path_defensa   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/mindefensa.png';
  2855.         $type_defensa   pathinfo($path_defensaPATHINFO_EXTENSION);
  2856.         $data_defensa   file_get_contents($path_defensafalsestream_context_create($arrContextOptions));
  2857.         $base64_defensa 'data:image/' $type_defensa ';base64,' base64_encode($data_defensa);
  2858.         
  2859.         $path_iess   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/iess.png';
  2860.         $type_iess   pathinfo($path_iessPATHINFO_EXTENSION);
  2861.         $data_iess   file_get_contents($path_iessfalsestream_context_create($arrContextOptions));
  2862.         $base64_iess 'data:image/' $type_iess ';base64,' base64_encode($data_iess);
  2863.         
  2864.         $path_issfa   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/issfa.png';
  2865.         $type_issfa   pathinfo($path_issfaPATHINFO_EXTENSION);
  2866.         $data_issfa   file_get_contents($path_issfafalsestream_context_create($arrContextOptions));
  2867.         $base64_issfa 'data:image/' $type_issfa ';base64,' base64_encode($data_issfa);
  2868.         
  2869.         $path_isspol   'https://coresalud.msp.gob.ec/coresalud/bundles/publico/img/isspol.png';
  2870.         $type_isspol   pathinfo($path_isspolPATHINFO_EXTENSION);
  2871.         $data_isspol   file_get_contents($path_isspolfalsestream_context_create($arrContextOptions));
  2872.         $base64_isspol 'data:image/' $type_isspol ';base64,' base64_encode($data_isspol);
  2873.         
  2874.         // Recupere el HTML generado en nuestro archivo twig
  2875.         $html $this->renderView('agenda/resultado.html.twig',[
  2876.             'content' => $content,
  2877.             'cedula'  => $cedula,
  2878.             'arrContextOptions' => $arrContextOptions,
  2879.             'path' => $path,
  2880.             'type' => $type,
  2881.             'data' => $data,
  2882.             'base64' => $base64,
  2883.             'path_2' => $path_2,
  2884.             'type_2' => $type_2,
  2885.             'data_2' => $data_2,
  2886.             'base64_2'   => $base64_2,
  2887.             'path_msp'   => $path_msp,
  2888.             'type_msp'   => $type_msp,
  2889.             'data_msp'   => $data_msp,
  2890.             'base64_msp' => $base64_msp,
  2891.             'path_interior'   => $path_interior,
  2892.             'type_interior'   => $type_interior,
  2893.             'data_interior'   => $data_interior,
  2894.             'base64_interior' => $base64_interior,
  2895.             'path_defensa'   => $path_defensa,
  2896.             'type_defensa'   => $type_defensa,
  2897.             'data_defensa'   => $data_defensa,
  2898.             'base64_defensa' => $base64_defensa,
  2899.             'path_iess'   => $path_iess,
  2900.             'type_iess'   => $type_iess,
  2901.             'data_iess'   => $data_iess,
  2902.             'base64_iess' => $base64_iess,
  2903.             'path_issfa'   => $path_issfa,
  2904.             'type_issfa'   => $type_issfa,
  2905.             'data_issfa'   => $data_issfa,
  2906.             'base64_issfa' => $base64_issfa,
  2907.             'path_isspol'   => $path_isspol,
  2908.             'type_isspol'   => $type_isspol,
  2909.             'data_isspol'   => $data_isspol,
  2910.             'base64_isspol' => $base64_isspol,
  2911.         ]);
  2912.         
  2913.         // Cargar HTML en Dompdf
  2914.         $dompdf->loadHtml($html);
  2915.         //$dompdf->loadHtmlFile($html);
  2916.         // (Opcional) Configure el tamaño del papel y la orientación 'vertical' o 'vertical'
  2917.         $dompdf->setPaper('A4''portrait');
  2918.         //dompdf->setPaper('A4', 'landscape');
  2919.         // Renderiza el HTML como PDF
  2920.         $dompdf->render();
  2921.         // Envíe el PDF generado al navegador (vista en línea)
  2922.         $dompdf->stream($cedula.".pdf", [
  2923.             "Attachment" => false
  2924.         ]);
  2925.         
  2926.         /*$pdf      = \App::make('dompdf.wrapper');
  2927.         $vistaurl = "resultados_pdf";
  2928.         $view     = \View::make($vistaurl, compact('content', 'cedula'))->render();
  2929.         $pdf->loadHTML($view);
  2930.         $pdf->setOptions(['dpi' => 150]);
  2931.         return $pdf->download('test.pdf');
  2932.         $datos = DB::table('excel')->where('id', $id)->first();
  2933.         if (is_null($datos)) {
  2934.             return "no existe el registro";
  2935.         }
  2936.         return $pdf->download($datos->nombre . '' . $datos->numero_paciente . '' . date('d-m-Y') . '.pdf');*/
  2937.     }
  2938.     
  2939.      /**
  2940.      * @Route("/agenda_archivo/delete/{id}", name="agenda_archivo_delete", methods={"GET", "POST"})
  2941.      */
  2942.     public function agenda_archivo_delete(Request $request$idAgendaArchivosRepository $agendaArchivosRepository): Response
  2943.     {
  2944.             $agendaArchivo $agendaArchivosRepository->find($id);
  2945.             //dd($agendaArchivo);
  2946.             $entityManager $this->getDoctrine()->getManager();
  2947.             $entityManager->remove($agendaArchivo);
  2948.             $entityManager->flush();
  2949.         
  2950.             
  2951.         
  2952.         return $this->json(['estado' => 'ok']); 
  2953.     }
  2954.     
  2955.     /**
  2956.      * @Route("/corregir/nota_entrega", name="masivo_corrige_nota_entrega", methods={"GET"})
  2957.      */
  2958.     public function masivo_corrige_nota_entrega(AgendaRepository $agendaRepositoryRecetaRepository $recetaRepository)
  2959.     {
  2960.         ini_set('memory_limit''100000000M'); 
  2961.         
  2962.         //$agendas = $agendaRepository->findByDate();
  2963.         //dd($agendas);
  2964.         
  2965.         /*foreach ($agendas as $agenda) {
  2966.             if($agenda->getHistoriaClinica() != null){
  2967.                 $historia = $agenda->getHistoriaClinica();
  2968.                 if($historia->getRecetas()->count() > 0){
  2969.                     $recetas = $historia->getRecetas();
  2970.                     foreach( $recetas as $receta ){
  2971.                         $detalles = $receta->getRecetaDetalles();
  2972.                         //dd($detalles);
  2973.                         foreach($detalles as $detalle){
  2974.                             //dd($detalle);
  2975.                             $nombre_nv = $detalle->getMedicina()->getNombre();
  2976.                             $detalle->setNombre($nombre_nv);
  2977.                             $detalle->setIpCrea('MAS03');
  2978.                             
  2979.                             $this->getDoctrine()->getManager()->flush();
  2980.                         }
  2981.                     }
  2982.                     
  2983.                 }
  2984.                 $agenda->setIpCrea('MAS03');
  2985.                             
  2986.                 $this->getDoctrine()->getManager()->flush();
  2987.             }
  2988.             
  2989.             
  2990.             
  2991.         }*/
  2992.         
  2993.         $recetas $recetaRepository->findByDate();
  2994.         foreach( $recetas as $receta ){
  2995.             $detalles $receta->getRecetaDetalles();
  2996.             //dd($detalles);
  2997.             foreach($detalles as $detalle){
  2998.                 //dd($detalle);
  2999.                 $nombre_nv $detalle->getMedicina()->getNombre();
  3000.                 $detalle->setNombre($nombre_nv);
  3001.                 $detalle->setIpCrea('MAS03');
  3002.                 
  3003.                 $this->getDoctrine()->getManager()->flush();
  3004.             }
  3005.         }
  3006.         //dd($recetas);
  3007.         
  3008.         return "ok";
  3009.           
  3010.     }
  3011.     
  3012.     /**
  3013.      * @Route("reunion/new_modal", name="agenda_reunion_new_modal", methods={"GET"})
  3014.      */
  3015.     public function reunion_new_modal(Request $requestPacienteRepository $pacienteRepositorySalaRepository $salaRepositoryUserRepository $userRepositoryEspecialidadRepository $especialidadRepository): Response
  3016.     {
  3017.         $agenda      = new Agenda();
  3018.         $session     $request->getSession();
  3019.         $id_sala     $session->get('id_sala');
  3020.         $paciente    $pacienteRepository->findOneBy(['cedula'=>'REUNION']);
  3021.         
  3022.         $sala        $salaRepository->find($id_sala);
  3023.         $sala_doctor 0;$especialidad null$nunidad null;
  3024.         $nunidad $sala->getUnidad()->getNombre();
  3025.         $doctor null;
  3026.         if($sala->getIdDoctor()!=null){//dd($sala->getIdDoctor());
  3027.             $sala_doctor $sala->getIdDoctor();
  3028.             $doctor $userRepository->find($sala_doctor);//dd($doctor);
  3029.             $especialidad $doctor->getEspecialidad();
  3030.             
  3031.         }else{
  3032.             
  3033.             if($sala->getUnidad()->getId()=='1'){
  3034.                 
  3035.                 $especialidad $especialidadRepository->find('1'); 
  3036.             
  3037.                 
  3038.             }else{
  3039.                 
  3040.                 $especialidad $especialidadRepository->find('17'); 
  3041.                 
  3042.             }
  3043.             
  3044.         }
  3045.         //dd($doctor);
  3046.         if($sala->getUnidad()->getId()== '1' and $doctor == null){
  3047.             $doctor $userRepository->find(2);//dd($doctor);
  3048.             $agenda->setDoctor($doctor);
  3049.             $especialidad $doctor->getEspecialidad();
  3050.             $agenda->setEspecialidad($especialidad);
  3051.             $sala        $salaRepository->findOneBy(['id_doctor' => '2']);
  3052.             $agenda->setSala($sala);//dd($agenda);
  3053.         }
  3054.         if($sala->getUnidad()->getId()== '2' and $doctor == null){
  3055.             $doctor $userRepository->find(12);//dd($doctor);
  3056.             $agenda->setDoctor($doctor);
  3057.             $especialidad $doctor->getEspecialidad();
  3058.             $agenda->setEspecialidad($especialidad);
  3059.             $sala        $salaRepository->findOneBy(['id_doctor' => '12']);
  3060.             $agenda->setSala($sala);
  3061.             //dd($especialidad);
  3062.         }
  3063.         
  3064.         $agenda->setEspecialidad($especialidad);
  3065.         //dd($sala->getUnidad(),$sala_doctor, $especialidad, $nunidad);
  3066.         
  3067.         $form $this->createForm(AgendaReunionType::class, $agenda, ['doctor' => $sala_doctor'especialidad' => $especialidad->getId(), 'unidad' => $nunidad ]);
  3068.         
  3069.         //dd($form);
  3070.         $form->handleRequest($request);
  3071.         
  3072.         return $this->render('agenda/reunion_new_modal.html.twig', [
  3073.             'agenda'   => $agenda,
  3074.             'form'     => $form->createView(),
  3075.             'paciente' => $paciente,
  3076.             'sala'     => $sala
  3077.         ]);
  3078.     }   
  3079.         
  3080.     /**
  3081.      * @Route("/calendar/medico/id_auth", name="agenda_calendar_medico", methods={"GET"})
  3082.      */
  3083.     public function calendar_medico(Request $requestEmpresaRepository $empresaRepositorySalaRepository $salaRepository): Response
  3084.     {
  3085.         
  3086.         $user   $this->security->getUser();
  3087.         $sala   $salaRepository->findOneBy(['id_doctor' => $user->getId()]);
  3088.         $id_sala $sala->getId();
  3089.         if($user->getId() == '2'){
  3090.             //$id_sala = '20';
  3091.         }
  3092.         if($user->getId() == '22'){
  3093.             //$id_sala = '33';
  3094.         }
  3095.         
  3096.         $sala   $salaRepository->find($id_sala);
  3097.         $session $request->getSession();
  3098.         $session->set('tipo_cal','0');
  3099.         
  3100.         if(!is_null($sala)){
  3101.         
  3102.             $session $request->getSession();
  3103.             $session->set('id_sala'$sala->getId());
  3104.             $empresa $empresaRepository->find(1);
  3105.         
  3106.             return $this->render('agenda/calendar.html.twig',['id_sala' => $sala->getId(), 'empresa' => $empresa'sala' => $sala]);
  3107.             
  3108.         }
  3109.         
  3110.         return $this->redirectToRoute('dashboard');
  3111.         
  3112.         
  3113.     }
  3114.     
  3115.     /**
  3116.      * @Route("/seguros/dia", name="agenda_seguros_dia", methods={"GET","POST"})
  3117.      */
  3118.     public function seguros_dia(AgendaRepository $agendaRepositoryPaginatorInterface $paginatorRequest $requestEmpresaRepository $empresaRepositoryOrdenVentaRepository $ordenVentaRepositoryFormaPagoRepository $formaPagoRepositorySeguroPrivadoRepository $seguroPrivadoRepository): Response
  3119.     {
  3120.         $user   $this->security->getUser();
  3121.         $seguros $seguroPrivadoRepository->findBy(['estado' => 1'tipo' => 2]);
  3122.         $empresa $empresaRepository->find(1);
  3123.         date_default_timezone_set("America/Guayaquil");
  3124.         $agenda = new Agenda();
  3125.         $form $this->createForm(BuscaPreparacionType_seguros::class,$agenda);
  3126.         $form->handleRequest($request);
  3127.         //$seguro = $form->get('seguro')->getData();
  3128.         $unidad $form->get('unidad')->getData();
  3129.         $fecha $form->get('inicio')->getData();
  3130.         $hasta $form->get('hasta')->getData();
  3131.         $paciente $form->get('paciente')->getData();
  3132.         $doctor $form->get('doctor')->getData();
  3133.         
  3134.         $datosPorSeguro = [];$datosPorSeguro2 = [];
  3135.         $resumenSeguro = [];$resultados2 = [];
  3136.         
  3137.         $session $request->getSession();
  3138.         $session->set('paciente',null);
  3139.         
  3140.         $meses = [
  3141.             '1' => 0'2' => 0'3' => 0'4' => 0
  3142.             '5' => 0'6' => 0'7' => 0'8' => 0
  3143.             '9' => 0'10' => 0'11' => 0'12' => 0
  3144.         ];
  3145.         $datosPorMes = [
  3146.             '1' => 0'2' => 0'3' => 0'4' => 0
  3147.             '5' => 0'6' => 0'7' => 0'8' => 0
  3148.             '9' => 0'10' => 0'11' => 0'12' => 0
  3149.         ];
  3150.         $datosPorMes2 = [
  3151.             '1' => 0'2' => 0'3' => 0'4' => 0
  3152.             '5' => 0'6' => 0'7' => 0'8' => 0
  3153.             '9' => 0'10' => 0'11' => 0'12' => 0
  3154.         ];
  3155.             
  3156.         if($form->isSubmitted()){
  3157.             if($fecha!=null){
  3158.                 //$session = $request->getSession();
  3159.                 $session->set('fecha_busqueda'$fecha);
  3160.             }
  3161.             if($hasta!=null){
  3162.                 //$session = $request->getSession();
  3163.                 $session->set('fecha_hasta'$hasta);
  3164.             }
  3165.             
  3166.             if($fecha==null){
  3167.                 $fecha = new \DateTime("now");
  3168.                 $form->get('inicio')->setData($fecha);
  3169.                 $session->set('fecha_busqueda'$fecha);  
  3170.             }
  3171.             if($hasta==null){
  3172.                 $hasta = new \DateTime("now");
  3173.                 $form->get('hasta')->setData($hasta);
  3174.                 $session->set('fecha_hasta'$hasta);  
  3175.             } 
  3176.             
  3177.             
  3178.                 
  3179.             $resultados $agendaRepository->findByEstadistico_Acum($unidaddate_format($fecha,'Y-m-d'))->getResult();
  3180.             // Inicializamos un array con todos los meses en 0
  3181.             
  3182.             $resultados2 $agendaRepository->findByEstadistico_Acum2($unidaddate_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'))->getResult();
  3183.             
  3184.             //dd($resultados2);
  3185.             
  3186.             // Procesamos los resultados y rellenamos los meses con los valores obtenidos
  3187.             foreach ($resultados as $resultado) {
  3188.                 $seguro $resultado['nombre_seguro'];
  3189.                 $anio $resultado['anio'];
  3190.                 $mes = (int)$resultado['mes']; // Convertimos el mes a entero para usar como índice
  3191.                 $oda $resultado['total_oda'];
  3192.                 $sub_total $resultado['sub_total'];
  3193.             
  3194.                 // Si el seguro no está en el array, inicializamos con los meses en 0
  3195.                 if (!isset($datosPorSeguro[$seguro])) {
  3196.                     $datosPorSeguro[$seguro] = $meses;
  3197.                     $datosPorSeguro2[$seguro] = $meses;
  3198.                     
  3199.                 }
  3200.             
  3201.                 // Asignamos el valor de oda al mes correspondiente
  3202.                 $datosPorSeguro[$seguro][$mes] = $oda;
  3203.                 $datosPorSeguro2[$seguro][$mes] = $sub_total;
  3204.                 $datosPorMes[$mes] += $oda;
  3205.                 $datosPorMes2[$mes] += $sub_total;
  3206.                 
  3207.             }
  3208.                 
  3209.             
  3210.         }else{
  3211.             $fecha $session->get('fecha_busqueda'); 
  3212.             if($fecha==null){
  3213.                 $fecha = new \DateTime("now");  
  3214.             }  
  3215.             $form->get('inicio')->setData($fecha);    
  3216.             $hasta $session->get('fecha_hasta'); 
  3217.             if($hasta==null){
  3218.                 $hasta = new \DateTime("now");  
  3219.             }  
  3220.             $form->get('hasta')->setData($hasta);
  3221.         }     
  3222.   
  3223.         foreach($seguros as $seguro){
  3224.             
  3225.             $query $agendaRepository->findByAdmisionadas_rpt(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$seguro,$paciente,$unidad,$doctor);
  3226.             $agendas $paginator->paginate(
  3227.                 $query,
  3228.                 $request->query->getInt('page',1),
  3229.                 100
  3230.             );
  3231.             $tabs[$seguro->getId()] = $agendas;
  3232.         
  3233.         }
  3234.         
  3235.         $seguros $seguroPrivadoRepository->findBy(['estado' => '1''tipo' => '2' ]); 
  3236.         
  3237.         if ($form->getClickedButton() === $form->get('Reporte_Admin')){
  3238.             
  3239.             return $this->reporte_xls_seguros$seguros$agendaRepository$fecha$hasta$ordenVentaRepository$empresa$paciente$unidad$doctor$datosPorSeguro$datosPorSeguro2$datosPorMes$datosPorMes2$resultados2 );
  3240.             
  3241.         }
  3242.         
  3243.         if ($form->getClickedButton() === $form->get('Reporte_Admin_2')){
  3244.             
  3245.             return $this->reporte_xls_seguros_2$seguros$agendaRepository$fecha$hasta$ordenVentaRepository$empresa$paciente$unidad$doctor$datosPorSeguro$datosPorSeguro2$datosPorMes$datosPorMes2$resultados2 );
  3246.             
  3247.         }
  3248.         
  3249.         //$estad = $agendaRepository->findByAdmisionadas_estad(date_format($fecha,'Y-m-d'),date_format($hasta,'Y-m-d'),$paciente,$unidad,$doctor)->getResult(); dd($estad);
  3250.         
  3251.         return $this->render('historia_clinica/index_seguro_dia.html.twig', [ 'tabs' => $tabs'form' => $form->createView(), 'empresa' => $empresa'fecha' => $fecha'hasta' => $hasta'seguros' => $seguros'ordenVentaRepository' => $ordenVentaRepository'datosPorSeguro' => $datosPorSeguro'datosPorSeguro2' => $datosPorSeguro2'datosPorMes' => $datosPorMes'datosPorMes2' => $datosPorMes2'resultados2' => $resultados2  ]);
  3252.     }
  3253.     
  3254.     public function reporte_xls_seguros$seguros$agendaRepository$fecha$hasta$ordenVentaRepository$empresa$paciente$unidad$doctor$datosPorSeguro$datosPorSeguro2$datosPorMes$datosPorMes2$resultados2 ){
  3255.         
  3256.         $spreadsheet = new Spreadsheet();
  3257.         // Eliminar la hoja por defecto que se crea automáticamente
  3258.         $spreadsheet->removeSheetByIndex(0);
  3259.         $cont 0;
  3260.         
  3261.         $arr_mes = ['Enero''Febrero''Marzo''Abril''Mayo''Junio''Julio''Agosto''Septiembre''Octubre''Noviembre''Diciembre'];
  3262.         $arr_letra range('B''ZZ');
  3263.         
  3264.         foreach($seguros as $seguro){
  3265.             $i 4;
  3266.             $agendas $agendaRepository->findByAdmisionadas_rpt(date_format($fecha,'Y-m-d'), date_format($hasta,'Y-m-d'), $seguro$paciente$unidad$doctor);
  3267.             $agendas $agendas->getResult();
  3268.             
  3269.             $sheet = new Worksheet($spreadsheet$seguro->getNombre());
  3270.             // Crear la segunda pestaña (Hoja 2)
  3271.     
  3272.             $spreadsheet->addSheet($sheet);
  3273.     
  3274.             $sheet->setTitle($seguro->getNombre());
  3275.             $titulo 'ATENCION DE CONSULTAS Y PROCEDIMIENTOS '.$seguro->getNombre().' DESDE:'.date_format($fecha,'Y-m-d').' HASTA:'.date_format($hasta,'Y-m-d');
  3276.             $sheet->setCellValue('A1'$empresa->getNombreCorto())->mergeCells('A1:J1');
  3277.             $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3278.             $sheet->setCellValue('A2'$titulo )->mergeCells('A2:J2');
  3279.             /////////////////////////////////
  3280.             $sheet->getStyle('A1:L3')->getFont()->setBold(true);
  3281.             $sheet->setCellValue('A3''FECHA');
  3282.             $sheet->setCellValue('B3''PACIENTE');
  3283.             $sheet->setCellValue('C3''TIPO DE SERVICIO');
  3284.             $sheet->setCellValue('D3''SEGURO');
  3285.             $sheet->setCellValue('E3''DIAGNOSTICO');
  3286.             $sheet->setCellValue('F3''NRO FACTURA');
  3287.             $sheet->setCellValue('G3''FECHA FACTURA');
  3288.             $sheet->setCellValue('H3''ODA');
  3289.             $sheet->setCellValue('I3''RETENCION');
  3290.             $sheet->setCellValue('J3''TOTAL PAGO');
  3291.             $sheet->setCellValue('K3''FECHA PAGO');
  3292.             $sheet->setCellValue('L3''VERIFICADO');
  3293.         
  3294.             $total_oda 0;
  3295.             foreach ($agendas as $value) {
  3296.                 $pxs $value['agenda']->getAgendaProcedimientos();
  3297.                 $sheet->setCellValue('A'.$idate_format($value['inicio'], 'd/m/Y'));
  3298.                 $sheet->setCellValue('B'.$i$value['paciente']);
  3299.                 $txt_proc $value['agenda']->getProcedimiento()->getNombre()."->  ";
  3300.                 foreach($pxs as $px){
  3301.                     $txt_proc.= $px->getProcedimiento()->getNombre()."->  ";
  3302.                 }
  3303.                 $sheet->setCellValue('C'.$i$txt_proc);
  3304.                 //$sheet->setCellValue('C'.$i, $value['agenda']->getProcedimiento()->getNombre());
  3305.                 $sheet->setCellValue('D'.$i$value['agenda']->getSeguro()->getNombre());
  3306.                 $dxs = [];$txt_dx '';
  3307.                 $historia $value['agenda']->getHistoriaClinica();
  3308.                 if($historia != null){
  3309.                     $dxs $historia->getDiagnosticosHistoriaClinicas();
  3310.                 }
  3311.                 foreach($dxs as $dx){
  3312.                     $txt_dx .= $dx->getCie10()->getNombre().' ';
  3313.                 }
  3314.                 $sheet->setCellValue('E'.$i$txt_dx);
  3315.                 $sheet->setCellValue('F'.$i$value['agenda']->getFactura());
  3316.                 $sheet->setCellValue('G'.$i$value['agenda']->getFechaFactura());
  3317.                 
  3318.                 $oda 0;
  3319.                 $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $value['agenda']->getId()]);
  3320.                 if(!is_null($orden)){
  3321.                     $total_oda += $orden->getOda();
  3322.                     $oda $orden->getOda();
  3323.                 }
  3324.                 $sheet->setCellValue('H'.$i$oda);
  3325.                 $retencion $oda 0.03;
  3326.                 $sheet->setCellValue('I'.$i$retencion);
  3327.                 $tp $oda $retencion;
  3328.                 $sheet->setCellValue('J'.$i$tp);
  3329.                 $sheet->setCellValue('K'.$i$value['agenda']->getFechaPago());
  3330.                 $sheet->setCellValue('L'.$i$value['agenda']->getVerificado());
  3331.                 
  3332.                 $sheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3333.                 $sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3334.                 $sheet->getStyle('J'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3335.     
  3336.                 $i++;
  3337.             }
  3338.         
  3339.             $sheet->getColumnDimension('A')->setWidth(10);
  3340.             $sheet->getColumnDimension('B')->setWidth(25);
  3341.             $sheet->getColumnDimension('C')->setWidth(20);
  3342.             $sheet->getColumnDimension('D')->setWidth(20);
  3343.             $sheet->getColumnDimension('E')->setWidth(25);
  3344.             $sheet->getColumnDimension('F')->setWidth(15);
  3345.             $sheet->getColumnDimension('G')->setWidth(15);
  3346.             $sheet->getColumnDimension('H')->setWidth(15);
  3347.             $sheet->getColumnDimension('I')->setWidth(15);
  3348.             $sheet->getColumnDimension('J')->setWidth(15);
  3349.             $sheet->getColumnDimension('K')->setWidth(15);
  3350.             $sheet->getColumnDimension('L')->setWidth(15);
  3351.        
  3352.             /////////////////////////////////
  3353.        
  3354.         
  3355.         }
  3356.         
  3357.         $sheet = new Worksheet($spreadsheet'RESUMEN ODA');
  3358.         // Crear la segunda pestaña (Hoja 2)
  3359.         $spreadsheet->addSheet($sheet);
  3360.         $sheet->setTitle('RESUMEN ODA');
  3361.         $sheet->setCellValue('A1''RESUMEN ODA')->mergeCells('A1:J1');
  3362.         $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3363.         $sheet->setCellValue('A2''SEGURO');
  3364.         $sheet->getColumnDimension('A')->setWidth(20);
  3365.         $n 0;
  3366.         foreach( $arr_mes as $mes ){
  3367.             $sheet->setCellValue($arr_letra[$n].'2'$mes);
  3368.             $sheet->getColumnDimension($arr_letra[$n])->setWidth(15);
  3369.             $n ++;
  3370.         }
  3371.         $z1 3;
  3372.         foreach( $datosPorSeguro as $empresa => $valores ){
  3373.             $sheet->setCellValue('A'.$z1$empresa);
  3374.             $n 0;
  3375.             foreach( $valores as $valor ){
  3376.                 $sheet->setCellValue($arr_letra[$n].$z1$valor);
  3377.                 $sheet->getStyle($arr_letra[$n].$z1)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3378.                 $n ++;
  3379.             }
  3380.             $z1 ++;
  3381.         }
  3382.         $sheet->setCellValue('A'.$z1' ');
  3383.         $n 0;
  3384.         foreach( $datosPorMes as $dmes ){
  3385.             $sheet->setCellValue($arr_letra[$n].$z1$dmes);
  3386.             $sheet->getStyle($arr_letra[$n].$z1)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3387.             $n ++;
  3388.         }
  3389.         
  3390.         /////////////////////////////////
  3391.         $sheet = new Worksheet($spreadsheet'RESUMEN TOTAL');
  3392.         // Crear la segunda pestaña (Hoja 2)
  3393.         $spreadsheet->addSheet($sheet);
  3394.         $sheet->setTitle('RESUMEN TOTAL');
  3395.         $sheet->setCellValue('A1''RESUMEN TOTAL')->mergeCells('A1:J1');
  3396.         $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3397.         $sheet->setCellValue('A2''SEGURO');
  3398.         $sheet->getColumnDimension('A')->setWidth(20);
  3399.         $n 0;
  3400.         foreach( $arr_mes as $mes ){
  3401.             $sheet->setCellValue($arr_letra[$n].'2'$mes);
  3402.             $sheet->getColumnDimension($arr_letra[$n])->setWidth(15);
  3403.             $n ++;
  3404.         }
  3405.         $z1 3;
  3406.         foreach( $datosPorSeguro2 as $empresa => $valores ){
  3407.             $sheet->setCellValue('A'.$z1$empresa);
  3408.             $n 0;
  3409.             foreach( $valores as $valor ){
  3410.                 $sheet->setCellValue($arr_letra[$n].$z1$valor);
  3411.                 $sheet->getStyle($arr_letra[$n].$z1)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3412.                 $n ++;
  3413.             }
  3414.             $z1 ++;
  3415.         }
  3416.         $sheet->setCellValue('A'.$z1' ');
  3417.         $n 0;
  3418.         foreach( $datosPorMes2 as $dmes ){
  3419.             $sheet->setCellValue($arr_letra[$n].$z1$dmes);
  3420.             $sheet->getStyle($arr_letra[$n].$z1)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3421.             $n ++;
  3422.         }
  3423.             
  3424.         /////////////////////////////////
  3425.         
  3426.         /////////////////////////////////
  3427.         $titulox 'RESUMEN SEGUROS DESDE:'.date_format($fecha,'Y-m-d').' HASTA:'.date_format($hasta,'Y-m-d');
  3428.         $sheet = new Worksheet($spreadsheet'RESUMEN SEGUROS');
  3429.         // Crear la segunda pestaña (Hoja 2)
  3430.         $spreadsheet->addSheet($sheet);
  3431.         $sheet->setTitle('RESUMEN TOTAL');
  3432.         $sheet->setCellValue('A1'$titulox)->mergeCells('A1:J1');
  3433.         $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3434.         $sheet->setCellValue('A2''SEGURO');
  3435.         $sheet->getColumnDimension('A')->setWidth(20);
  3436.         $n 0;
  3437.         
  3438.         $sheet->setCellValue('B2''ODA');
  3439.         $sheet->getColumnDimension('B')->setWidth(15);
  3440.         
  3441.         $sheet->setCellValue('C2''TOTAL');
  3442.         $sheet->getColumnDimension('C')->setWidth(15);
  3443.             $n ++;
  3444.        
  3445.         $z1 3;
  3446.         foreach( $resultados2 as $resultado ){
  3447.             $sheet->setCellValue('A'.$z1$resultado['nombre_seguro']);
  3448.             $sheet->setCellValue('B'.$z1$resultado['total_oda']);
  3449.             $sheet->setCellValue('C'.$z1$resultado['sub_total']);
  3450.             
  3451.             $z1 ++;
  3452.         }
  3453.         
  3454.         $n 0;
  3455.         
  3456.             
  3457.         /////////////////////////////////
  3458.         
  3459.         
  3460.         // Create your Office 2007 Excel (XLSX Format)
  3461.         $writer = new Xlsx($spreadsheet);
  3462.         
  3463.         // Create a Temporary file in the system
  3464.         $fileName 'AGENDA_DEL_DIA_'.date('Y-m-d').'.xlsx';
  3465.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  3466.         
  3467.         // Create the excel file in the tmp directory of the system
  3468.         $writer->save($temp_file);
  3469.         
  3470.         // Return the excel file as an attachment
  3471.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  3472.     }
  3473.     
  3474.     
  3475.     public function reporte_xls_seguros_2$seguros$agendaRepository$fecha$hasta$ordenVentaRepository$empresa$paciente$unidad$doctor$datosPorSeguro$datosPorSeguro2$datosPorMes$datosPorMes2$resultados2 ){
  3476.         
  3477.         $spreadsheet = new Spreadsheet();
  3478.         // Eliminar la hoja por defecto que se crea automáticamente
  3479.         $spreadsheet->removeSheetByIndex(0);
  3480.         $cont 0;
  3481.         
  3482.         $arr_mes = ['Enero''Febrero''Marzo''Abril''Mayo''Junio''Julio''Agosto''Septiembre''Octubre''Noviembre''Diciembre'];
  3483.         $arr_letra range('B''ZZ');
  3484.         
  3485.         
  3486.             $i 4;
  3487.             $agendas $agendaRepository->findByAdmisionadas_rpt_part(date_format($fecha,'Y-m-d'), date_format($hasta,'Y-m-d'), null$paciente$unidad$doctor);
  3488.             $agendas $agendas->getResult();
  3489.             
  3490.             $sheet = new Worksheet($spreadsheet'REPORTE');
  3491.             // Crear la segunda pestaña (Hoja 2)
  3492.     
  3493.             $spreadsheet->addSheet($sheet);
  3494.     
  3495.             $sheet->setTitle('REPORTE');
  3496.             $titulo 'ATENCION DE CONSULTAS Y PROCEDIMIENTOS DESDE:'.date_format($fecha,'Y-m-d').' HASTA:'.date_format($hasta,'Y-m-d');
  3497.             $sheet->setCellValue('A1'$empresa->getNombreCorto())->mergeCells('A1:J1');
  3498.             $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3499.             $sheet->setCellValue('A2'$titulo )->mergeCells('A2:J2');
  3500.             /////////////////////////////////
  3501.             $sheet->getStyle('A1:L3')->getFont()->setBold(true);
  3502.             $sheet->setCellValue('A3''FECHA');
  3503.             $sheet->setCellValue('B3''PACIENTE');
  3504.             $sheet->setCellValue('C3''TIPO DE SERVICIO');
  3505.             $sheet->setCellValue('D3''SEGURO');
  3506.             $sheet->setCellValue('E3''DIAGNOSTICO');
  3507.         
  3508.             $sheet->setCellValue('F3''ODA');
  3509.             $sheet->setCellValue('G3''RETENCION');
  3510.             $sheet->setCellValue('H3''TOTAL PAGO');
  3511.             //$sheet->setCellValue('I3', 'TOTAL FACTURA');
  3512.          
  3513.             //dd($resultados2);
  3514.         
  3515.             $total_oda 0;$total_ret 0;$total_acum 0;$total_factura 0;
  3516.             foreach ($agendas as $value) {
  3517.                 $pxs $value['agenda']->getAgendaProcedimientos();
  3518.                 $sheet->setCellValue('A'.$idate_format($value['inicio'], 'd/m/Y'));
  3519.                 $sheet->setCellValue('B'.$i$value['paciente']);
  3520.                 $txt_proc $value['agenda']->getProcedimiento()->getNombre()."->  ";
  3521.                 foreach($pxs as $px){
  3522.                     $txt_proc.= $px->getProcedimiento()->getNombre()."->  ";
  3523.                 }
  3524.                 $sheet->setCellValue('C'.$i$txt_proc);
  3525.                 $sheet->setCellValue('D'.$i$value['agenda']->getSeguro()->getNombre());
  3526.                 
  3527.                 $txt_color $value['agenda']->getSeguro()->getColor();
  3528.                 $txt_color substr($txt_color,1);
  3529.                 $sheet->getStyle('D'.$i)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF'.$txt_color); 
  3530.             
  3531.                 $dxs = [];$txt_dx '';
  3532.                 $historia $value['agenda']->getHistoriaClinica();
  3533.                 if($historia != null){
  3534.                     $dxs $historia->getDiagnosticosHistoriaClinicas();
  3535.                 }
  3536.                 foreach($dxs as $dx){
  3537.                     $txt_dx .= $dx->getCie10()->getNombre().' ';
  3538.                 }
  3539.                 $sheet->setCellValue('E'.$i$txt_dx);
  3540.                 
  3541.                 
  3542.                 $oda 0;$factura 0;
  3543.                 $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $value['agenda']->getId()]);
  3544.                 if(!is_null($orden)){
  3545.                     $total_oda += $orden->getOda();
  3546.                     $oda $orden->getOda();
  3547.                     $factura $orden->getSubtotal();
  3548.                     $total_factura += $factura;
  3549.                 }
  3550.                 $sheet->setCellValue('F'.$i$oda);
  3551.                 $retencion $oda 0.03;
  3552.                 $total_ret += $retencion;
  3553.                 $sheet->setCellValue('G'.$i$retencion);
  3554.                 $tp $oda $retencion;
  3555.                 $total_acum += $tp;
  3556.                 $sheet->setCellValue('H'.$i$tp);
  3557.                 //$sheet->setCellValue('I'.$i, $factura);
  3558.                 
  3559.                 $sheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3560.                 //$sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3561.                 $sheet->getStyle('J'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3562.     
  3563.                 $i++;
  3564.                 $sheet->setCellValue('E'.$i'TOTAL');
  3565.                 $sheet->setCellValue('F'.$i$total_oda);
  3566.                 $sheet->setCellValue('G'.$i$total_ret);
  3567.                 $sheet->setCellValue('H'.$i$total_acum);
  3568.                 //$sheet->setCellValue('I'.$i, $total_factura);
  3569.        
  3570.             /////////////////////////////////
  3571.        
  3572.         
  3573.         }
  3574.         
  3575.         $i++;
  3576.                 
  3577.         $sheet->getStyle('A'.$i.':B'.$i)->getFont()->setBold(true);        
  3578.         $sheet->setCellValue('A'.$i'SEGURO');
  3579.         $sheet->setCellValue('B'.$i'TOTAL ODA');
  3580.         
  3581.         $i++;
  3582.         $acum_oda 0;
  3583.         $acum_total 0;
  3584.         foreach( $resultados2 as $resultado ){
  3585.             if( $resultado['nombre_seguro'] != ' PARTICULAR GVITA'){
  3586.                 $acum_oda += $resultado['total_oda'];
  3587.                 $acum_total += $resultado['sub_total'];
  3588.                 
  3589.                 $sheet->setCellValue('A'.$i$resultado['nombre_seguro'] );
  3590.                 $sheet->setCellValue('B'.$i$resultado['total_oda']);
  3591.                 $i++;
  3592.             }    
  3593.         }
  3594.         $sheet->getStyle('A'.$i)->getFont()->setBold(true);
  3595.         $sheet->setCellValue('A'.$i'TOTAL' );
  3596.         $sheet->setCellValue('B'.$i$acum_oda);
  3597.         
  3598.         /*$sheet->getColumnDimension('A')->setWidth(20);
  3599.         $sheet->getColumnDimension('B')->setWidth(25);
  3600.         $sheet->getColumnDimension('C')->setWidth(20);
  3601.         $sheet->getColumnDimension('D')->setWidth(20);
  3602.         $sheet->getColumnDimension('E')->setWidth(25);
  3603.         $sheet->getColumnDimension('F')->setWidth(15);
  3604.         $sheet->getColumnDimension('G')->setWidth(15);
  3605.         $sheet->getColumnDimension('H')->setWidth(15);
  3606.         $sheet->getColumnDimension('I')->setWidth(15);
  3607.         $sheet->getColumnDimension('J')->setWidth(15);
  3608.         $sheet->getColumnDimension('K')->setWidth(15);
  3609.         $sheet->getColumnDimension('L')->setWidth(15);*/
  3610.             
  3611.         /////////////////////////////////
  3612.         $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
  3613.         
  3614.         $sheet->getPageSetup()->setFitToWidth(1);
  3615.         $sheet->getPageSetup()->setFitToHeight(1);
  3616.         
  3617.         // Definir un área de impresión automática basada en los datos
  3618.         $highestColumn $sheet->getHighestColumn(); // Última columna con datos
  3619.         $highestRow $sheet->getHighestRow(); // Última fila con datos
  3620.         $printArea 'A1:' $highestColumn $highestRow;
  3621.         $sheet->getPageSetup()->setPrintArea($printArea);
  3622.         // Ajustar tamaño de columnas automáticamente
  3623.         foreach (range('A'$highestColumn) as $col) {
  3624.             $sheet->getColumnDimension($col)->setAutoSize(true);
  3625.         }
  3626.         // Configurar márgenes mínimos para maximizar el espacio
  3627.         $sheet->getPageMargins()->setTop(0.2);
  3628.         $sheet->getPageMargins()->setRight(0.2);
  3629.         $sheet->getPageMargins()->setLeft(0.2);
  3630.         $sheet->getPageMargins()->setBottom(0.2);
  3631.         
  3632.         /////////////////////////////////
  3633.     
  3634.         
  3635.             
  3636.         /////////////////////////////////
  3637.         
  3638.         
  3639.         // Create your Office 2007 Excel (XLSX Format)
  3640.         $writer = new Xlsx($spreadsheet);
  3641.         
  3642.         // Create a Temporary file in the system
  3643.         $fileName 'AGENDA_DEL_DIA_'.date('Y-m-d').'.xlsx';
  3644.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  3645.         
  3646.         // Create the excel file in the tmp directory of the system
  3647.         $writer->save($temp_file);
  3648.         
  3649.         // Return the excel file as an attachment
  3650.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  3651.     }
  3652.     
  3653.     /**
  3654.      * @Route("/confirma/paciente/edit/{id}", name="agenda_confirma_paciente", methods={"GET"})
  3655.      */
  3656.     public function confirma_paciente(Request $requestAgenda $agenda): Response
  3657.     {
  3658.         $ip     $request->getClientIp();
  3659.         $user   $this->security->getUser();
  3660.         $logagenda   = new LogAgenda();
  3661.         $agenda->setConfirma(1);
  3662.         $logagenda->setUserCrea($user->getId());
  3663.         $logagenda->setUserModifica($user->getId());
  3664.         $inicio          $agenda->getInicio();
  3665.         $fin             $agenda->getFin();
  3666.         $seguro          $agenda->getSeguro();
  3667.         $especialidad    $agenda->getEspecialidad();
  3668.         $doctor          $agenda->getDoctor();
  3669.             
  3670.         $logagenda->setInicio($inicio);
  3671.         $logagenda->setFin($fin);
  3672.         $logagenda->setObservacion("CONFIRMA PACIENTE");
  3673.         $logagenda->setAgenda($agenda);
  3674.         $logagenda->setEstadoAgenda($agenda->getEstadoAgenda());
  3675.         $logagenda->setSeguro($seguro);
  3676.         $logagenda->setEspecialidad($especialidad);
  3677.         $logagenda->setDoctor($doctor);
  3678.         $logagenda->setDescripcion("CONFIRMA");
  3679.         $logagenda->setIpCrea($ip);
  3680.         $logagenda->setIpModifica($ip);
  3681.         $logagenda->setSala($agenda->getSala());
  3682.         $entityManager $this->getDoctrine()->getManager();
  3683.         $entityManager->persist($logagenda);
  3684.         
  3685.         $entityManager->flush(); 
  3686.         
  3687.         return $this->json(['estado' => 'ok']);
  3688.         
  3689.     }
  3690.     
  3691.     
  3692.     /**
  3693.      * @Route("/id/edit/update/desplazar", name="agenda_update_desplazar", methods={"POST"})
  3694.      */
  3695.     public function update_desplazar(Request $requestAgendaRepository $agendaRepository): JsonResponse
  3696.     {
  3697.         $ip     $request->getClientIp();
  3698.         $user   $this->security->getUser();
  3699.         $data json_decode($request->getContent(), true);
  3700.     
  3701.         $agenda $agendaRepository->find($data['id']);
  3702.         if (!$agenda) {
  3703.             return new JsonResponse(['error' => 'Evento no encontrado'], 404);
  3704.         }
  3705.         
  3706.         $inicio = new \DateTime($data['start']);
  3707.         $fin    = new \DateTime($data['end']);
  3708.         $agenda->setInicio($inicio);
  3709.         if ($data['end']) {
  3710.             $agenda->setFin($fin);
  3711.         }
  3712.         //dd($agenda);
  3713.         $observacion "DESPLAZA AGENDA";
  3714.         $descripcion "DESPLAZA AGENDA";
  3715.         
  3716.         $logagenda   = new LogAgenda();
  3717.         $logagenda->setSala($agenda->getsala());
  3718.         $logagenda->setIpCrea($ip);
  3719.         $logagenda->setIpModifica($ip);
  3720.         $logagenda->setEstadoAgenda($agenda->getEstadoAgenda());
  3721.         $logagenda->setUserCrea($user->getId());
  3722.         $logagenda->setUserModifica($user->getId());
  3723.         $logagenda->setInicio($inicio);
  3724.         $logagenda->setFin($fin);
  3725.         $logagenda->setObservacion($observacion);
  3726.         $logagenda->setAgenda($agenda);
  3727.         $logagenda->setSeguro($agenda->getSeguro());
  3728.         $logagenda->setEspecialidad($agenda->getEspecialidad());
  3729.         $logagenda->setDoctor($agenda->getDoctor());
  3730.         $logagenda->setDescripcion($descripcion);
  3731.         $em $this->getDoctrine()->getManager();
  3732.         $em->persist($agenda);
  3733.         $em->persist($logagenda);
  3734.         $em->flush();
  3735.     
  3736.         return new JsonResponse(['success' => true]);
  3737.     }
  3738.     
  3739.     /**
  3740.      * @Route("/seguros/dia/corte", name="agenda_seguros_dia_corte", methods={"GET","POST"})
  3741.      */
  3742.     public function seguros_dia_corte(AgendaRepository $agendaRepositoryPaginatorInterface $paginatorRequest $requestEmpresaRepository $empresaRepositoryOrdenVentaRepository $ordenVentaRepositoryFormaPagoRepository $formaPagoRepositorySeguroPrivadoRepository $seguroPrivadoRepository): Response
  3743.     {
  3744.         $user   $this->security->getUser();
  3745.         $seguros $seguroPrivadoRepository->findBy(['estado' => 1'tipo' => 2]);
  3746.         $empresa $empresaRepository->find(1);
  3747.         date_default_timezone_set("America/Guayaquil");
  3748.         $agenda = new Agenda();
  3749.         $form $this->createForm(BuscaPreparacionType_segurosCorte::class,$agenda);
  3750.         $form->handleRequest($request);
  3751.     
  3752.         $unidad $form->get('unidad')->getData();
  3753.         $corte $form->get('corte')->getData();
  3754.        
  3755.         $doctor $form->get('doctor')->getData();
  3756.         
  3757.         $datosPorSeguro = [];$datosPorSeguro2 = [];
  3758.         $resumenSeguro = [];$resultados2 = [];
  3759.         
  3760.         $session $request->getSession();
  3761.         $session->set('paciente',null);
  3762.         
  3763.         $meses = [
  3764.             '1' => 0'2' => 0'3' => 0'4' => 0
  3765.             '5' => 0'6' => 0'7' => 0'8' => 0
  3766.             '9' => 0'10' => 0'11' => 0'12' => 0
  3767.         ];
  3768.         $datosPorMes = [
  3769.             '1' => 0'2' => 0'3' => 0'4' => 0
  3770.             '5' => 0'6' => 0'7' => 0'8' => 0
  3771.             '9' => 0'10' => 0'11' => 0'12' => 0
  3772.         ];
  3773.         $datosPorMes2 = [
  3774.             '1' => 0'2' => 0'3' => 0'4' => 0
  3775.             '5' => 0'6' => 0'7' => 0'8' => 0
  3776.             '9' => 0'10' => 0'11' => 0'12' => 0
  3777.         ];
  3778.         
  3779.         if($corte==null){
  3780.             $fecha   = new \DateTime("now");
  3781.             $corte   $fecha->format('mY');
  3782.             $form->get('corte')->setData($corte);
  3783.               
  3784.         }
  3785.         if($unidad == null){
  3786.             $unidad 1;    
  3787.         }
  3788.             
  3789.         if($form->isSubmitted()){
  3790.             
  3791.             
  3792.                 
  3793.             
  3794.         }else{
  3795.             
  3796.             
  3797.         }     
  3798.         
  3799.         $resultados $agendaRepository->findByEstadistico_Acum_Corte($unidad$corte)->getResult();
  3800.         //dd($resultados, $corte);
  3801.         // Inicializamos un array con todos los meses en 0
  3802.         
  3803.         $resultados2 $agendaRepository->findByEstadistico_Acum2_Corte($unidad$corte)->getResult();
  3804.         //dd($resultados2);
  3805.         
  3806.         // Procesamos los resultados y rellenamos los meses con los valores obtenidos
  3807.         foreach ($resultados as $resultado) {
  3808.             $seguro $resultado['nombre_seguro'];
  3809.             $anio $resultado['anio'];
  3810.             $mes = (int)$resultado['mes']; // Convertimos el mes a entero para usar como índice
  3811.             $oda $resultado['total_oda'];
  3812.             $sub_total $resultado['sub_total'];
  3813.         
  3814.             // Si el seguro no está en el array, inicializamos con los meses en 0
  3815.             if (!isset($datosPorSeguro[$seguro])) {
  3816.                 $datosPorSeguro[$seguro] = $meses;
  3817.                 $datosPorSeguro2[$seguro] = $meses;
  3818.                 
  3819.             }
  3820.         
  3821.             // Asignamos el valor de oda al mes correspondiente
  3822.             $datosPorSeguro[$seguro][$mes] = $oda;
  3823.             $datosPorSeguro2[$seguro][$mes] = $sub_total;
  3824.             $datosPorMes[$mes] += $oda;
  3825.             $datosPorMes2[$mes] += $sub_total;
  3826.             
  3827.         }
  3828.   
  3829.         foreach($seguros as $seguro){
  3830.             
  3831.             $query $agendaRepository->findByAdmisionadas_rpt_Corte($corte $seguronull$unidad$doctor);
  3832.             $agendas $paginator->paginate(
  3833.                 $query,
  3834.                 $request->query->getInt('page',1),
  3835.                 100
  3836.             );
  3837.             $tabs[$seguro->getId()] = $agendas;
  3838.         
  3839.         }
  3840.         
  3841.         $seguros $seguroPrivadoRepository->findBy(['estado' => '1''tipo' => '2' ]); 
  3842.         
  3843.         //if ($form->getClickedButton() === $form->get('Reporte_Admin')){
  3844.             
  3845.             //return $this->reporte_xls_seguros( $seguros, $agendaRepository, $fecha, $hasta, $ordenVentaRepository, $empresa, $paciente, $unidad, $doctor, $datosPorSeguro, $datosPorSeguro2, $datosPorMes, $datosPorMes2, $resultados2 );
  3846.             
  3847.         //}
  3848.         
  3849.         if ($form->getClickedButton() === $form->get('Reporte_Admin')){
  3850.             
  3851.             return $this->reporte_xls_seguros_corte$seguros$agendaRepository$corte$ordenVentaRepository$empresanull$unidad$doctor$datosPorSeguro$datosPorSeguro2$datosPorMes$datosPorMes2$resultados2 );
  3852.             
  3853.         }
  3854.         
  3855.         
  3856.         return $this->render('historia_clinica/index_seguro_dia_corte.html.twig', [ 'tabs' => $tabs'form' => $form->createView(), 'empresa' => $empresa'corte' => $corte'seguros' => $seguros'ordenVentaRepository' => $ordenVentaRepository'datosPorSeguro' => $datosPorSeguro'datosPorSeguro2' => $datosPorSeguro2'datosPorMes' => $datosPorMes'datosPorMes2' => $datosPorMes2'resultados2' => $resultados2  ]);
  3857.     }
  3858.     
  3859.     public function reporte_xls_seguros_corte$seguros$agendaRepository$corte$ordenVentaRepository$empresa$paciente$unidad$doctor$datosPorSeguro$datosPorSeguro2$datosPorMes$datosPorMes2$resultados2 ){
  3860.         
  3861.         $spreadsheet = new Spreadsheet();
  3862.         // Eliminar la hoja por defecto que se crea automáticamente
  3863.         $spreadsheet->removeSheetByIndex(0);
  3864.         $cont 0;
  3865.         
  3866.         $arr_mes = ['Enero''Febrero''Marzo''Abril''Mayo''Junio''Julio''Agosto''Septiembre''Octubre''Noviembre''Diciembre'];
  3867.         $arr_letra range('B''ZZ');
  3868.         
  3869.         
  3870.             $i 4;
  3871.             $agendas $agendaRepository->findByAdmisionadas_rpt_corte2($cortenull$paciente$unidad$doctor);
  3872.             //dd($corte, null, $paciente, $unidad, $doctor, $agendas);
  3873.             $agendas $agendas->getResult();
  3874.             
  3875.             $sheet = new Worksheet($spreadsheet'REPORTE');
  3876.             // Crear la segunda pestaña (Hoja 2)
  3877.     
  3878.             $spreadsheet->addSheet($sheet);
  3879.     
  3880.             $sheet->setTitle('REPORTE');
  3881.             $titulo 'ATENCION DE CONSULTAS Y PROCEDIMIENTOS PERIODO: '.$corte;
  3882.             $sheet->setCellValue('A1'$empresa->getNombreCorto())->mergeCells('A1:J1');
  3883.             $sheet->getStyle('A1:M2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3884.             $sheet->setCellValue('A2'$titulo )->mergeCells('A2:J2');
  3885.             /////////////////////////////////
  3886.             $sheet->getStyle('A1:L3')->getFont()->setBold(true);
  3887.             $sheet->setCellValue('A3''FECHA');
  3888.             $sheet->setCellValue('B3''PACIENTE');
  3889.             $sheet->setCellValue('C3''TIPO DE SERVICIO');
  3890.             $sheet->setCellValue('D3''SEGURO');
  3891.             $sheet->setCellValue('E3''DIAGNOSTICO');
  3892.         
  3893.             $sheet->setCellValue('F3''ODA');
  3894.             $sheet->setCellValue('G3''RETENCION');
  3895.             $sheet->setCellValue('H3''TOTAL PAGO');
  3896.             //$sheet->setCellValue('I3', 'TOTAL FACTURA');
  3897.          
  3898.             //dd($resultados2);
  3899.         
  3900.             $total_oda 0;$total_ret 0;$total_acum 0;$total_factura 0;
  3901.             foreach ($agendas as $value) {
  3902.                 $pxs $value['agenda']->getAgendaProcedimientos();
  3903.                 $sheet->setCellValue('A'.$idate_format($value['inicio'], 'd/m/Y'));
  3904.                 $sheet->setCellValue('B'.$i$value['paciente']);
  3905.                 $txt_proc $value['agenda']->getProcedimiento()->getNombre()."\n";
  3906.                 foreach($pxs as $px){
  3907.                     $txt_proc.= $px->getProcedimiento()->getNombre()."\n";
  3908.                 }
  3909.                 $sheet->setCellValue('C'.$i$txt_proc);
  3910.                 $sheet->setCellValue('D'.$i$value['agenda']->getSeguro()->getNombre());
  3911.                 
  3912.                 $txt_color $value['agenda']->getSeguro()->getColor();
  3913.                 $txt_color substr($txt_color,1);
  3914.                 $sheet->getStyle('D'.$i)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF'.$txt_color); 
  3915.             
  3916.                 $dxs = [];$txt_dx '';
  3917.                 $historia $value['agenda']->getHistoriaClinica();
  3918.                 if($historia != null){
  3919.                     $dxs $historia->getDiagnosticosHistoriaClinicas();
  3920.                 }
  3921.                 foreach($dxs as $dx){
  3922.                     $txt_dx .= $dx->getCie10()->getNombre().' ';
  3923.                 }
  3924.                 $sheet->setCellValue('E'.$i$txt_dx);
  3925.                 
  3926.                 
  3927.                 $oda 0;$factura 0;
  3928.                 $orden $ordenVentaRepository->findOneBy(['tipo' => 'AGENDA''estado' =>  '1''id_agenda' => $value['agenda']->getId()]);
  3929.                 if(!is_null($orden)){
  3930.                     $total_oda += $orden->getOda();
  3931.                     $oda $orden->getOda();
  3932.                     $factura $orden->getSubtotal();
  3933.                     $total_factura += $factura;
  3934.                 }
  3935.                 $sheet->setCellValue('F'.$i$oda);
  3936.                 $retencion $oda 0.03;
  3937.                 $total_ret += $retencion;
  3938.                 $sheet->setCellValue('G'.$i$retencion);
  3939.                 $tp $oda $retencion;
  3940.                 $total_acum += $tp;
  3941.                 $sheet->setCellValue('H'.$i$tp);
  3942.                 //$sheet->setCellValue('I'.$i, $factura);
  3943.                 
  3944.                 $sheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3945.                 //$sheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3946.                 $sheet->getStyle('J'.$i)->getNumberFormat()->setFormatCode('### ### ### ##0.00');
  3947.     
  3948.                 $i++;
  3949.                 $sheet->setCellValue('E'.$i'TOTAL');
  3950.                 $sheet->setCellValue('F'.$i$total_oda);
  3951.                 $sheet->setCellValue('G'.$i$total_ret);
  3952.                 $sheet->setCellValue('H'.$i$total_acum);
  3953.                 //$sheet->setCellValue('I'.$i, $total_factura);
  3954.        
  3955.             /////////////////////////////////
  3956.        
  3957.         
  3958.         }
  3959.         
  3960.         $i++;
  3961.                 
  3962.         $sheet->getStyle('A'.$i.':B'.$i)->getFont()->setBold(true);        
  3963.         $sheet->setCellValue('A'.$i'SEGURO');
  3964.         $sheet->setCellValue('B'.$i'TOTAL ODA');
  3965.         
  3966.         $i++;
  3967.         $acum_oda 0;
  3968.         $acum_total 0;
  3969.         foreach( $resultados2 as $resultado ){
  3970.             if( $resultado['nombre_seguro'] != ' PARTICULAR GVITA'){
  3971.                 $acum_oda += $resultado['total_oda'];
  3972.                 $acum_total += $resultado['sub_total'];
  3973.                 
  3974.                 $sheet->setCellValue('A'.$i$resultado['nombre_seguro'] );
  3975.                 $sheet->setCellValue('B'.$i$resultado['total_oda']);
  3976.                 $i++;
  3977.             }    
  3978.         }
  3979.         $sheet->getStyle('A'.$i)->getFont()->setBold(true);
  3980.         $sheet->setCellValue('A'.$i'TOTAL' );
  3981.         $sheet->setCellValue('B'.$i$acum_oda);
  3982.         
  3983.         /*$sheet->getColumnDimension('A')->setWidth(20);
  3984.         $sheet->getColumnDimension('B')->setWidth(25);
  3985.         $sheet->getColumnDimension('C')->setWidth(20);
  3986.         $sheet->getColumnDimension('D')->setWidth(20);
  3987.         $sheet->getColumnDimension('E')->setWidth(25);
  3988.         $sheet->getColumnDimension('F')->setWidth(15);
  3989.         $sheet->getColumnDimension('G')->setWidth(15);
  3990.         $sheet->getColumnDimension('H')->setWidth(15);
  3991.         $sheet->getColumnDimension('I')->setWidth(15);
  3992.         $sheet->getColumnDimension('J')->setWidth(15);
  3993.         $sheet->getColumnDimension('K')->setWidth(15);
  3994.         $sheet->getColumnDimension('L')->setWidth(15);*/
  3995.             
  3996.         /////////////////////////////////
  3997.         $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
  3998.         
  3999.         $sheet->getPageSetup()->setFitToWidth(1);
  4000.         $sheet->getPageSetup()->setFitToHeight(1);
  4001.         
  4002.         // Definir un área de impresión automática basada en los datos
  4003.         $highestColumn $sheet->getHighestColumn(); // Última columna con datos
  4004.         $highestRow $sheet->getHighestRow(); // Última fila con datos
  4005.         $printArea 'A1:' $highestColumn $highestRow;
  4006.         $sheet->getPageSetup()->setPrintArea($printArea);
  4007.         // Ajustar tamaño de columnas automáticamente
  4008.         foreach (range('A'$highestColumn) as $col) {
  4009.             $sheet->getColumnDimension($col)->setAutoSize(true);
  4010.         }
  4011.         // Configurar márgenes mínimos para maximizar el espacio
  4012.         $sheet->getPageMargins()->setTop(0.2);
  4013.         $sheet->getPageMargins()->setRight(0.2);
  4014.         $sheet->getPageMargins()->setLeft(0.2);
  4015.         $sheet->getPageMargins()->setBottom(0.2);
  4016.         
  4017.         /////////////////////////////////
  4018.     
  4019.         
  4020.             
  4021.         /////////////////////////////////
  4022.         
  4023.         
  4024.         // Create your Office 2007 Excel (XLSX Format)
  4025.         $writer = new Xlsx($spreadsheet);
  4026.         
  4027.         // Create a Temporary file in the system
  4028.         $fileName 'AGENDA_DEL_DIA_'.date('Y-m-d').'.xlsx';
  4029.         $temp_file tempnam(sys_get_temp_dir(), $fileName);
  4030.         
  4031.         // Create the excel file in the tmp directory of the system
  4032.         $writer->save($temp_file);
  4033.         
  4034.         // Return the excel file as an attachment
  4035.         return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE); 
  4036.     }
  4037.     /**
  4038.      * @Route("/calendar/buscar", name="agenda_buscar", methods={"POST"})
  4039.      */
  4040.     public function buscarCalendarioAgenda(Request $requestAgendaRepository $repo): JsonResponse
  4041.     {
  4042.         $q $request->request->get('q');
  4043.         $resultados $repo->buscarAgenda($q);
  4044.         return $this->json($resultados);
  4045.     }
  4046.         
  4047.         
  4048.     
  4049.     
  4050. }