src/Aviatur/MultiBundle/Controller/FlightHotelController.php line 1151

Open in your IDE?
  1. <?php
  2. namespace Aviatur\MultiBundle\Controller;
  3. use Aviatur\GeneralBundle\Services\AviaturAthServices;
  4. use Knp\Snappy\Pdf;
  5. use Aviatur\AgencyBundle\Entity\Agency;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. use Aviatur\TwigBundle\Services\TwigFolder;
  8. use Aviatur\HotelBundle\Services\UrlService;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Routing\RouterInterface;
  12. use Aviatur\GeneralBundle\Services\ExceptionLog;
  13. use Aviatur\GeneralBundle\Services\AviaturPixeles;
  14. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  15. use Aviatur\MultiBundle\Services\MultiHotelDiscount;
  16. use Aviatur\FlightBundle\Services\SearchFlightCookie;
  17. use Aviatur\GeneralBundle\Services\AviaturWebService;
  18. use Symfony\Component\HttpFoundation\RedirectResponse;
  19. use Aviatur\GeneralBundle\Services\PayoutExtraService;
  20. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  21. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  22. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  23. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  24. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  25. use Aviatur\FlightBundle\Services\GenerateFlightResumeEmail;
  26. use Aviatur\GeneralBundle\Services\QuotationUtils;
  27. use Aviatur\CustomerBundle\Services\PhoneNumberService;
  28. use Aviatur\GeneralBundle\Service\MaintenanceTimeValidator;
  29. use Aviatur\SearchBundle\Entity\TravelDestination;
  30.         
  31. class FlightHotelController extends AbstractController
  32. {
  33.     private $em;
  34.     /**
  35.      * @var Agency|object|null
  36.      */
  37.     protected $agency;
  38.     /**
  39.      * @var bool
  40.      */
  41.     protected $isAval;
  42.     private MaintenanceTimeValidator $maintenanceTimeValidator;
  43.     public function __construct(ManagerRegistry $managerRegistrySessionInterface $sessionMaintenanceTimeValidator $maintenanceTimeValidator) {
  44.         $this->session $session;
  45.         $this->em $managerRegistry->getManager();
  46.         $this->agency $this->em->getRepository(Agency::class)->find($session->get('agencyId'));
  47.         $this->isAval $this->agency->getAssetsFolder() == 'aval';
  48.         $this->maintenanceTimeValidator $maintenanceTimeValidator;
  49.     }
  50.     public function resultsAction(Request $requestSessionInterface $sessionAviaturPixeles $aviaturPixelesManagerRegistry $registryAviaturErrorHandler $aviaturErrorHandlerSearchFlightCookie $searchFlightCookieAviaturWebService $aviaturWebServiceTwigFolder $twigFolderUrlService $urlService$origin1$destination1$date1$date2 null$rooms$adult1 null$child1 null$adult2 null,$child2 null$adult3 null$child3 null) {
  51.         $AvailabilityArray = [];
  52.         $urlDescription = [];
  53.         $pixel = [];
  54.         $em $this->em;
  55.         $fullRequest $request;
  56.         $isFront $session->has('operatorId');
  57.         $paymentType "online"// flightHotel have not another payment method by now
  58.         $isFront $session->has('operatorId');
  59.         $redirectResponse $this->maintenanceTimeValidator->validateMaintenanceTime('avail');
  60.         if ($redirectResponse !== null && !$isFront) {
  61.             return $redirectResponse;
  62.         }
  63.         // generate request url with
  64.         $configsHotelAgency $this->em
  65.             ->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)
  66.             ->findProviderForHotelsWithAgency($this->agency$paymentType);
  67.         //dd($configsHotelAgency, $this->agency);
  68.         $hotelProviders json_encode(
  69.             array_map(
  70.                 fn($config) => $config->getId(),
  71.                 $configsHotelAgency
  72.             )
  73.         );
  74.         $parameters json_decode($session->get($fullRequest->getHost().'[parameters]'));
  75.         $providersApi $parameters->hotel_avail_api;
  76.         $providersForHotelFilter = [];
  77.         if($isFront){
  78.             $providersForHotelFilter $this->em
  79.                 ->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)
  80.                 ->getProvidersForHotelFilter($this->agency$paymentType);
  81.         }
  82.         $safeQuery = [];
  83.         $safeParams = ['class''stop''airline''carryOn''baggage''tourCode''airlineTourCode''isActiveTourCode'];
  84.         foreach ($safeParams as $param) {
  85.             if ($fullRequest->query->has($param)) {
  86.                 $safeQuery[$param] = \urlencode($fullRequest->query->get($param));
  87.             }
  88.         }
  89.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), array_merge($fullRequest->attributes->get('_route_params'), $safeQuery));
  90.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  91.         if ($session->has('notEnableMultiHVSearch')) {
  92.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/''Busqueda de resultados''No podemos realizar la consulta ya que no existe un proveedor configurado para este servicio'));
  93.         }
  94.         $safeUrl 'https://'.$agency->getDomainsecure();
  95.         // CREATE FLIGHT/HOTEL URL FOR AJAX
  96.         $adults 0;
  97.         $children 0;
  98.         $infants 0;
  99.         $hotelPassenger null;
  100.         $services = [];
  101.         $countAdults 0;
  102.         $countChildren 0;
  103.         $childAgesCookie 0;
  104.         $flights 2;
  105.         $dateError = [];
  106.         for ($i 1$i <= $flights; ++$i) {
  107.             $AvailabilityArray['date'.$i] = false !== strpos(${'date'.$i}, 'T') ? date('Y-m-d\TH:i:s'strtotime(substr(${'date'.$i}, 010).sprintf('+%d hours'substr(${'date'.$i}, -2)))) : date('Y-m-d\TH:i:s'strtotime(substr(${'date'.$i}, 010)));
  108.             if ($i 1) {
  109.                 if (($AvailabilityArray['date'.$i] < $AvailabilityArray['date'.($i 1)]) || ((date('Y-m-d\TH:i:s'strtotime($AvailabilityArray['date'.$i])) < date('Y-m-d\TH:i:s'strtotime('today +6 hour'))) && ((date('H'strtotime('now')) >= 18) || (date('Y-m-d'strtotime('today')) > date('Y-m-d'strtotime($AvailabilityArray['date1']))))) || ($AvailabilityArray['date'.$i] > date('Y-m-d\TH:i:s'strtotime('+12 month')))) {
  110.                     $dateError[$i] = $AvailabilityArray['date'.$i];
  111.                 }
  112.             } else {
  113.                 if (((date('Y-m-d\TH:i:s'strtotime($AvailabilityArray['date'.$i])) < date('Y-m-d\TH:i:s'strtotime('today +6 hour'))) && ((date('H'strtotime('now')) >= 18) || (date('Y-m-d'strtotime('today')) > date('Y-m-d'strtotime($AvailabilityArray['date'.$i]))))) || ($AvailabilityArray['date'.$i] > date('Y-m-d\TH:i:s'strtotime('+11 month')))) {
  114.                     $dateError[$i] = $AvailabilityArray['date'.$i];
  115.                 }
  116.             }
  117.         }
  118.         if (!= sizeof($dateError)) {
  119.             //test: /vuelos/BAQ-BOG/2014-12-18+2014-12-15/1-0-0
  120.             foreach ($dateError as $key => $date) {
  121.                 if ($date date('Y-m-d\TH:i:s'strtotime('today +12 hour'))) {
  122.                     ${'date'.$key} = date('Y-m-d'strtotime('+1 day'));
  123.                 } elseif ($date date('Y-m-d\TH:i:s'strtotime('+28 day'))) {
  124.                     if (isset($AvailabilityArray['date'.($key 1)])) {
  125.                         ${'date'.$key} = date('Y-m-d'strtotime($AvailabilityArray['date'.($key 1)].'+1 week'));
  126.                         if (${'date'.$key} > date('Y-m-d\TH:i:s'strtotime('+28 day'))) {
  127.                             ${'date'.$key} = date('Y-m-d'strtotime('+27 day'));
  128.                         }
  129.                     } else {
  130.                         ${'date'.$key} = date('Y-m-d'strtotime(${'date'.$key}.'-12 month'));
  131.                     }
  132.                 } else {
  133.                     ${'date'.$key} = date('Y-m-d'strtotime($AvailabilityArray['date'.($key 1)].'+1 week'));
  134.                 }
  135.             }
  136.             $url $this->generateUrl(
  137.                 $request->get('_route'),
  138.                 [
  139.                 'date1' => $date1,
  140.                 'date2' => $date2,
  141.                 'origin1' => $origin1,
  142.                 'destination1' => $destination1,
  143.                 'rooms' => $rooms,
  144.                 'adult1' => $adult1,
  145.                 'child1' => $child1,
  146.                 'adult2' => $adult2,
  147.                 'child2' => $child2,
  148.                 'adult3' => $adult3,
  149.                 'child3' => $child3,
  150.                 'multi' => 'results',
  151.                 ]
  152.             );
  153.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($url'Recomendación Automática''La consulta que realizaste no era válida, hemos analizado tu búsqueda y esta es nuestra recomendación'));
  154.         }
  155.         for ($i 1$i <= $rooms; ++$i) {
  156.             $adults $adults + ${'adult'.$i};
  157.             $hotelPassenger .= '/'.${'adult'.$i}.'+'.${'child'.$i};
  158.             if ('n' != ${'child'.$i}) {
  159.                 $childs explode('-', ${'child'.$i});
  160.                 foreach ($childs as $child) {
  161.                     if($child 11) {
  162.                         ++$adults;
  163.                     }
  164.                     elseif ($child >= 2) {
  165.                         ++$children;
  166.                     } else {
  167.                         ++$infants;
  168.                     }
  169.                 }
  170.             }
  171.         }
  172.         $searchParam = ['class''stop''airline''carryOn''baggage''isActiveTourCode''airlineTourCode''tourCode'];
  173.         $optionalArray $this->getParamsInRequest($fullRequest$searchParam);
  174.         $optionals sizeof($optionalArray) > '?'.implode('&'$optionalArray) : '';
  175.         // CITY INFORMATION
  176.         $originLabel $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($origin1);
  177.         if (null == $originLabel) {
  178.             $originLabel $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findOneByIata($origin1)->getSearchCities();
  179.         }
  180.         $destinationLabel $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination1);
  181.         if (null == $destinationLabel) {
  182.             $destinationLabel $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findOneByIata($destination1)->getSearchCities();
  183.         }
  184.         $ajaxMultiFlightUrl '/vuelos/'.$originLabel->getIata().'-'.$destinationLabel->getIata().'/'.$date1.'+'.$date2.'/'.$adults.'-'.$children.'-'.$infants.$optionals;
  185.         $hotelDate1 false !== strpos($date1'T') ? substr($date1010) : $date1;
  186.         $hotelDate2 false !== strpos($date2'T') ? substr($date2010) : $date2;
  187.         $ajaxMultiHotelUrl '/hoteles/'.$destinationLabel->getIata().'/'.$hotelDate1.'+'.$hotelDate2.''.$hotelPassenger;
  188.         $AvailabilityArray = [
  189.             'originLabel1' => $originLabel->getCity().', '.$originLabel->getCountry().' ('.$originLabel->getIata().')',
  190.             'destinationLabel1' => $destinationLabel->getCity().', '.$destinationLabel->getCountry().' ('.$destinationLabel->getIata().')',
  191.             'originCity1' => $originLabel->getCity(),
  192.             'destinationCity1' => $destinationLabel->getCity(),
  193.             'date1' => $AvailabilityArray['date1'],
  194.             'date2' => $AvailabilityArray['date2'],
  195.             'origin1' => $origin1,
  196.             'destination1' => $destination1,
  197.             'adults' => $adults,
  198.             'children' => $children,
  199.             'infants' => $infants,
  200.             'rooms' => $rooms,
  201.             'countryCode' => $destinationLabel->getCountrycode(),
  202.         ];
  203.         $AvailabilityArray += [
  204.             'cityName' => $destinationLabel->getCity(),
  205.             'countryCode' => $originLabel->getCity(),
  206.             'StartDate' =>  $date1,
  207.             'EndDate' =>  $date2,
  208.             'Rooms' => $rooms,
  209.             'Destination' => $destinationLabel->getCity(),
  210.             'Nights' => (strtotime($date1) - strtotime($date2)) / 86400,
  211.         ];
  212.         for ($i 1$i <= $rooms; ++$i) {
  213.             ${'countAdults'.$i} = 0;
  214.             ${'countChildren'.$i} = 0;
  215.             $childrens = [];
  216.             if ('n' != ${'child'.$i}) {
  217.                 ${'child'.$i.'Ages'} = array_filter(explode('-', ${'child'.$i}));
  218.                 if (== $i) {
  219.                     $childAgesCookie = [
  220.                         'age'.$i => ${'child'.$i.'Ages'},
  221.                     ];
  222.                 }
  223.                 ${'child'.$i.'Size'} = is_countable(${'child'.$i.'Ages'}) ? count(${'child'.$i.'Ages'}) : 0;
  224.                 foreach (${'child'.$i.'Ages'} as $age) {
  225.                     $childrens[] = $age;
  226.                     ++${'countChildren'.$i};
  227.                     ++$countChildren;
  228.                 }
  229.             }
  230.             $countAdults $countAdults + ${'adult'.$i};
  231.             $services[] = ['adults' => ${'adult'.$i}, 'childrens' => $childrens];
  232.             $AvailabilityArray[$i] = [];
  233.             $AvailabilityArray[$i]['Children'] = ${'countChildren'.$i};
  234.             $AvailabilityArray[$i]['Adults'] = ${'adult'.$i};
  235.             if ($children >= ) {
  236.                 $AvailabilityArray[$i]['ChildrenAges'] = $childAgesCookie;
  237.             }
  238.         }
  239.         $cookieLastSearch $searchFlightCookie->searchFlightCookie(['flight' => base64_encode(json_encode($AvailabilityArray))]);
  240.         $AvailabilityArray['Children'] = $countChildren;
  241.         $AvailabilityArray['Adults'] = $countAdults;
  242.         $AvailabilityArray['Rooms'] = 1;
  243.         $ages explode('-'$child1);
  244.         for ($j 0$j sizeof($ages); ++$j) {
  245.             $cookieLastSearch['childAge'][$j] = $ages[$j];
  246.         }
  247.         $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  248.         if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  249.             $aviaturErrorHandler->errorRedirect('''Error MPA''No se creó Login!');
  250.             return new Response('Estamos experimentando dificultades técnicas en este momento.');
  251.         }
  252.         $ajaxMultiFlightUrl .= (sizeof($optionalArray) > '&' '?').'transactionMulti='.base64_encode($transactionIdResponse);
  253.         $ajaxMultiHotelUrl .= '?transactionMulti='.base64_encode($transactionIdResponse);
  254.         // RENDER VIEW
  255.         $agencyFolder $twigFolder->twigFlux();
  256.          $view $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Multi/Default/results.html.twig');
  257.         $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($ajaxMultiFlightUrl);
  258.         $urlDescription['long'] = null != $seoUrl $seoUrl[0]->getDescription() : '';
  259.         $urlDescription['short'] = null != $seoUrl $seoUrl[0]->getShortdescription() : '';
  260.         $seoMaskedUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
  261.         $urlDescription['url'] = null != $seoMaskedUrl '/'.$seoMaskedUrl[0]->getUrl() : $requestUrl;
  262.         $pixelInfo = [];
  263.         if (!$session->has('operatorId')) {
  264.             // PIXELES INFORMATION
  265.             $pixel['partner_datalayer']['flight'] = [
  266.                 'enabled' => true,
  267.                 'event' => 'paquete_search',
  268.                 'dimension1' => $destination1,
  269.                 'dimension2' => $origin1,
  270.                 'dimension3' => $date1,
  271.                 'dimension4' => $date2 ?? '',
  272.                 'dimension5' => 'Hotel+Vuelo',
  273.                 'dimension6' => '',
  274.                 'dimension7' => isset($destination1) ? 'RoundTrip' 'OneWay',
  275.                 'dimension8' => 'economy',
  276.                 'dimension9' => '',
  277.                 'dimension10' => ((int) $adult1 + (int) $adult2 + (int) $adult3 + (int) $child1 + (int) $child2 + (int) $child3),
  278.                 'dimension11' => '',
  279.                 'dimension12' => 'Busqueda-PaqueteVuelos',
  280.                 'ecommerce' => [
  281.                     'currencyCode' => 'COP',
  282.                 ],
  283.             ];
  284.             $pixel['partner_datalayer']['hotel'] = [
  285.                 'enabled' => true,
  286.                 'event' => 'paquete_search',
  287.                 'dimension1' => $destination1,
  288.                 'dimension2' => '',
  289.                 'dimension3' => $date1,
  290.                 'dimension4' => $date2,
  291.                 'dimension5' => 'Hotel+Vuelo',
  292.                 'dimension6' => '',
  293.                 'dimension7' => '',
  294.                 'dimension8' => '',
  295.                 'dimension9' => '',
  296.                 'dimension10' => ((int) $adult1 + (int) $child1 + (int) $adult2 + (int) $child2 + (int) $adult3 + (int) $child3),
  297.                 'dimension11' => $rooms,
  298.                 'dimension12' => 'Busqueda-PaqueteHotel',
  299.                 'ecommerce' => [
  300.                     'currencyCode' => 'COP',
  301.                 ],
  302.             ];
  303.             $pixelInfo $aviaturPixeles->verifyPixeles($pixel'multi''availability'$agency->getAssetsFolder(), false);
  304.         }
  305.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  306.         $rooms = [];
  307.         // Habitación 1
  308.         if ($adult1 !== null) {
  309.             $rooms[] = [
  310.                 "Adults" => (int)$adult1,
  311.                 "Children" => $child1 !== 'n' count(explode('-'$child1)) : 0,
  312.                 "childAges" => $child1 !== 'n' explode('-'$child1) : []
  313.             ];
  314.         }
  315.         // Habitación 2
  316.         if ($adult2 !== null) {
  317.             $rooms[] = [
  318.                 "Adults" => (int)$adult2,
  319.                 "Children" => $child2 !== 'n' count(explode('-'$child2)) : 0,
  320.                 "childAges" => $child2 !== 'n' explode('-'$child2) : []
  321.             ];
  322.         }
  323.         // Habitación 3
  324.         if ($adult3 !== null) {
  325.             $rooms[] = [
  326.                 "Adults" => (int)$adult3,
  327.                 "Children" => $child3 !== 'n' count(explode('-'$child3)) : 0,
  328.                 "childAges" => $child3 !== 'n' explode('-'$child3) : []
  329.             ];
  330.         }
  331.         $currentDate date('Y-m-d');
  332.         $endDateCensocud $parameters->date_end_cencosud;
  333.         $activeCheckCencosud = (strtotime($endDateCensocud) >= strtotime($currentDate));
  334.         $searchCitiesResult $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination1);
  335.         //si no obtiene datos se busca como id referencia de aeropuerto
  336.         if($searchCitiesResult === null){
  337.             $searchCitiesResult $destinationLabel;
  338.         }
  339.         $defaultCoordinates json_decode($searchCitiesResult->getCoordinates(), true);
  340.         // $hotelInfo = (Object)[];
  341.         // $hotelInfo->latitude = $defaultCoordinates['latitude'];
  342.         // $hotelInfo->longitude = $defaultCoordinates['longitude'];
  343.         // $hotelInfo->countryIata = $defaultCoordinates["countryCode"];
  344.         // $hotelInfo->providerId = "";
  345.         // $hotelInfo->hotelname = "";
  346.         // $travelDestination = $searchCitiesResult->getTravelDestination();
  347.         // if ($travelDestination === null) {
  348.         //     $storeResult = TravelDestinationController::fetchAndStoreHotelLocation($registry, $hotelInfo);
  349.         //     $latitude = $storeResult->results[0]->latitude ?? null;
  350.         //     $longitude = $storeResult->results[0]->longitude ?? null;
  351.         // } else {
  352.         //     $latitude = $travelDestination->getLatitude();
  353.         //     $longitude = $travelDestination->getLongitude();
  354.         // }
  355.         $hotelUrl $urlService->generateUrlHotelForMulti($destination1$date1$date2, (int) $adult1$child1$defaultCoordinates['latitude'],
  356.         $defaultCoordinates['longitude'], $rooms$searchCitiesResult);
  357.         $roomsToConsult $urlService->urlToRoomsArray($hotelUrl);
  358.         $jsonHotelAvailrq $urlService->jsonHotelAvailability($date1$date2strtoupper($searchCitiesResult->getIata()), 'MX'$defaultCoordinates['latitude'], $defaultCoordinates['longitude'], "10"$roomsToConsult$transactionIdResponse"HotelPackage");
  359.         $formatted 'las islas';
  360.         $type 'hotel';
  361.         $normalized_city 'Cartagena de Indias';
  362.         $destinationExist $this->em->getRepository(TravelDestination::class)->getMostPopularTravelDestinationResult($formatted$type$normalized_city);
  363.         $infoUrlPromoLasIslas null;
  364.         if(!is_null($destinationExist)) {
  365.             $providerId $destinationExist->getProviderIdentifier();
  366.             $hotelCode $destinationExist->getHotelCode();
  367.             if(!is_null($providerId) && !is_null($hotelCode)) {
  368.                 $infoUrlPromoLasIslas $hotelCode "-" $providerId;
  369.             }
  370.         }
  371.         $jsonHotelAvail = [
  372.             'HotelRq' => $jsonHotelAvailrq,
  373.             'payment' => 'online',
  374.         ];
  375.         $urlConsultPromo "";
  376.         $adults $AvailabilityArray['Adults'];
  377.         $children $AvailabilityArray['Children'];
  378.         if($children === 0) {
  379.             $children 'n';
  380.         }
  381.         
  382.         for ($i 1$i <= $AvailabilityArray['rooms']; $i++) {
  383.             if($i === 1) {
  384.                 $urlConsultPromo $date1 '+' $date2 '/';
  385.             }
  386.             $urlConsultPromo $urlConsultPromo 'room=' $i "&adults=" "&children=" $children;
  387.             if($i !== $AvailabilityArray['rooms']) {
  388.                 $urlConsultPromo $urlConsultPromo '/';
  389.             }
  390.         }
  391.         $countrycodePromo 'country=' strtolower($destinationLabel->getCountrycode());
  392.         $response $this->render($view, [
  393.             'availabilityFront' => $session->has('operatorId'),
  394.             'ajaxMultiUrl' => $requestUrl,
  395.             'destinationMetadata' => null,
  396.             'ajaxMultiFlightUrl' => $ajaxMultiFlightUrl,
  397.             'ajaxMultiHotelUrl' => $ajaxMultiHotelUrl,
  398.             'ajaxParameters' => base64_encode(json_encode($jsonHotelAvail)),
  399.             'countrycode' => $destinationLabel->getCountrycode(),
  400.             'checkin' => $date1,
  401.             'checkout' => $date2,
  402.             'roomsconsulturl' => 'rooms',
  403.             'availableArrayHotel' => $AvailabilityArray,
  404.             'cityName' => $destinationLabel->getCity(),
  405.             'isAval' => $this->isAval,
  406.             'QSE' => isset($QSE) ? $QSE null,
  407.             'safeUrl' => $safeUrl,
  408.             'urlDescription' => $urlDescription,
  409.             'AvailabilityArray' => $AvailabilityArray,
  410.             'cityOriginName' => $originLabel->getCity(),
  411.             'cityDestinationName' => $destinationLabel->getCity(),
  412.             'flights' => $flights,
  413.             'inlineEngine' => true,
  414.             'hotelProviders' => $hotelProviders,
  415.             'providersApi' => $providersApi,
  416.             'providersForHotelFilter' => $providersForHotelFilter,
  417.             // 'cookieLastSearch' => $cookieLastSearch,
  418.             'pixel_info' => $pixelInfo,
  419.             'activeCheckCencosud' => $activeCheckCencosud,
  420.             'online' => 'online',
  421.             'infoUrlPromoLasIslas' => $infoUrlPromoLasIslas,
  422.             'urlConsultPromo' => $urlConsultPromo,
  423.             'countrycodePromo' => $countrycodePromo
  424.         ]);
  425.         return $response;
  426.     }
  427.     public function resultsDetailAction(Request $requestSessionInterface $sessionAviaturLogSave $aviaturLogSaveParameterBagInterface $parameterBagAviaturPixeles $aviaturPixelesAuthorizationCheckerInterface $authorizationCheckerManagerRegistry $registryRouterInterface $routerAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolderAviaturWebService $webService) {
  428.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  429.         $responseFlightDetail = [];
  430.         $fullRequest null;
  431.         $isAgent false;
  432.         $currentRequest=$request;
  433.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  434.         $webService->setUrls($parameters);
  435.         $request $request->request;
  436.         $currentRoute$currentRequest->get('_route') ?? $request->get('_route');
  437.         $routeType explode('_'$currentRoute);
  438.         $transactionId $session->get($transactionIdSessionName);
  439.         $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  440.         if ((is_countable($request->get('RPH')) ? count($request->get('RPH')) : 0) < 2) {
  441.             $message $responseFlightDetail['error'] ?? 'No se ha recibido la información completa para consultar el detalle de tus vuelos.';
  442.             if (true === $session->has($transactionId.'[availability_url]')) {
  443.                 $returnUrl $session->get($transactionId.'[availability_url]');
  444.             }
  445.             return $this->redirect($aviaturErrorHandler->errorRedirect($returnUrl''$message));
  446.         }
  447.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) {
  448.             $user $this->getUser();
  449.             $agent $user->getAgent();
  450.             if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $this->agency->getId()) {
  451.                 $isAgent true;
  452.             }
  453.         }
  454.         // Generate Flight Detail
  455.         $route $router->match($this->generateUrl('aviatur_flight_'.$routeType[3].'_secure'));
  456.         $responseFlightDetail $this->generateFlightDetail($route$twigFolder$request$aviaturErrorHandler);
  457.         if ($responseFlightDetail instanceof RedirectResponse) {
  458.             return $responseFlightDetail;
  459.         }
  460.         if ('error' == $responseFlightDetail || 
  461.              (is_object($responseFlightDetail) && method_exists($responseFlightDetail'getStatusCode') && $responseFlightDetail->getStatusCode() === 500)) {            
  462.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción FD'));
  463.         }
  464.         // Generate Hotel Detail
  465.         $responseHotelDetail $this->generateHotelDetail(
  466.             $request->get('rooms'),
  467.             $request->get('hotelcode'),
  468.             $request->get('checkIn'),
  469.             $request->get('checkOut'),
  470.             $request->get('providerid'),
  471.             $request->get('countrycode')
  472.         );
  473.         if ($responseHotelDetail instanceof RedirectResponse) {
  474.             return $responseHotelDetail;
  475.         }
  476.         if(empty($responseHotelDetail['info'])) {
  477.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl'''Ha ocurrido un error inesperado'));
  478.         }
  479.         //$detailFlightJson = json_encode($responseFlightDetail, JSON_PRETTY_PRINT);
  480.         $detailFlightJson json_encode($responseFlightDetailJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE JSON_PARTIAL_OUTPUT_ON_ERROR);
  481.         $compressedDetailFlight base64_encode(gzcompress($detailFlightJson));
  482.         $availAbilityPrice = (int) $currentRequest->get('AvailAbilityPrice');
  483.         $availAbilityPriceArray = [];
  484.         $totalNetRooms null;
  485.         if (!empty($responseHotelDetail['acomodationRooms'])) {
  486.             foreach ($responseHotelDetail['acomodationRooms'] as $room) {
  487.                 if (isset($room['net'])) {
  488.                     $totalNetRooms += (float) $room['net'];
  489.                 }
  490.             }
  491.         }
  492.         $totalAmount $responseFlightDetail['resume_info']['total_amount'] + $totalNetRooms;
  493.         $acepttedRangeDiff 100;
  494.        if (isset($availAbilityPrice) && abs($totalAmount $availAbilityPrice) > $acepttedRangeDiff) {
  495.             $availAbilityPriceArray = [
  496.                 'isPriceEqual' => false,
  497.                 'availabilityprice' => $availAbilityPrice,
  498.                 'detailPrice' => $totalAmount
  499.             ];
  500.         }
  501.         // Generate Multi Detail
  502.         $responseMultiDetail $responseHotelDetail;
  503.         $responseMultiDetail += [
  504.             'detailFlight' => $responseFlightDetail,
  505.             'hotelProvidersId' => $responseHotelDetail["info"]["providers"][0],
  506.             'compressedDetailFlight' => $compressedDetailFlight,
  507.             'availAbilityPriceArray' => $availAbilityPriceArray
  508.         ];
  509.         $agencyFolder $twigFolder->twigFlux();
  510.         //$view = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/roomlistIndex.html.twig');
  511.         $view $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Default/roomlist.html.twig');
  512.         if (isset($responseMultiDetail['resume_info']['fee_type'])) {
  513.             $responseMultiDetail['resume_info']['fee_type'] = implode(','$responseMultiDetail['resume_info']['fee_type']);
  514.         }
  515.         $iinRecordsArray $this->getIINRanges($this->em);
  516.         $responseMultiDetail["ccranges"] = $iinRecordsArray["ccranges"];
  517.         $responseMultiDetail["ccfranchises"] = $iinRecordsArray["ccfranchises"];
  518.         return $this->render($view$responseMultiDetail);
  519.     }
  520.     public function generateFlightDetail(array $routeTwigFolder $twigFolder$requestAviaturErrorHandler $aviaturErrorHandler) {
  521.         $responseFlightDetailForward $this->forward($route['_controller'], $route);
  522.         $responseFlightDetail json_decode($responseFlightDetailForward->getContent(), true);
  523.         if (null == $responseFlightDetail) {
  524.             return $responseFlightDetailForward;
  525.         }
  526.         if (isset($responseFlightDetail['error'])) {
  527.             $message $responseFlightDetail['error'] ?? 'Ha ocurrido un error inesperado';
  528.             $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  529.             if (true === $request->has('referer')) {
  530.                 $returnUrl $request->get('http_referer');
  531.             }
  532.             if (isset($responseFlightDetail['no_message']) && (true == $responseFlightDetail['no_message'])) {
  533.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl''$message));
  534.             } else {
  535.                 return $this->redirect($aviaturErrorHandler->errorRedirect($returnUrl''$message));
  536.             }
  537.         }
  538.         // Convertir los segmentos y sus itinerarios a arrays
  539.         foreach ($responseFlightDetail['segments'] as $key => $segment) {
  540.             foreach ($segment['itinerary'] as $key1 => $flight) {
  541.                 $responseFlightDetail['segments'][$key]['itinerary'][$key1] = $this->simpleXmlToArray($flight);
  542.             }
  543.         }
  544.         $documentType $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  545.         $genderType $this->em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  546.         $repositoryDocumentType $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  547.         $queryDocumentType $repositoryDocumentType
  548.                 ->createQueryBuilder('p')
  549.                 ->where('p.paymentcode != :paymentcode')
  550.                 ->setParameter('paymentcode''')
  551.                 ->getQuery();
  552.         $documentPaymentType $queryDocumentType->getResult();
  553.         $banks = [];
  554.         if (in_array('pse'$responseFlightDetail['paymentOptions'])) {
  555.             $banks $this->em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  556.         }
  557.         if (array_search('safety'$responseFlightDetail['paymentOptions'])) {
  558.             unset($responseFlightDetail['paymentOptions'][array_search('safety'$responseFlightDetail['paymentOptions'])]);
  559.         }
  560.         if (array_search('baloto'$responseFlightDetail['paymentOptions'])) {
  561.             unset($responseFlightDetail['paymentOptions'][array_search('baloto'$responseFlightDetail['paymentOptions'])]);
  562.         }
  563.         $today date('Y-m-d');
  564.         $diffDays = (strtotime($responseFlightDetail['destination_array'][0]['DateTime']) - strtotime($today)) / 86400;
  565.         if ($diffDays 0) {
  566.             $responseFlightDetail['baloto'] = true;
  567.         }
  568.         $responseFlightDetail['baloto'] ?? ($responseFlightDetail['baloto'] = false);
  569.         foreach ($responseFlightDetail['providersName'] as $providerName) {
  570.             if (('Kiu' == $providerName)) {
  571.                 $responseFlightDetail['baloto'] = false;
  572.             }
  573.         }
  574.         $conditions $this->em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($this->agency'reservation_conditions');
  575.         unset($responseFlightDetail['doc_type'], $responseFlightDetail['gender'], $responseFlightDetail['payment_doc_type'], $responseFlightDetail['cards'], $responseFlightDetail['inactiveCards'], $responseFlightDetail['banks'], $responseFlightDetail['conditions']);
  576.         $responseFlightDetail += [
  577.             'doc_type' => $documentType,
  578.             'gender' => $genderType,
  579.             'payment_doc_type' => $documentPaymentType,
  580.             'cards' => $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
  581.             'inactiveCards' => $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
  582.             'banks' => $banks,
  583.             'conditions' => $conditions,
  584.         ];
  585.         return $responseFlightDetail;
  586.     }
  587.     public function generateHotelDetail($rooms$hotelcode$checkIn$checkOut$providerid$countrycode) {
  588.         $response $this->forward('Aviatur\HotelBundle\Controller\HotelRestController::roomListAction',
  589.             [
  590.                 'hotelcode'   => $hotelcode,
  591.                 'providerid'  => $providerid,
  592.                 'checkIn'     => $checkIn,
  593.                 'checkOut'    => $checkOut,
  594.                 'rooms'       => $rooms,
  595.                 'countrycode' => $countrycode,
  596.                 'isFlightHotel' => true
  597.             ]
  598.         );
  599.         $data json_decode($response->getContent(), true);
  600.         return $data;
  601.     }
  602.     public function checkoutAction(Request $request, \Swift_Mailer $mailerParameterBagInterface $parameterBagTwigFolder $twigFolderSessionInterface $sessionAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerAviaturWebService $aviaturWebService) {
  603.         // Obtener checkout de hoteles
  604.         $responseDetailHotel $this->forward('Aviatur\HotelBundle\Controller\HotelRestController::checkoutAction', [
  605.             'request' => $request,
  606.             'parameterBag' => $parameterBag,
  607.             'twigFolder' => $twigFolder,
  608.             'session' => $session,
  609.             'aviaturErrorHandler' => $aviaturErrorHandler,
  610.             'router' => $router,
  611.             'aviaturWebService' => $aviaturWebService,
  612.             'isFlightHotel' => true
  613.         ]);
  614.         $responseCheckout json_decode($responseDetailHotel->getContent(), true);
  615.         if (isset($responseCheckout['error'])) {
  616.             $message $responseCheckout['error'] ?? 'Ha ocurrido un error inesperado';
  617.             $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  618.             if (true === $request->has('referer')) {
  619.                 $returnUrl $request->get('http_referer');
  620.             }
  621.             if (isset($responseCheckout['no_message']) && (true == $responseCheckout['no_message'])) {
  622.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl''$message));
  623.             } else {
  624.                 return $this->redirect($aviaturErrorHandler->errorRedirect($returnUrl''$message));
  625.             }
  626.         }
  627.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  628.         $transactionId $session->get($transactionIdSessionName);
  629.         $em $this->em;
  630.         $phoneService = new PhoneNumberService($em);
  631.         $phonePrefixes $phoneService->getActivePrefixes();
  632.         $responseCheckout['phone_prefixes'] = $phonePrefixes;
  633.         $responseCheckout['default_country'] = 'CO';
  634.         $compressedDetailFlight  $request->request->get("flightDetail");
  635.         $detailFlightJson = \gzuncompress(base64_decode($compressedDetailFlight));
  636.         $flightDetail json_decode($detailFlightJsontrue);
  637.         $xmlData = new \SimpleXMLElement('<?xml version="1.0"?><root></root>');
  638.         // Convertir los segmentos y sus itinerarios a SimpleXMLElement
  639.         foreach ($flightDetail['segments'] as $key => $segment) {
  640.             foreach ($segment['itinerary'] as $key1 => $itinerary) {
  641.                 $xmlData = new \SimpleXMLElement('<?xml version="1.0"?><itinerary></itinerary>');
  642.                 $this->array_to_xml($itinerary$xmlData);
  643.                 $flightDetail['segments'][$key]['itinerary'][$key1] = $xmlData;
  644.             }
  645.         }
  646.         // hoteles
  647.         $cards $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]);
  648.         $repositoryDocumentType $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  649.         $queryDocumentType $repositoryDocumentType
  650.             ->createQueryBuilder('p')
  651.             ->where('p.paymentcode != :paymentcode')
  652.             ->setParameter('paymentcode''')
  653.             ->getQuery();
  654.         $documentPaymentType $queryDocumentType->getResult();
  655.         $typeDocument $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  656.         $typeGender $this->em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  657.         $inactiveCards $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]);
  658.         $documentPassengerType $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAllActiveConfigured();
  659.         // Hoteles
  660.         $responseCheckout['cards'] = $cards;
  661.         $responseCheckout['payment_doc_type'] = $documentPaymentType;
  662.         $responseCheckout['doc_type'] = $typeDocument;
  663.         $responseCheckout['gender'] = $typeGender;
  664.         $responseCheckout['checkoutHoteles'] = $request->request->get("HT");
  665.         //Se toma los pasajero de vuelos
  666.         $responseCheckout['services'] = $flightDetail['services'];
  667.         // Vuelos
  668.         $responseCheckout["flightDetail"] = $flightDetail;
  669.         $responseCheckout["flightDetail"]['cards'] = $cards;
  670.         $responseCheckout["flightDetail"]['payment_doc_type'] = $documentPaymentType;
  671.         $responseCheckout["flightDetail"]['doc_type'] = $typeDocument;
  672.         $responseCheckout["flightDetail"]['gender'] = $typeGender;
  673.         $responseCheckout["flightDetail"]['inactiveCards'] = $inactiveCards;
  674.         $responseCheckout['documentPassengerType'] = $documentPassengerType;
  675.         $responseCheckout['airlineFareTypes'] = $flightDetail['airlineFareTypes'];
  676.         $responseCheckout["isMulti"] = true;
  677.         $responseCheckout["routeType"] = $flightDetail["routeType"];
  678.         // Informacion de puntos para aval
  679.         if ($this->isAval) {
  680.             $responseCheckout $this->aviaturAthServices->getPointsInfoByAgency($responseCheckout$transactionId$this->agency);
  681.         }
  682.         $agencyFolder $twigFolder->twigFlux();
  683.         $view $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/checkoutIndex.html.twig');
  684.         return $this->render($view$responseCheckout);
  685.     }
  686.     public function prePaymentStep1Action(Request $requestRouterInterface $routerSessionInterface $sessionAviaturErrorHandler $aviaturErrorHandler)
  687.     {
  688.         $isFront $this->session->has('operatorId');
  689.         $redirectResponse $this->maintenanceTimeValidator->validateMaintenanceTime();
  690.         if ($redirectResponse !== null && !$isFront) {
  691.             return $this->json(['error' => 'error''message' => $redirectResponse["message"]]);
  692.         }
  693.         if ($request->isXmlHttpRequest()) {
  694.             $routeHotel $router->match($this->generateUrl('aviatur_hotel_prepayment_step_1_secureN'));
  695.             $responseHotel $this->forward($routeHotel['_controller'], $routeHotel);
  696.             $responseHotelData json_decode($responseHotel->getContent(), true);
  697.             if (isset($responseHotelData['error'])) {
  698.                 return $this->json($responseHotelData);
  699.             }
  700.             return $this->json([
  701.                 'hotel' => $responseHotelData,
  702.                 'ajax_url' => $this->generateUrl('aviatur_multi_prepayment_step_2_secureN'),
  703.             ]);
  704.         }
  705.         return $this->redirect($aviaturErrorHandler->errorRedirect(
  706.             $this->generateUrl('aviatur_general_homepage'),
  707.             '',
  708.             'Acceso no autorizado'
  709.         ));
  710.     }
  711.     public function prePaymentStep2Action(Request $requestRouterInterface $router) {
  712.         if ($request->isXmlHttpRequest()) {
  713.             $routeFlight $router->match($this->generateUrl('aviatur_flight_prepayment_step_1_secure'));
  714.             $responseFlight $this->forward($routeFlight['_controller'], $routeFlight);
  715.             $responseFlightData json_decode($responseFlight->getContent(), true);
  716.             if (isset($responseFlightData['error'])) {
  717.                 return $this->json($responseFlightData);
  718.             }
  719.             $routeHotel $router->match($this->generateUrl('aviatur_hotel_prepayment_step_2_secureN'));
  720.             $responseHotel $this->forward($routeHotel['_controller'], $routeHotel);
  721.             $responseHotelData json_decode($responseHotel->getContent(), true);
  722.             if (isset($responseHotelData['error'])) {
  723.                 return $this->json($responseHotelData);
  724.             }
  725.             return $this->json([
  726.                 'hotel' => $responseHotelData,
  727.                 'flight' => $responseFlightData,
  728.                 'ajax_url' => $this->generateUrl('aviatur_multi_prepayment_step_3_secureN'),
  729.             ]);
  730.         }
  731.     }
  732.     public function prePaymentStep3Action(Request $requestSessionInterface $sessionRouterInterface $router) {
  733.         if ($request->isXmlHttpRequest()) {
  734.             $routeFlight $router->match($this->generateUrl('aviatur_flight_prepayment_step_2_secure'));
  735.             $responseFlightPrepayment2Forward $this->forward($routeFlight['_controller'], $routeFlight);
  736.             $responseFlightPrepayment2 json_decode($responseFlightPrepayment2Forward->getContent(), true);
  737.             if (null == $responseFlightPrepayment2) {
  738.                 var_dump($responseFlightPrepayment2Forward->getContent());
  739.             }
  740.             if (isset($responseFlightPrepayment2['error'])) {
  741.                 return $this->json($responseFlightPrepayment2);
  742.             }
  743.             if ($session->has('operatorId')) {
  744.                 $url 'aviatur_multi_results_reservation_success_secure';
  745.             }else{
  746.                 $url 'aviatur_multi_payment_secureN';
  747.             }
  748.             $responseFlightPrepayment2['url'] = $this->generateUrl($url);
  749.             return $this->json($responseFlightPrepayment2);
  750.         }
  751.     }
  752.     public function paymentAction(Request $requestParameterBagInterface $parameterBagRouterInterface $routerSessionInterface $sessionAviaturErrorHandler $aviaturErrorHandler) {
  753.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  754.         $transactionId $session->get($transactionIdSessionName);
  755.         $postData json_decode($session->get($transactionId.'[flight][detail_data_flight]'));
  756.         $paymentData $postData->PD;
  757.         $routeFlight $router->match($this->generateUrl('aviatur_flight_payment_secure'));
  758.         $responseFlight $this->forward($routeFlight['_controller'], $routeFlight);
  759.         $responseFlightData json_decode($responseFlight->getContent(), true);
  760.         if (isset($responseFlightData['error'])) {
  761.             return $this->json($responseFlightData);
  762.         }
  763.         $routeHotel $router->match($this->generateUrl('aviatur_hotel_payment_secureN'));
  764.         $responseHotel $this->forward($routeHotel['_controller'], $routeHotel);
  765.         $responseHotelData json_decode($responseHotel->getContent(), true);
  766.         if (isset($responseHotelData['error'])) {
  767.             return $this->json($responseHotelData);
  768.         }
  769.         if ('p2p' == $paymentData->type) {
  770.             return $this->redirect($this->generateUrl('aviatur_multi_payment_p2p_return_url_secureN', [], true));
  771.         } else {
  772.             $session->set('redirectedRetry'true);
  773.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_multi_results_retry_secure'), '''El tipo de pago es inválido'));
  774.         }
  775.     }
  776.     public function p2pCallbackAction(SessionInterface $sessionMultiHotelDiscount $multiHotelDiscountPayoutExtraService $aviaturPayoutExtraRouterInterface $routerManagerRegistry $registryParameterBagInterface $parameterBag) {
  777.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  778.         $agency $this->agency;
  779.         $transactionId $session->get($transactionIdSessionName);
  780.         $routeFlight $router->match($this->generateUrl('aviatur_flight_payment_p2p_return_url_secure'));
  781.         $responseFlightP2PCallbackForward $this->forward($routeFlight['_controller'], $routeFlight);
  782.         $responseFlightP2PCallback json_decode($responseFlightP2PCallbackForward->getContent(), true);
  783.         if (isset($responseFlightP2PCallback['error'])) {
  784.             return $this->json($responseFlightP2PCallback);
  785.         }
  786.         $routeHotel $router->match($this->generateUrl('aviatur_hotel_payment_p2p_return_url_secureN'));
  787.         $responseHotelP2PCallbackForward $this->forward($routeHotel['_controller'], $routeHotel);
  788.         $responseHotelP2PCallback json_decode($responseHotelP2PCallbackForward->getContent(), true);
  789.         if (isset($responseHotelP2PCallback['error'])) {
  790.             return $this->json($responseHotelP2PCallback);
  791.         }
  792.         $responseFlight $router->match($responseFlightP2PCallbackForward->getTargetUrl());
  793.         $responseHotel $router->match($responseHotelP2PCallbackForward->getTargetUrl());
  794.         $responseFlightArray explode('_'$responseFlight['_route']);
  795.         $responseHotelArray explode('_'$responseHotel['_route']);
  796.         $responsePreference = ['rejected' => 4'pending' => 3'success' => 2'error' => 1];
  797.         if ($responsePreference[$responseFlightArray[3]] > $responsePreference[$responseHotelArray[3]]) {
  798.             $responseTwig 'aviatur_multi_results_payment_'.$responseFlightArray[3].'_secure';
  799.         } else {
  800.             $responseTwig 'aviatur_multi_results_payment_'.$responseHotelArray[3].'_secure';
  801.         }
  802.         $aviaturPayoutExtra->payoutExtrasCallback($responseTwig$transactionId'multi_1'$agency);
  803.         // if ('success' === $responseHotelArray[3]) {
  804.         //     $roomRateDiscount = $multiHotelDiscount->updateHotelReservationDiscount();
  805.         // }
  806.         return $this->redirect($this->generateUrl($responseTwig, [], true));
  807.     }
  808.     public function getCommentValue($search$comments)
  809.     {
  810.         return \preg_replace("/^{$search}: (.{0,100}).*$/"'$1', (string) $comments[$this->arraySearcher($comments$searchtrue)], 1);
  811.     }
  812.     public function arraySearcher($array$substring$position true)
  813.     {
  814.         $return array_filter($array, fn($var) => preg_match("/\b$substring\b/i"$var));
  815.         if ($position) {
  816.             $returnPositions array_keys($return);
  817.             return $returnPositions[0];
  818.         } else {
  819.             return $return;
  820.         }
  821.     }
  822.     public function quotationAction(Request $requestSessionInterface $sessionExceptionLog $exceptionLogGenerateFlightResumeEmail $generateFlightResumeEmailPdf $pdfManagerRegistry $registryRouterInterface $routerParameterBagInterface $parameterBagAviaturWebService $aviaturWebServiceTwigFolder $twigFolder, \Swift_Mailer $mailerQuotationUtils $QuotationUtils)
  823.     {
  824.         $projectDir $parameterBag->get('kernel.project_dir');
  825.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  826.         $emailData = [];
  827.         $fullRequest $request;
  828.         $transactionId $session->get($transactionIdSessionName);
  829.         $prepaymentInfo = \simplexml_load_string($session->get($transactionId '[hotel][prepayment]'));
  830.         $server $fullRequest->server;
  831.         $request $fullRequest->request;
  832.         $queryString $fullRequest->query;
  833.         $agency $this->agency;
  834.         $isINNS 0;
  835.         $agencyFolder $twigFolder->twigFlux();
  836.         $responseFlight = \simplexml_load_string($session->get($transactionId '[flight][detail]'));
  837.         $i 0;
  838.         $segments = [];
  839.         $itineraryFlights = [];
  840.         $j 0;
  841.         $flights = [];
  842.         $totalDuration 0;
  843.         $stopoverArrival null;
  844.         $resp $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption;
  845.         foreach ($resp as $key => $datas) {
  846.             foreach ($datas->FlightSegment as $flightSegment) {
  847.                 if (null != $stopoverArrival) {
  848.                     $totalDuration += (int) abs(strtotime($flightSegment['DepartureDateTime']) - strtotime($stopoverArrival)) / 60;
  849.                     $flightSegment->StopoverLength $generateFlightResumeEmail->convertToHoursMins(abs(strtotime($flightSegment['DepartureDateTime']) - strtotime($stopoverArrival)) / 60);
  850.                 }
  851.                 $comments = (array) $flightSegment->Comment;
  852.                 $flightSegment['DepartureCityName'] = $this->getCommentValue('DepartureCityName'$comments);
  853.                 $flightSegment['ArrivalCityName'] = $this->getCommentValue('ArrivalCityName'$comments);
  854.                 $flightSegment['DepartureAirportName'] = $this->getCommentValue('DepartureAirportName'$comments);
  855.                 $flightSegment['ArrivalAirportName'] = $this->getCommentValue('ArrivalAirportName'$comments);
  856.                 $flightSegment['DepartureCountryName'] = $this->getCommentValue('DepartureCountryName'$comments);
  857.                 $flightSegment['ArrivalCountryName'] = $this->getCommentValue('ArrivalCountryName'$comments);
  858.                 $flightSegment['DepartureCountryCode'] = $this->getCommentValue('DepartureCountryCode'$comments);
  859.                 $flightSegment['ArrivalCountryCode'] = $this->getCommentValue('ArrivalCountryCode'$comments);
  860.                 $flightSegment->FlightLength = (string) $generateFlightResumeEmail->convertToHoursMins(substr($comments[$this->arraySearcher($comments'Total Duration')], strpos($comments[$this->arraySearcher($comments'Total Duration')], ':') + 2100));
  861.                 $totalDuration += (int) substr($comments[$this->arraySearcher($comments'Total Duration')], strpos($comments[$this->arraySearcher($comments'Total Duration')], ':') + 2100);
  862.                 $stopoverArrival $flightSegment['ArrivalDateTime'];
  863.                 $flights[$i][] = $flightSegment;
  864.                 $departure_place = (string) $flightSegment['DepartureCityName'] . ', ' . (string) $flightSegment['DepartureCountryName'] . ' ' . (string) $flightSegment['DepartureCountryCode'];
  865.                 $arrival_place = (string) $flightSegment['ArrivalCityName'] . ', ' . (string) $flightSegment['ArrivalCountryName'] . ' ' . (string) $flightSegment['ArrivalCountryCode'];
  866.                 $itineraryFlights[] = ['dep' => $departure_place'arr' => $arrival_place'stopover' => ($j 0) ? true false];
  867.                 ++$j;
  868.             }
  869.             ++$i;
  870.         }
  871.         $responseHotel json_decode($session->get($transactionId '[hotel][detail]'));
  872.         $selectedRooms $session->get($transactionId "[hotel][selected_rooms]");
  873.         $selectedRate null;
  874.         foreach ($responseHotel->data->hotelRoomlist->hotels[0]->rates as $rate) {
  875.             if ($rate->rateKey === $selectedRooms[0]) {
  876.                 $selectedRate $rate;
  877.                 break;
  878.             }
  879.         }
  880.         $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  881.         $datosAgente simplexml_load_string($session->get('front_user'));
  882.         $detailHotelRaw $responseHotel->data->hotelRoomlist->hotels[0]->name;
  883.         $locationHotel =  $responseHotel->data->hotelRoomlist->hotels[0]->location->address;
  884.         $dateIn strtotime($responseHotel->data->hotelRoomlist->stay->checkIn);
  885.         $dateOut strtotime($responseHotel->data->hotelRoomlist->stay->checkOut);
  886.         $postDataJson $session->get($transactionId '[hotel][detail_data_hotel]');
  887.         if ($session->has($transactionId '[crossed]' '[url-hotel]')) {
  888.             $urlAvailability $session->get($transactionId '[crossed]' '[url-hotel]');
  889.         } elseif ($session->has($transactionId '[hotel][availability_url]')) {
  890.             $urlAvailability $session->get($transactionId '[hotel][availability_url]');
  891.         } else {
  892.             $urlAvailability $session->get($transactionId '[availability_url]');
  893.         }
  894.         $routeParsed parse_url($urlAvailability);
  895.         $availabilityUrl $router->match($routeParsed['path']);
  896.         $rooms = [];
  897.         for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  898.             $adult $availabilityUrl['adult' $i];
  899.             $child = [];
  900.             if ('n' != $availabilityUrl['child' $i]) {
  901.                 $child explode('-'$availabilityUrl['child' $i]);
  902.             }
  903.             $rooms[$i] = ['adult' => $adult'child' => $child];
  904.         }
  905.         $valorHotel $fullRequest->request->get('quotationPriceTotalMulti');
  906.         $detailHotel = [
  907.             'dateIn' => $dateIn,
  908.             'dateOut' => $dateOut,
  909.             'roomInformation' => $rooms,
  910.             'dateInStr' => (string) $responseHotel->data->hotelRoomlist->stay->checkIn,
  911.             'dateOutStr' => (string) $responseHotel->data->hotelRoomlist->stay->checkOut,
  912.             'nights' => floor(($dateOut $dateIn) / (24 60 60)),
  913.             'adults' => (string) $session->get($transactionId '[hotel][totalAdults]'),
  914.             'children' => (string) $session->get($transactionId '[hotel][totalChildren]'),
  915.             'rooms' => $responseHotel->data->hotelRoomlist->hotels[0],
  916.             'timeSpan' => $responseHotel->data->auditData->timestamp,
  917.             'basicInfos' => $selectedRate,
  918.             'total' => $selectedRate->net,
  919.             'category' => $selectedRate->boardName,
  920.             'description' => (string) $responseHotel->data->hotelRoomlist->hotels[0]->description,
  921.             // 'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
  922.             'services' => $responseHotel->data->hotelRoomlist->hotels[0]->services,
  923.             'photos' => $responseHotel->data->hotelRoomlist->hotels[0]->gallery,
  924.             'agentName' => simplexml_load_string($session->get('NOMBRE_USUARIO')) . ' ' simplexml_load_string($session->get('APELLIDOS_USUARIO')),
  925.             'agentMail' => simplexml_load_string($session->get('CORREO_ELECTRONICO')),
  926.             'agentPhone' => simplexml_load_string($session->get('TELEFONO_SUCURSAL')),
  927.             'agentAddress' => simplexml_load_string($session->get('DIRECCION_SUCURSAL')),
  928.             'namesClient' => $fullRequest->request->get('quotationName'),
  929.             'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
  930.             'emailClient' => $fullRequest->request->get('quotationEmail'),
  931.             'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotalMulti'),
  932.             'priceCurrency' => $fullRequest->request->get('quotationCurrencyMulti'),
  933.             'infoTerms' => $fullRequest->request->get('quotationTerms'),
  934.             'infoComments' => $fullRequest->request->get('quotationComments'),
  935.             'prepaymentsInfo' => $prepaymentInfo,
  936.             'longitude' => $responseHotel->data->hotelRoomlist->hotels[0]->location->coordinates->longitude,
  937.             'latitude' => $responseHotel->data->hotelRoomlist->hotels[0]->location->coordinates->latitude,
  938.         ];
  939.         $html $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Multi/Default/quotation.html.twig');
  940.         $namefilepdf 'Aviatur_cotizacion_hotel+vuelo_' $transactionId;
  941.         $voucherMultiFile $projectDir '/app/quotationLogs/multiQuotation/' $namefilepdf '.pdf';
  942.         $docPDF = [];
  943.         $vouchersFiles = [];
  944.         $z 0;
  945.         foreach ($responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption as $countOrgOption) {
  946.             ++$z;
  947.         }
  948.         $date floor(($dateOut $dateIn) / (24 60 60));
  949.         $totalHotel str_replace('.'''$valorHotel);
  950.         $codImg $QuotationUtils->curlImg($session);
  951.         $data = [
  952.             'countOrgOptionValue' => $z,
  953.             'datas' => $detailHotel,
  954.             'flightSegment' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption,
  955.             'terms' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->Notes,
  956.             'childrens' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions['ChdQuantity'],
  957.             'adults' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions['AdtQuantity'],
  958.             'infants' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions['InfQuantity'],
  959.             'agentName' => $datosAgente->NOMBRE_AGENTE,
  960.             'agentMail' => $datosAgente->CORREO_ELECTRONICO,
  961.             'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
  962.             'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL ?? $datosAgente->NOMBRE_OFICINA_PERTENECE,
  963.             'priceTotalQuotation' =>$fullRequest->request->get('quotationPriceTotalMulti'),
  964.             'priceCurrency' => $fullRequest->request->get('quotationCurrencyMulti'),
  965.             'typeRoom' => $fullRequest->request->get('typeRoom'),
  966.             'priceRoomNights' => $valorHotel,
  967.             'flightSegments' => $flights,
  968.             'pricingData' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItineraryPricingInfo,
  969.             'docCountries' => $docPDF,
  970.             'codImg' => $codImg,
  971.             'totalHotel' => $totalHotel,
  972.             'agentCity' => $datosAgente->CIUDAD,
  973.         ];
  974.         $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Cruise/Default/email_quotation.html.twig');
  975.         $emailData = [];
  976.         $body $this->renderView($urlResume$emailData);
  977.         if (!file_exists($voucherMultiFile)) {
  978.             // Configuración de opciones para generar el PDF
  979.             $pdf->setOption('page-size''LETTER');
  980.             $pdf->setOption('margin-top'0);
  981.             $pdf->setOption('margin-right'0);
  982.             $pdf->setOption('margin-bottom'0);
  983.             $pdf->setOption('margin-left'0);
  984.             $pdf->setOption('orientation''portrait');
  985.             $pdf->setOption('enable-javascript'true);
  986.             $pdf->setOption('no-stop-slow-scripts'true);
  987.             $pdf->setOption('no-background'false);
  988.             $pdf->setOption('lowquality'false);
  989.             $pdf->setOption('encoding''utf-8');
  990.             $pdf->setOption('images'true);
  991.             $pdf->setOption('dpi'300);
  992.             $pdf->setOption('enable-external-links'true);
  993.             $pdf->setOption('enable-internal-links'true);
  994.             // Genera el PDF
  995.             $pdf->generateFromHtml($this->renderView($html$data), $voucherMultiFile);
  996.         }
  997.         $nameProduct str_replace(["cotizacion""/""check-conditions"], ""$fullRequest->getPathInfo());
  998.         $QuotationUtils->sendQuotation($nameProduct,$voucherMultiFile$mailer$session$twigFolder$codImg$fullRequest,$parameterBag $aviaturWebService ,$pdf $exceptionLog);
  999.         $request = new Request();
  1000.         if (file_exists($voucherMultiFile)) {
  1001.             unlink($voucherMultiFile);
  1002.         }
  1003.         // $this->saveInformationCGSVuelos($request, $aviaturLogSave, $registry, $aviaturErrorHandler, $aviaturWebService, $responseFlight, $z, $additionalUserFront, $detailHotel, $agency);
  1004.         return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Hotel/Default/resume_quotation.html.twig'), ['nameProduct'=> $nameProduct]);
  1005.     }
  1006.     public function paymentOutputAction(Request $requestSessionInterface $session, \Swift_Mailer $mailerAviaturPixeles $aviaturPixelesPdf $pdfTwigFolder $twigFolderManagerRegistry $registryRouterInterface $routerParameterBagInterface $parameterBagExceptionLog $exceptionLog) {
  1007.         $projectDir $parameterBag->get('kernel.project_dir');
  1008.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1009.         $emailNotification $parameterBag->get('email_notification');
  1010.         $voucherFile null;
  1011.         $transactionId $session->get($transactionIdSessionName);
  1012.         $session->set($transactionId.'[multi]'.'[validation]'true);
  1013.         $agency $this->agency;
  1014.         $detailData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  1015.         if ($session->has('operatorId')) {
  1016.             $routeNameFlight 'aviatur_flight_reservation_success_secure';
  1017.             $routeNameHotel 'aviatur_hotel_reservation_success_secureN';
  1018.         } else {
  1019.             $routeName explode('_'$request->get('_route'));
  1020.             $routeNameFlight 'aviatur_flight_payment_'.$routeName[4].'_secure';
  1021.             $routeNameHotel $routeName[4] == 'success'
  1022.                 'aviatur_hotel_reservation_'.$routeName[4].'_secureN'
  1023.                 'aviatur_hotel_payment_'.$routeName[4].'_secureN';
  1024.         }
  1025.         //Vuelos
  1026.         $routeFlight $router->match($this->generateUrl($routeNameFlight));
  1027.         $responseFlightPaymentOutputForward $this->forward($routeFlight['_controller'], $routeFlight);
  1028.         $responseFlightPaymentOutput json_decode($responseFlightPaymentOutputForward->getContent(), true);
  1029.         if (null == $responseFlightPaymentOutput) {
  1030.             var_dump($responseFlightPaymentOutputForward->getContent());
  1031.         }
  1032.         if (isset($responseFlightPaymentOutput['error'])) {
  1033.             return $this->json($responseFlightPaymentOutput);
  1034.         }
  1035.         //Hoteles
  1036.         $routeHotel $router->match($this->generateUrl($routeNameHotel));
  1037.         $responseHotelPaymentOutputForward $this->forward($routeHotel['_controller'], $routeHotel);
  1038.         $responseHotelPaymentOutput json_decode($responseHotelPaymentOutputForward->getContent(), true);
  1039.         if (empty($responseHotelPaymentOutput)) {
  1040.             var_dump($responseHotelPaymentOutputForward->getContent());
  1041.         }
  1042.         if (isset($responseHotelPaymentOutput['error'])) {
  1043.             return $this->json($responseHotelPaymentOutput);
  1044.         }
  1045.         if (isset($responseHotelPaymentOutput['emissionData']) && !isset($responseHotelPaymentOutput['emailData']['emissionData'])) {
  1046.             $responseHotelPaymentOutput['emailData']['emissionData'] = $responseHotelPaymentOutput['emissionData'];
  1047.         }
  1048.         $responsePaymentOutput = [
  1049.             'flightResumen' => $responseFlightPaymentOutput,
  1050.             'hotelResumen' => $responseHotelPaymentOutput,
  1051.             'rooms' => $responseHotelPaymentOutput["emailData"]["rooms"],
  1052.             'countryCode' => $responseHotelPaymentOutput["emailData"]["countryCode"],
  1053.             'alertsValidation' => $responseHotelPaymentOutput["emailData"]["alertsValidation"],
  1054.             'payment' => $responseHotelPaymentOutput["emailData"]["payment"],
  1055.             'data_amount_total' => $detailData->data_amount_total ?? 0,
  1056.             'isAval' => $this->isAval
  1057.         ];
  1058.         $this->sendEmailThankYouPageAction($routeNameFlight$routeNameHotel$responsePaymentOutput$mailer$session$twigFolder$parameterBag);
  1059.         $agencyFolder $twigFolder->twigFlux();
  1060.         $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/thankYouPage.html.twig');
  1061.         return $this->render($urlResume$responsePaymentOutput);
  1062.     }
  1063.     public function sendEmailThankYouPageAction($routeNameFlight$routeNameHotel$responsePaymentOutput, \Swift_Mailer $mailerSessionInterface $sessionTwigFolder $twigFolderParameterBagInterface $parameterBag) {
  1064.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1065.         $transactionId $session->get($transactionIdSessionName);
  1066.         $postDataFlight json_decode($session->get($transactionId '[flight][detail_data_flight]'));
  1067.         $postDataHotel json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  1068.         $customerId $postDataFlight->BD->id ?? $postDataHotel->BD->id;
  1069.         $customer $this->em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($customerId);
  1070.         $datosAgente simplexml_load_string($session->get('front_user'));
  1071.         $bccMails = ['supervisorescallcenter@aviatur.com''notificacionessitioweb@aviatur.com'];
  1072.         if ($session->has('operatorId')) {
  1073.             $setTo $datosAgente->CORREO_ELECTRONICO;
  1074.         }else {
  1075.             $setTo $customer->getEmail();
  1076.         }
  1077.         $agencyFolder $twigFolder->twigFlux();
  1078.         $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/emailThankYou.html.twig');
  1079.         $subjectPrefix $session->get('agencyShortName') . ' - ';
  1080.         $emissionData $responsePaymentOutput["hotelResumen"]["emissionData"] ?? null;
  1081.         $flightParts explode('_'$routeNameFlight);
  1082.         $hotelParts explode('_'$routeNameHotel);
  1083.         $flightStatus = isset($flightParts[3]) ? $flightParts[3] : null;
  1084.         $hotelStatus = isset($hotelParts[3]) ? $hotelParts[3] : null;
  1085.         $responsePreference = ['success' => 1'rejected' => 2'pending' => 3'error' => 4];
  1086.         if ($flightStatus && $hotelStatus) {
  1087.             $selectedStatus $responsePreference[$flightStatus] > $responsePreference[$hotelStatus] ? $hotelStatus $flightStatus;
  1088.         } else {
  1089.             $selectedStatus $flightStatus ?: $hotelStatus;
  1090.         }
  1091.         if ($emissionData === 'No Reservation') {
  1092.             $selectedStatus 'rejected';
  1093.         }
  1094.         switch ($selectedStatus) {
  1095.             case 'success':
  1096.                 $setSubject 'Gracias por su compra';
  1097.                 break;
  1098.             case 'rejected':
  1099.                 $setSubject 'Pago rechazado';
  1100.                 break;
  1101.             case 'pending':
  1102.                 $setSubject 'Pago pendiente';
  1103.                 break;
  1104.             default:
  1105.                 $setSubject 'Estado de la transacción';
  1106.                 break;
  1107.         }
  1108.         try{
  1109.             $message = (new \Swift_Message())
  1110.                 ->setContentType('text/html')
  1111.                 ->setFrom($session->get('emailNoReply'))
  1112.                 ->setTo($setTo)
  1113.                 ->setBcc($bccMails)
  1114.                 ->setSubject($subjectPrefix $setSubject)
  1115.                 ->setBody($this->renderView($urlResume$responsePaymentOutput));
  1116.             $mailer->send($message);
  1117.         }catch(\Exception $e){
  1118.             return false;
  1119.         }
  1120.         return true;
  1121.     }
  1122.     public function getParamsInRequest(Request $fullRequest, array $searchParam): array {
  1123.         $optionalArray = [];
  1124.         foreach ($searchParam as $param) {
  1125.             if ($fullRequest->query->has($param)) {
  1126.                 $optionalArray[] = $param '=' $fullRequest->query->get($param);
  1127.             }
  1128.         }
  1129.         return $optionalArray;
  1130.     }
  1131.     private function array_to_xml($info, &$xml_info) {
  1132.         foreach ($info as $key => $value) {
  1133.             if (is_array($value)) {
  1134.                 if (!is_numeric($key)) {
  1135.                     if ('@attributes' == $key) {
  1136.                         foreach ($value as $attributeKey => $attribute) {
  1137.                             $xml_info->addAttribute($attributeKey$attribute);
  1138.                         }
  1139.                     } else {
  1140.                         foreach ($value as $key2 => $value2) {
  1141.                             if (!is_numeric($key2)) {
  1142.                                 $subnode $xml_info->addChild($key);
  1143.                                 $this->array_to_xml($value$subnode);
  1144.                                 break;
  1145.                             } else {
  1146.                                 if (!is_array($value2)) {
  1147.                                     $subnode $xml_info->addChild($key$value2);
  1148.                                 } else {
  1149.                                     $subnode $xml_info->addChild($key);
  1150.                                     $this->array_to_xml($value2$subnode);
  1151.                                 }
  1152.                             }
  1153.                         }
  1154.                     }
  1155.                 } else {
  1156.                     $subnode $xml_info->addChild('item'.$key);
  1157.                     $this->array_to_xml($value$subnode);
  1158.                 }
  1159.             } else {
  1160.                 $xml_info->addChild($keyhtmlspecialchars($value));
  1161.             }
  1162.         }
  1163.     }
  1164.     private function simpleXmlToArray($xml) {
  1165.         $json json_encode($xml);
  1166.         return json_decode($jsontrue);
  1167.     }
  1168.     public function getIINRanges($em) {
  1169.         $iinRecords $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findByActiveFranchises();
  1170.         $iinRecordsArray = [];
  1171.         $ccranges = [];
  1172.         $ccfranchises = [];
  1173.         foreach ($iinRecords as $key => $iinRecord) {
  1174.             $paymentGatewayCode $iinRecord["paymentgatewaycode"];
  1175.             $description $iinRecord["description"];
  1176.             $description strtoupper(str_replace(' '''trim($description)));
  1177.             $stringRanges $iinRecord["ranges"];
  1178.             $ranges json_decode($stringRangestrue);
  1179.             $stringLengths $iinRecord["lengths"];
  1180.             $lengths json_decode($stringLengthstrue);
  1181.             $luhn $iinRecord["luhn"];
  1182.             $cvvDigits $iinRecord["cvvdigits"];
  1183.             $tempLengths = [];
  1184.             foreach ($lengths["lengths"] as $length) {
  1185.                 $tempLengths[] = array(=> $length[0], => (isset($length[1]) ? $length[1] : $length[0]));
  1186.             }
  1187.             $tempRecordArrayFranchises = [];
  1188.             $tempRecordArrayFranchises["code"] = $paymentGatewayCode;
  1189.             $tempRecordArrayFranchises["codename"] = $description;
  1190.             $tempRecordArrayFranchises["luhn"] = $luhn;
  1191.             $tempRecordArrayFranchises["length"] = $tempLengths;
  1192.             $tempRecordArrayFranchises["cvvd"] = $cvvDigits;
  1193.             $ccfranchises[$paymentGatewayCode] = $tempRecordArrayFranchises;
  1194.             foreach ($ranges["ranges"] as $range) {
  1195.                 $tempRecordArrayRanges = [];
  1196.                 $tempRecordArrayRanges["range"][0] = $range[0];
  1197.                 $tempRecordArrayRanges["range"][1] = (isset($range[1]) ? $range[1] : $range[0]);
  1198.                 $tempRecordArrayRanges["minimum"] = strlen($range[0]);
  1199.                 $tempRecordArrayRanges["code"] = $paymentGatewayCode;
  1200.                 $ccranges[] = $tempRecordArrayRanges;
  1201.             }
  1202.         }
  1203.         $iinRecordsArray = array("ccranges" => $ccranges"ccfranchises" => $ccfranchises);
  1204.         return $iinRecordsArray;
  1205.     }
  1206. }