src/Aviatur/HotelBundle/Controller/HotelController.php line 4622

Open in your IDE?
  1. <?php
  2. namespace Aviatur\HotelBundle\Controller;
  3. use Aviatur\AgentBundle\Entity\AgentTransaction;
  4. use Aviatur\GeneralBundle\Services\AviaturRestService;
  5. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  7. use Aviatur\CustomerBundle\Models\CustomerModel;
  8. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  9. use Aviatur\GeneralBundle\Entity\Metatransaction;
  10. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  11. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  12. use Aviatur\HotelBundle\Models\HotelModel;
  13. use Aviatur\TwigBundle\Services\TwigFolder;
  14. use FOS\UserBundle\Model\UserInterface;
  15. use Doctrine\Persistence\ManagerRegistry;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\Cookie;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  22. use Symfony\Component\Routing\RouterInterface;
  23. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  24. use Aviatur\GeneralBundle\Services\PayoutExtraService;
  25. use Knp\Snappy\Pdf;
  26. use Aviatur\GeneralBundle\Services\AviaturPixeles;
  27. use Aviatur\GeneralBundle\Services\AviaturWebService;
  28. use Aviatur\GeneralBundle\Services\ExceptionLog;
  29. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  30. use Knp\Component\Pager\Paginator;
  31. use Knp\Component\Pager\PaginatorInterface;
  32. use Aviatur\MultiBundle\Services\MultiHotelDiscount;
  33. use Exception;
  34. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  35. use Symfony\Component\HttpFoundation\RedirectResponse;
  36. use Symfony\Component\Routing\Annotation\Route;
  37. use FOS\UserBundle\Security\LoginManager;
  38. use FOS\UserBundle\Security\LoginManagerInterface;
  39. use Aviatur\GeneralBundle\Services\AviaturUpdateBestprices;
  40. use Aviatur\HotelBundle\Services\SearchHotelCookie;
  41. use Aviatur\GeneralBundle\Services\AviaturMailer;
  42. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  43. use Aviatur\PaymentBundle\Services\TokenizerService;
  44. use Aviatur\GeneralBundle\Services\CouponDiscountService;
  45. use Aviatur\GeneralBundle\Controller\OrderController;
  46. use Aviatur\PaymentBundle\Controller\P2PController;
  47. use Aviatur\PaymentBundle\Controller\WorldPayController;
  48. use Aviatur\PaymentBundle\Controller\PSEController;
  49. use Aviatur\HotelBundle\Services\ConfirmationWebservice;
  50. use Aviatur\PaymentBundle\Controller\CashController;
  51. use Aviatur\PaymentBundle\Controller\SafetypayController;
  52. use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
  53. use Aviatur\GeneralBundle\Services\AviaturXsltRender;
  54. use Aviatur\MultiBundle\Services\MultiCustomUtils;
  55. class HotelController extends AbstractController
  56. {
  57.     /**
  58.      * @var \Doctrine\Persistence\ObjectManager
  59.      */
  60.     protected $managerRegistry;
  61.     /**
  62.      * @var SessionInterface
  63.      */
  64.     protected $session;
  65.     protected $agency;
  66.     private $multiCustomUtils;
  67.     private $aviaturRestService;
  68.     public function __construct(ManagerRegistry $registrySessionInterface $sessionMultiCustomUtils $multiCustomUtilsAviaturRestService $aviaturRestService) {
  69.         $this->managerRegistry $registry->getManager();
  70.         $this->session $session;
  71.         $this->agency $this->managerRegistry->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  72.         $this->multiCustomUtils $multiCustomUtils;
  73.         $this->aviaturRestService $aviaturRestService;
  74.     }
  75.     public function searchAction()
  76.     {
  77.         return $this->redirect($this->generateUrl('aviatur_search_hotels',[]));
  78.     }
  79.     /**
  80.      * Metodo encargado de consultar la disponibilidad hotelera, pendiente de conectar con el Qs
  81.      * Instancia la clase hotel, obtiene el dummy de RQ de disponibilidad, Asigna el id del provedor de hoteles
  82.      * Envia al metodo encargado de la logica de consumo de los servicios.
  83.      *
  84.      * @return type
  85.      */
  86.     public function availabilityAction(
  87.         Request $fullRequest,
  88.         AuthorizationCheckerInterface $authorizationChecker,
  89.         SearchHotelCookie $hotelSearchCookie,
  90.         AviaturUpdateBestprices $updateBestPrices,
  91.         MultiHotelDiscount $multiHotelDiscount,
  92.         ExceptionLog $exceptionLog,
  93.         AviaturLogSave $aviaturLogSave,
  94.         AviaturErrorHandler $aviaturErrorHandler,
  95.         ManagerRegistry $registry,
  96.         TwigFolder $twigFolder,
  97.         AviaturPixeles $aviaturPixeles,
  98.         AviaturWebService $aviaturWebService,
  99.         ParameterBagInterface $parameterBag,
  100.         $rooms,
  101.         $destination,
  102.         $date1,
  103.         $date2,
  104.         $adult1,
  105.         $child1 null,
  106.         $adult2 null,
  107.         $child2 null,
  108.         $adult3 null,
  109.         $child3 null
  110.     )
  111.     {
  112.         $urlDescription = [];
  113.         $providers = [];
  114.         $roomRate null;
  115.         $em $this->managerRegistry;
  116.         $session $this->session;
  117.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  118.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
  119.         $agency $this->agency;
  120.         $isFront $session->has('operatorId');
  121.         $isMulti strpos($fullRequest->server->get('HTTP_REFERER'), 'multi') ? true false;
  122.         if ($session->has('notEnableHotelSearch')) {
  123.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/''Busqueda de resultados''No podemos realizar la consulta ya que no existe un proveedor configurado para este servicio'));
  124.         }
  125.         $dateIn strtotime($date1);
  126.         $dateOut strtotime($date2);
  127.         $now strtotime('today');
  128.         if (($dateIn <= $now) || ($dateIn >= $dateOut)) {
  129.             $redirectText 'Hemos detectado una inconsistencia en tu consulta, esta es nuestra recomendación';
  130.             if ($dateIn == $now) {
  131.                 $dateOut date('Y-m-d'strtotime($date2.'+1 day'));
  132.                 $redirectText 'Para poder efectuar su reserva en línea, requiere mínimo 24h de anticipación a la fecha de ingreso.';
  133.             } else {
  134.                 $dateOut $dateIn $now date('Y-m-d'strtotime('+8 day')) : date('Y-m-d'strtotime($date1.'+8 day'));
  135.             }
  136.             $dateIn $dateIn <= $now date('Y-m-d'strtotime('+1 day')) : date('Y-m-d'$dateIn);
  137.             $data = ['destination' => $destination,
  138.                 'date1' => $dateIn,
  139.                 'date2' => $dateOut,
  140.                 'adult1' => $adult1,
  141.                 'child1' => $child1, ];
  142.             $redirectRoute 'aviatur_hotel_1';
  143.             if ($adult3) {
  144.                 $redirectRoute 'aviatur_hotel_3';
  145.                 $data['adult3'] = $adult3;
  146.                 $data['child3'] = $child3;
  147.                 $data['adult2'] = $adult2;
  148.                 $data['child2'] = $child2;
  149.             } elseif ($adult2) {
  150.                 $redirectRoute 'aviatur_hotel_2';
  151.                 $data['adult2'] = $adult2;
  152.                 $data['child2'] = $child2;
  153.             }
  154.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl($redirectRoute$data), 'Recomendación Automática'$redirectText));
  155.         }
  156.         $AvailabilityArray = [
  157.             'StartDate' => $date1,
  158.             'EndDate' => $date2,
  159.             'Rooms' => $rooms,
  160.             'Destination' => $destination,
  161.             'Nights' => floor(($dateOut $dateIn) / (24 60 60)),
  162.         ];
  163.         $services = [];
  164.         $countAdults 0;
  165.         $countChildren 0;
  166.         $childAgesCookie 0;
  167.         for ($i 1$i <= $rooms; ++$i) {
  168.             ${'countAdults'.$i} = 0;
  169.             ${'countChildren'.$i} = 0;
  170.             $childrens = [];
  171.             if ('n' != ${'child'.$i}) {
  172.                 ${'child'.$i.'Ages'} = explode('-', ${'child'.$i});
  173.                 if (== $i) {
  174.                     $childAgesCookie = [
  175.                         'age'.$i => ${'child'.$i.'Ages'},
  176.                     ];
  177.                 }
  178.                 ${'child'.$i.'Size'} = is_countable(${'child'.$i.'Ages'}) ? count(${'child'.$i.'Ages'}) : 0;
  179.                 foreach (${'child'.$i.'Ages'} as $age) {
  180.                     $childrens[] = $age;
  181.                     ++${'countChildren'.$i};
  182.                     ++$countChildren;
  183.                 }
  184.             }
  185.             $countAdults $countAdults + ${'adult'.$i};
  186.             $services[] = ['adults' => ${'adult'.$i}, 'childrens' => $childrens];
  187.             $AvailabilityArray[$i] = [];
  188.             $AvailabilityArray[$i]['Children'] = ${'countChildren'.$i};
  189.             $AvailabilityArray[$i]['Adults'] = ${'adult'.$i};
  190.         }
  191.         $AvailabilityArray['Children'] = $countChildren;
  192.         $AvailabilityArray['Adults'] = $countAdults;
  193.         $destinationObject $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination);
  194.         if (null != $destinationObject) {
  195.             $AvailabilityArray['cityName'] = $destinationObject->getCity();
  196.             $AvailabilityArray['countryCode'] = $destinationObject->getCountrycode();
  197.         } else {
  198.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Error en la consulta''La ciudad ingresada no es válida'));
  199.         }
  200.         $session->remove('AvailabilityArrayhotel');
  201.         $session->set('AvailabilityArrayhotel'$AvailabilityArray);
  202.         $domain $fullRequest->getHost();
  203.         $requestMultiHotelDiscountInfo false;
  204.         $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
  205.         $urlDescription['url'] = null != $seoUrl '/'.$seoUrl[0]->getUrl() : $requestUrl;
  206.         $pixelInfo = []; //THIS IS INTENDED FOR STORING ALL DATA CLASIFIED BY PIXEL.
  207.         if ($fullRequest->isXmlHttpRequest()) {
  208.             $session->remove($session->get($transactionIdSessionName).'[hotel][availability_file]');
  209.             if ($destinationObject) {
  210.                 $currency 'COP';
  211.                 $configsHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
  212.                 if ($configsHotelAgency) {
  213.                     foreach ($configsHotelAgency as $configHotelAgency) {
  214.                         $providers[] = $configHotelAgency->getProvider()->getProvideridentifier();
  215.                         if (strpos($configHotelAgency->getProvider()->getName(), '-USD')) {
  216.                             $currency 'USD';
  217.                         }
  218.                     }
  219.                 } else {
  220.                     $exceptionLog->log('Error Fatal''No se encontró la agencia segun el dominio: '.$domainnullfalse);
  221.                     return new Response('no se encontró agencias para consultar disponibilidad.');
  222.                 }
  223.                 $hotelModel = new HotelModel();
  224.                 $xmlTemplate $hotelModel->getXmlAvailability();
  225.                 $xmlRequest $xmlTemplate[0];
  226.                 $provider implode(';'$providers);
  227.                 $requestLanguage mb_strtoupper($fullRequest->getLocale());
  228.                 //$MoreDataEchoToken = $isMulti ? 'MoreDataEchoToken="P"' : '';
  229.                 $MoreDataEchoToken 'MoreDataEchoToken="P"';
  230.                 $variable = [
  231.                     'ProviderId' => $provider,
  232.                     'date1' => $date1,
  233.                     'date2' => $date2,
  234.                     'destination' => $destination,
  235.                     'country' => $destinationObject->getCountrycode(),
  236.                     'language' => $requestLanguage,
  237.                     'currency' => $currency,
  238.                     'userIp' => $fullRequest->getClientIp(),
  239.                     'userAgent' => $fullRequest->headers->get('User-Agent'),
  240.                 ];
  241.                 $i 1;
  242.                 foreach ($services as $room) {
  243.                     $xmlRequest .= str_replace('templateAdults''adults_'.$i$xmlTemplate[1]);
  244.                     $j 1;
  245.                     foreach ($room['childrens'] as $child) {
  246.                         $xmlRequest .= str_replace('templateChild''child_'.$i.'_'.$j$xmlTemplate[2]);
  247.                         $variable['child_'.$i.'_'.$j] = $child;
  248.                         ++$j;
  249.                     }
  250.                     $variable['adults_'.$i] = $room['adults'];
  251.                     $xmlRequest .= $xmlTemplate[3];
  252.                     ++$i;
  253.                 }
  254.                 $xmlRequest .= $xmlTemplate[4];
  255.                 $xmlRequest str_replace('{moreDataEchoToken}'$MoreDataEchoToken$xmlRequest);
  256.                 $makeLogin true;
  257.                 if ($fullRequest->query->has('transactionMulti')) {
  258.                     $transactionId base64_decode($fullRequest->query->get('transactionMulti'));
  259.                     $session->set($transactionIdSessionName$transactionId);
  260.                     $makeLogin false;
  261.                     $requestMultiHotelDiscountInfo true;
  262.                 }
  263.                 if ($session->get($session->get($transactionIdSessionName).'[crossed]'.'[url-hotel]')) {
  264.                     $makeLogin false;
  265.                 }
  266.                 if ($makeLogin) {
  267.                     $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  268.                     if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  269.                         $aviaturErrorHandler->errorRedirect('''Error MPA''No se creo Login!');
  270.                         // return new Response('Estamos experimentando dificultades técnicas en este momento.');
  271.                         return (new JsonResponse())->setData([
  272.                                     'error' => true,
  273.                                     'message' => 'Estamos experimentando dificultades técnicas en este momento.',
  274.                         ]);
  275.                     }
  276.                     $transactionId = (string) $transactionIdResponse;
  277.                     $session->set($transactionIdSessionName$transactionId);
  278.                 }
  279.                 $variable['transactionId'] = $transactionId;
  280.                 $preResponse $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  281.                 if (isset($preResponse['error'])) {
  282.                     if (false === strpos($preResponse['error'], '66002')) {
  283.                         $aviaturErrorHandler->errorRedirect($requestUrl'Error disponibilidad hoteles'$preResponse['error']);
  284.                     }
  285.                     $preResponse $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  286.                     if (isset($preResponse['error'])) {
  287.                         if (false === strpos($preResponse['error'], '66002')) {
  288.                             $aviaturErrorHandler->errorRedirect($requestUrl'Error disponibilidad hoteles'$preResponse['error']);
  289.                         }
  290.                         return new Response($preResponse['error']);
  291.                     }
  292.                 } elseif (empty((array) $preResponse->Message)) {
  293.                     $aviaturErrorHandler->errorRedirect($requestUrl'Error disponibilidad hoteles'$preResponse->Message);
  294.                     return new Response('No hemos encontrado información para el destino solicitado.');
  295.                 }
  296.                 $searchImages = ['hotelbeds.com/giata/small''/100x100/''_tn.jpg''&lt;p&gt;&lt;b&gt;Ubicaci&#xF3;n del establecimiento&lt;/b&gt; &lt;br /&gt;'];
  297.                 $replaceImages = ['hotelbeds.com/giata''/200x200/''.jpg'''];
  298.                 $response simplexml_load_string(str_replace($searchImages$replaceImages$preResponse->asXML()));
  299.                 $response->Message->OTA_HotelAvailRS['StartDate'] = $date1;
  300.                 $response->Message->OTA_HotelAvailRS['EndDate'] = $date2;
  301.                 $response->Message->OTA_HotelAvailRS['Country'] = $variable['country'];
  302.                 $configHotelAgencyIds = [];
  303.                 foreach ($configsHotelAgency as $configHotelAgency) {
  304.                     $configHotelAgencyIds[] = $configHotelAgency->getId();
  305.                     $providerOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getProvider()->getProvideridentifier();
  306.                     $providerNames[$configHotelAgency->getId()] = $configHotelAgency->getProvider()->getName();
  307.                     $typeOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getType();
  308.                 }
  309.                 $markups $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->getMarkups($configHotelAgencyIds$destinationObject->getId());
  310.                 $parametersJson $session->get($domain.'[parameters]');
  311.                 $parameters json_decode($parametersJson);
  312.                 $tax = (float) $parameters->aviatur_payment_iva;
  313.                 if (property_exists($response->Message->OTA_HotelAvailRS->RoomStays'RoomStay')) {
  314.                     $currencyCode = (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
  315.                 } else {
  316.                     return new Response('Error no hay hoteles disponibles para esta fecha.');
  317.                 }
  318.                 if ('COP' != $currencyCode && 'COP' == $currency) {
  319.                     $trm $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
  320.                     $trm $trm[0]['value'];
  321.                 } else {
  322.                     $trm 1;
  323.                 }
  324.                 $key 0;
  325.                 $searchHotelCodes = ['|''/'];
  326.                 $replaceHotelCodes = ['--''---'];
  327.                 //load discount info if applicable
  328.                 $multiHotelDiscountInfo null;
  329.                 if ($requestMultiHotelDiscountInfo) {
  330.                     $transactionId $session->get($transactionIdSessionName.'Multi');
  331.                     $multiHotelDiscountInfo $multiHotelDiscount->getAvailabilityDiscountsInfo($transactionId, [$dateIn$dateOut], $destinationObject$agency);
  332.                 }
  333.                 //$aviaturLogSave->logSave(print_r($session, true), 'Bpcs', 'availSession');
  334.                 $homologationObjects $em->getRepository(\Aviatur\HotelBundle\Entity\HotelHomologation::class)->findBySearchCities([$destinationObjectnull]);
  335.                 $hotelHomologationArray = [];
  336.                 foreach ($homologationObjects as $homologationObject) {
  337.                     foreach (json_decode($homologationObject->getHotelcodes()) as $hotelCode) {
  338.                         $hotelHomologationArray[$hotelCode] = $homologationObject->getPreferredcode();
  339.                     }
  340.                 }
  341.                 $options = [];
  342.                 $isAgent false;
  343.                 foreach ($response->Message->OTA_HotelAvailRS->RoomStays->RoomStay as $roomStay) {
  344.                     $roomStay['Show'] = '1';
  345.                     $hotelIdentifier = (string) $roomStay->TPA_Extensions->HotelInfo->providerID.'-'.(string) $roomStay->BasicPropertyInfo['HotelCode'];
  346.                     if (array_key_exists($hotelIdentifier$hotelHomologationArray) && ($hotelHomologationArray[$hotelIdentifier] != $hotelIdentifier)) {
  347.                         $roomStay['Show'] = '0';
  348.                     } else {
  349.                         $roomStay->BasicPropertyInfo['HotelCode'] = str_replace($searchHotelCodes$replaceHotelCodes, (string) $roomStay->BasicPropertyInfo['HotelCode']);
  350.                         $hotelCode $roomStay->BasicPropertyInfo['HotelCode'];
  351.                         $hotelEntity $em->getRepository(\Aviatur\HotelBundle\Entity\Hotel::class)->findOneByCodhotel($hotelCode);
  352.                         $hotel null != $hotelEntity $hotelEntity->getId() : null;
  353.                         $roomRate $roomStay->RoomRates->RoomRate;
  354.                         $i 0;
  355.                         $markup false;
  356.                         while (!$markup) {
  357.                             if (($markups[$i]['hotel_id'] == $hotel || null == $markups[$i]['hotel_id']) && ($providerOfConfig[$markups[$i]['config_hotel_agency_id']] == (string) $roomStay->TPA_Extensions->HotelInfo->providerID)) {
  358.                                 // if ($hotelEntity != null) {
  359.                                 //     $markups[$i]['value'] = $hotelEntity->getMarkupValue();
  360.                                 // }
  361.                                 if ('N' == $typeOfConfig[$markups[$i]['config_hotel_agency_id']]) {
  362.                                     $aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markups[$i]['value'] / (100 $markups[$i]['value']);
  363.                                 } else {
  364.                                     $aviaturMarkup 0;
  365.                                 }
  366.                                 $roomStay->TPA_Extensions->HotelInfo->providerName $providerNames[$markups[$i]['config_hotel_agency_id']];
  367.                                 $roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
  368.                                 if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
  369.                                     $roomRate->Total['AmountAviaturMarkupTax'] = 0;
  370.                                 } else {
  371.                                     $roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup $tax;
  372.                                 }
  373.                                 $roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
  374.                                 $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round(((float) $aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
  375.                                 if ('COP' == $currencyCode) {
  376.                                     $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
  377.                                 }
  378.                                 if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
  379.                                     $roomRate->TotalAviatur['AmountTax'] = 0;
  380.                                 } else {
  381.                                     $roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
  382.                                 }
  383.                                 $roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
  384.                                 $roomRate->TotalAviatur['CurrencyCode'] = $currency;
  385.                                 $roomRate->TotalAviatur['Markup'] = $markups[$i]['value'];
  386.                                 $roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markups[$i]['id'];
  387.                                 $roomRate->TotalAviatur['MarkupId'] = $markups[$i]['id'];
  388.                                 $nameProduct 'hotel';
  389.                                 $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  390.                                 $session->set($transactionId.'_isActiveQse', ((is_countable($productCommission) ? count($productCommission) : 0) > 0) ? true false);
  391.                                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING') && $session->get($transactionId.'_isActiveQse')) {
  392.                                     $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  393.                                     // if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
  394.                                     if (!empty($agent)) {
  395.                                         $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
  396.                                         $infoQse json_decode($agentCommission->getQseproduct());
  397.                                         // TODO: uncomment
  398.                                         // $infoQse = (empty($infoQse)) ? false : (empty($infoQse->$nameProduct)) ? false : $infoQse->$nameProduct;
  399.                                         $productCommissionPercentage $productCommission->getQsecommissionpercentage();
  400.                                         $hotelCommission = ($infoQse) ? (int) $infoQse->hotel->commission_money 0;
  401.                                         $commissionActive = ($infoQse) ? (int) $infoQse->hotel->active 0;
  402.                                         $commissionPercentage = ($infoQse) ? (float) $infoQse->hotel->commission_percentage 0;
  403.                                         $activeDetail $agentCommission->getActivedetail();
  404.                                         /*                                         * ***************** Commision Qse Agent ******************* */
  405.                                         $roomRate->TypeHotel['type'] = $typeOfConfig[$markups[$i]['config_hotel_agency_id']];
  406.                                         $nightsCommission floor(($dateOut $dateIn) / (24 60 60));
  407.                                         $roomRate->TotalAviatur['CommissionActive'] = $commissionActive;
  408.                                         if ('0' == $commissionActive) {
  409.                                             $roomRate->TotalAviatur['AgentComission'] = round($hotelCommission);
  410.                                         } elseif ('1' == $commissionActive) {
  411.                                             $roomRate->TotalAviatur['AgentComission'] = round(($roomRate->Total['AmountIncludingMarkup'] * $commissionPercentage) * $nightsCommission);
  412.                                         }
  413.                                         $roomRate->TotalAviatur['CommissionPay'] = round(($roomRate->TotalAviatur['AgentComission'] / 1.19) * $productCommissionPercentage);
  414.                                         $roomRate->TotalAviatur['TotalCommissionFare'] = round($roomRate->Total['AmountAviaturMarkup']);
  415.                                         if ('P' == $typeOfConfig[$markups[$i]['config_hotel_agency_id']]) {
  416.                                             $commissionFare round($roomRate->Total['AmountIncludingMarkup'] * ($markups[$i]['value'] / 100));
  417.                                             $roomRate->TotalAviatur['TotalCommissionFare'] = $commissionFare;
  418.                                             $roomRate->TotalAviatur['CommissionPay'] = round(((($roomRate->TotalAviatur['AgentComission'] + ($roomRate->TotalAviatur['TotalCommissionFare'] * $nightsCommission)) / 1.19) * $productCommissionPercentage));
  419.                                         }
  420.                                         $roomRate->TotalAviatur['activeDetail'] = $activeDetail;
  421.                                         $isAgent true;
  422.                                     } else {
  423.                                         $session->set($transactionId.'_isActiveQse'false);
  424.                                     }
  425.                                 }
  426.                                 if (false == $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) {
  427.                                     $roomRate->TotalAviatur['submitBuy'] = '1';
  428.                                 }
  429.                                 if ($multiHotelDiscountInfo) {
  430.                                     $roomRateDiscount $multiHotelDiscount->setAvailabilityDiscount($roomRate$multiHotelDiscountInfo, (string) $roomStay->TPA_Extensions->HotelInfo->providerID);
  431.                                     $roomRate->TotalAviatur['hasDiscount'] = $roomRateDiscount true false;
  432.                                     $roomRate->TotalAviatur['DiscountTotal'] = $roomRateDiscount $roomRateDiscount->discountTotal 0;
  433.                                     $roomRate->TotalAviatur['DiscountAmount'] = $roomRateDiscount $roomRateDiscount->discountAmount 0;
  434.                                 } else {
  435.                                     $requestMultiHotelDiscountInfo false;
  436.                                 }
  437.                                 $markup true;
  438.                             }
  439.                             ++$i;
  440.                         }
  441.                         $options[$key]['amount'] = (float) $roomStay->RoomRates->RoomRate->TotalAviatur['AmountTotal'];
  442.                         $options[$key]['provider'] = (int) $roomStay->TPA_Extensions->HotelInfo->providerID;
  443.                         $options[$key]['HotelName'] = (string) $roomStay->BasicPropertyInfo['HotelName'];
  444.                         $options[$key]['xml'] = $roomStay->asXml();
  445.                         ++$key;
  446.                     }
  447.                 }
  448.                 $roomRate->TotalAviatur['isAgent'] = $isAgent;
  449.                 if (!= sizeof($options)) {
  450.                     usort($options, fn($a$b) => $a['amount'] - $b['amount']);
  451.                     $tempOptions = [[], []];
  452.                     $providerMPT = [5866]; // hoteles propios produccion / pruebas
  453.                     if ($isFront) {
  454.                         foreach ($options as $option) {
  455.                             if (in_array($option['provider'], $providerMPT)) {
  456.                                 $tempOptions[0][] = $option;
  457.                             } else {
  458.                                 $tempOptions[1][] = $option;
  459.                             }
  460.                         }
  461.                         $options = [...$tempOptions[0], ...$tempOptions[1]];
  462.                     } else {
  463.                         foreach ($options as $option) {
  464.                             if (in_array($option['provider'], $providerMPT) && false !== strpos(strtolower($option['HotelName']), 'las islas')) {
  465.                                 $tempOptions[0][] = $option;
  466.                             } else {
  467.                                 $tempOptions[1][] = $option;
  468.                             }
  469.                         }
  470.                         $options = [...$tempOptions[0], ...$tempOptions[1]];
  471.                     }
  472.                     $responseXml explode('<RoomStay>'str_replace(['</RoomStay>''<RoomStay InfoSource="B2C" Show="1">''<RoomStay InfoSource="B2C" Show="0">''<RoomStay InfoSource="B2B" Show="1">''<RoomStay InfoSource="B2B" Show="0">'], '<RoomStay>'$response->asXml()));
  473.                     $orderedResponse $responseXml[0];
  474.                     foreach ($options as $option) {
  475.                         $orderedResponse .= $option['xml'];
  476.                     }
  477.                     $orderedResponse .= $responseXml[sizeof($responseXml) - 1];
  478.                     $response simplexml_load_string($orderedResponse);
  479.                     $fileName $aviaturLogSave->logSave($orderedResponse'HotelAvailResponse''RS');
  480.                     $session->set($session->get($transactionIdSessionName).'[hotel][availability_file]'$fileName);
  481.                     $agencyFolder $twigFolder->twigFlux();
  482.                     $HotelBestPrice[0] = ['price' => (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay[0]->RoomRates->RoomRate->TotalAviatur['AmountTotal'][0], 'accomodationNumber' => (string) count($response->Message->OTA_HotelAvailRS->RoomStays->RoomStay)];
  483.                     //$HotelBestPrice = (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay[0]->RoomRates->RoomRate->TotalAviatur['AmountTotal'][0];
  484.                     $session->set($session->get($transactionIdSessionName).'[hotel][HotelBestPrice]'$HotelBestPrice);
  485.                     $updateBestPrices->add((object) $HotelBestPrice$requestUrl); //Always send array or object, as price list
  486.                     $renderTwig $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/AjaxAvailability.html.twig');
  487.                     // Prueba de llamado a Geocoding Api solo para 3.4519988, -76.5325259
  488.                     $geocodingResponseApi $this->aviaturRestService->getPlaceByCoordinates('3.4519988''-76.5325259''d4ea2db24f6448dcbb1551c3546851d6');
  489.                     $resultsGeocoding = [];
  490.                     if (isset($geocodingResponseApi->status) && $geocodingResponseApi->status->code === 200) {
  491.                         $resultsGeocoding $geocodingResponseApi->results;
  492.                     }
  493.                     return $this->render($renderTwig , [
  494.                                 'hotels' => $response->Message->OTA_HotelAvailRS,
  495.                                 'AvailabilityHasDiscount' => $requestMultiHotelDiscountInfo,
  496.                                 'urlDescription' => $urlDescription,
  497.                                 'HotelMinPrice' => $HotelBestPrice[0]['price'],
  498.                                 'isMulti' => $isMulti,
  499.                                 'resultsGeocoding' => $resultsGeocoding
  500.                     ]);
  501.                 } else {
  502.                     return new Response('No hay hoteles disponibles para pago en línea en este destino actualmente.');
  503.                 }
  504.             } else {
  505.                 $exceptionLog->log(
  506.                     'Error Fatal',
  507.                     'La ciudad de destino no se pudo encontrar en la base de datos, iata: '.$destination,
  508.                     null,
  509.                     false
  510.                 );
  511.                 return new Response('La ciudad de destino no se pudo encontrar en la base de datos');
  512.             }
  513.         } else {
  514.             $cookieArray = [
  515.                 'destination' => $destination,
  516.                 'destinationLabel' => $destinationObject->getCity().', '.$destinationObject->getCountry().' ('.$destination.')',
  517.                 'adults' => $AvailabilityArray['1']['Adults'],
  518.                 'children' => $AvailabilityArray['1']['Children'],
  519.                 'childAge' => $childAgesCookie,
  520.                 'date1' => date('Y-m-d\TH:i:s'$dateIn),
  521.                 'date2' => date('Y-m-d\TH:i:s'$dateOut),
  522.             ];
  523.             $agencyFolder $twigFolder->twigFlux();
  524.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/availability.html.twig');
  525.             if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
  526.                 $safeUrl 'https://'.$agency->getDomain();
  527.             } else {
  528.                 $safeUrl 'https://'.$agency->getDomainsecure();
  529.             }
  530.             $cookieLastSearch $hotelSearchCookie->searchHotelCookie(['hotel' => base64_encode(json_encode($cookieArray))]);
  531.             if (!$isFront) {
  532.                 // PIXELES INFORMATION
  533.                 $pixel['partner_datalayer'] = [
  534.                     'enabled' => true,
  535.                     'event' => 'hotel_search',
  536.                     'dimension1' => $destination,
  537.                     'dimension2' => '',
  538.                     'dimension3' => $date1,
  539.                     'dimension4' => $date2,
  540.                     'dimension5' => 'Hotel',
  541.                     'dimension6' => '',
  542.                     'dimension7' => '',
  543.                     'dimension8' => '',
  544.                     'dimension9' => '',
  545.                     'dimension10' => ((int) $adult1 + (int) $child1 + (int) $adult2 + (int) $child2 + (int) $adult3 + (int) $child3),
  546.                     'dimension11' => $rooms,
  547.                     'dimension12' => 'Busqueda-Hotel',
  548.                     'ecommerce' => [
  549.                         'currencyCode' => 'COP',
  550.                     ],
  551.                 ];
  552.                 //$pixel['dataxpand'] = true;
  553.                 $pixelInfo $aviaturPixeles->verifyPixeles($pixel'hotel''availability'$agency->getAssetsFolder(), false);
  554.             }
  555.             $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  556.             if (null != $pointRedemption) {
  557.                 $points 0;
  558.                 if ($fullRequest->request->has('pointRedemptionValue')) {
  559.                     $points $fullRequest->request->get('pointRedemptionValue');
  560.                     $session->set('point_redemption_value'$points);
  561.                 } elseif ($fullRequest->query->has('pointRedeem')) {
  562.                     $points $fullRequest->query->get('pointRedeem');
  563.                     $session->set('point_redemption_value'$points);
  564.                 } elseif ($session->has('point_redemption_value')) {
  565.                     $points $session->get('point_redemption_value');
  566.                 }
  567.                 $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  568.             }
  569.             $response $this->render($urlAvailability, [
  570.                 'ajaxUrl' => $requestUrl,
  571.                 'availableArrayHotel' => $AvailabilityArray,
  572.                 'inlineEngine' => true,
  573.                 'safeUrl' => $safeUrl,
  574.                 'cookieLastSearch' => $cookieLastSearch,
  575.                 'cityName' => $destinationObject->getCity(),
  576.                 'date1' => date('c'$dateIn),
  577.                 'date2' => date('c'$dateOut),
  578.                 'availabilityHasDiscount' => $requestMultiHotelDiscountInfo,
  579.                 'urlDescription' => $urlDescription,
  580.                 'pointRedemption' => $pointRedemption,
  581.                 'pixel_info' => $pixelInfo,
  582.             ]);
  583.             $response->headers->setCookie(new Cookie('_availability_array[hotel]'base64_encode(json_encode($cookieArray)), (time() + 3600 24 7), '/'));
  584.             return $response;
  585.         }
  586.     }
  587.     public function getAvailabilityResultsAction(TwigFolder $twigFolderSessionInterface $sessionParameterBagInterface $parameterBag)
  588.     {
  589.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  590.         if ($session->has($transactionIdSessionName)) {
  591.             $transactionId $session->get($transactionIdSessionName);
  592.             if (true === $session->has($transactionId.'[hotel][availability_file]')) {
  593.                 $availFile $session->get($transactionId.'[hotel][availability_file]');
  594.                 $response = \simplexml_load_file($availFile);
  595.                 $agencyFolder $twigFolder->twigFlux();
  596.                 return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/AjaxAvailability.html.twig'), ['hotels' => $response->Message->OTA_HotelAvailRS]);
  597.             } else {
  598.                 if ($session->has($transactionId.'[hotel][availability_results_retry]')) {
  599.                     $retry $session->get($transactionId.'[hotel][availability_results_retry]');
  600.                     if ($retry 8) {
  601.                         $session->set($transactionId.'[hotel][availability_results_retry]'$retry 1);
  602.                         return new Response('retry');
  603.                     } else {
  604.                         return new Response('error');
  605.                     }
  606.                 } else {
  607.                     $session->set($transactionId.'[hotel][availability_results_retry]'1);
  608.                     return new Response('retry');
  609.                 }
  610.             }
  611.         } else {
  612.             return new Response('error');
  613.         }
  614.     }
  615.     public function availabilitySeoAction(Request $requestRouterInterface $router$url)
  616.     {
  617.         $session $this->session;
  618.         $em $this->managerRegistry;
  619.         $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findOneByUrl('hoteles/'.$url);
  620.         if (null != $seoUrl) {
  621.             $maskedUrl $seoUrl->getMaskedurl();
  622.             $session->set('maxResults'$request->query->get('maxResults'));
  623.             if (false !== strpos($maskedUrl'?')) {
  624.                 $parameters explode('&'substr($maskedUrlstrpos($maskedUrl'?') + 1));
  625.                 foreach ($parameters as $parameter) {
  626.                     $sessionInfo explode('='$parameter);
  627.                     if (== sizeof($sessionInfo)) {
  628.                         $session->set($sessionInfo[0], $sessionInfo[1]);
  629.                     }
  630.                 }
  631.                 $maskedUrl substr($maskedUrl0strpos($maskedUrl'?'));
  632.             }
  633.             if (null != $seoUrl) {
  634.                 $route $router->match($maskedUrl);
  635.                 $route['_route_params'] = [];
  636.                 foreach ($route as $param => $val) {
  637.                     // set route params without defaults
  638.                     if ('_' !== \substr($param01)) {
  639.                         $route['_route_params'][$param] = $val;
  640.                     }
  641.                 }
  642.                 return $this->forward($route['_controller'], $route);
  643.             } else {
  644.                 throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
  645.             }
  646.         } else {
  647.             throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
  648.         }
  649.     }
  650.     public function detailAction(Request $fullRequest, \Swift_Mailer $mailerCouponDiscountService $aviaturCouponDiscountCustomerMethodPaymentService $customerMethodPaymentTokenStorageInterface $tokenStorageMultiHotelDiscount $multiHotelDiscountAviaturWebService $aviaturWebServiceAviaturPixeles $aviaturPixelesPayoutExtraService $payoutExtraServiceAuthorizationCheckerInterface $authorizationCheckerAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerTwigFolder $twigFolderParameterBagInterface $parameterBagLoginManagerInterface $loginManagerInterface)
  651.     {
  652.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  653.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  654.         $response = [];
  655.         $transactionId null;
  656.         $passangerTypes = [];
  657.         $flux null;
  658.         $provider null;
  659.         $responseHotelDetail = [];
  660.         $guestsInfo null;
  661.         $fullPricing = [];
  662.         $pixel = [];
  663.         $em $this->managerRegistry;
  664.         $session $this->session;
  665.         $agency $this->agency;
  666.         $request $fullRequest->request;
  667.         $server $fullRequest->server;
  668.         $domain $fullRequest->getHost();
  669.         $route $router->match(str_replace($fullRequest->getSchemeAndHttpHost(), ''$fullRequest->getUri()));
  670.         $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  671.         $isFront $session->has('operatorId');
  672.         $detailHasDiscount false;
  673.         $detailHasCoupon false;
  674.         $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  675.         $isAgent false;
  676.         if (true === $request->has('referer')) {
  677.             $returnUrl $request->get('http_referer');
  678.         }
  679.         if (true === $request->has('whitemarkDataInfo')) {
  680.             $session->set('whitemarkDataInfo'json_decode($request->get('whitemarkDataInfo'), true));
  681.         }
  682.         if (true === $request->has('userLogin') && '' != $request->get('userLogin') && null != $request->get('userLogin')) {
  683.             $user $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($request->get('userLogin'));
  684.             $this->authenticateUser($user$loginManagerInterface);
  685.         }
  686.         if (true === $request->has('transactionID')) {
  687.             $transactionId $request->get('transactionID');
  688.             if ($fullRequest->request->has('kayakclickid') || $fullRequest->query->has('kayakclickid')) {
  689.                 $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/');
  690.                 if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  691.                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl'Ha ocurrido un error en la validación''No se creo Login'));
  692.                 }
  693.                 $transactionId = (string) $transactionIdResponse;
  694.             }
  695.             //Validación para agregar el referer en los hoteles (Temporal)
  696.             if (true === $request->has('referer')) {
  697.                 $referer $request->get('referer');
  698.                 $metasearch $em->getRepository(\Aviatur\GeneralBundle\Entity\Metasearch::class)->findOneByUrl($referer);
  699.                 if (null != $metasearch) {
  700.                     $transactionId $transactionId.'||'.$metasearch->getId();
  701.                 }
  702.             }
  703.             if (false !== strpos($transactionId'||')) {
  704.                 $explodedTransaction explode('||'$transactionId);
  705.                 $transactionId $explodedTransaction[0];
  706.                 $request->set('transactionID'$transactionId);
  707.                 $metaseachId $explodedTransaction[1];
  708.                 $session->set('generals[metasearch]'$metaseachId);
  709.                 $metatransaction $em->getRepository(\Aviatur\GeneralBundle\Entity\Metatransaction::class)->findOneByTransactionId($transactionId);
  710.                 if (null == $metatransaction) {
  711.                     $metasearch $em->getRepository(\Aviatur\GeneralBundle\Entity\Metasearch::class)->find($metaseachId);
  712.                     if (null == $metasearch) {
  713.                         $response['error'] = 'Por favor selecciona nuevamente tu itinerario de viaje';
  714.                         return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl'Ha ocurrido un error en la validación'$response['error']));
  715.                     }
  716.                     $metatransaction = new Metatransaction();
  717.                     $metatransaction->setTransactionId((string) $transactionId);
  718.                     $metatransaction->setDatetime(new \DateTime());
  719.                     $metatransaction->setIsactive(true);
  720.                     $metatransaction->setMetasearch($metasearch);
  721.                     $em->persist($metatransaction);
  722.                     $em->flush();
  723.                 }
  724.                 $d1 $metatransaction->getDatetime();
  725.                 $d2 = new \DateTime(date('Y-m-d H:i:s'time() - (15 60)));
  726.                 if (false == $metatransaction->getIsactive()) {
  727.                     $response['error'] = 'Por favor selecciona nuevamente tu itinerario de viaje';
  728.                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl''$response['error']));
  729.                 } elseif ($d1 $d2) {
  730.                     $response['error'] = 'Por favor selecciona nuevamente tu itinerario de viaje';
  731.                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl'Tu consulta fue realizada hace mas de 15 minutos'$response['error']));
  732.                 } else {
  733.                     $metatransaction->setIsactive(false);
  734.                     $em->persist($metatransaction);
  735.                     $em->flush();
  736.                 }
  737.             } else {
  738.                 $session->set($transactionIdSessionName$transactionId);
  739.             }
  740.         } elseif (true === $session->has($transactionIdSessionName)) {
  741.             $transactionId $session->get($transactionIdSessionName);
  742.         }
  743.         if (true === $session->has($transactionId.'[hotel][retry]')) {
  744.             $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  745.             // Parse XML Response stored  in Session
  746.             $response simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  747.             $detailHotelRaw $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay;
  748.             $dateIn strtotime((string) $response->Message->OTA_HotelRoomListRS['StartDate']);
  749.             $dateOut strtotime((string) $response->Message->OTA_HotelRoomListRS['EndDate']);
  750.             $postDataJson $session->get($transactionId.'[hotel][detail_data_hotel]');
  751.             $postDataInfo json_decode($postDataJson);
  752.             $passangerInfo $postDataInfo->PI;
  753.             $billingData $postDataInfo->BD;
  754.             $contactData $postDataInfo->CD;
  755.             $hotelInfo $postDataInfo->HI;
  756.             $paymentData = isset($postDataInfo->PD) ? $postDataInfo->PD '';
  757.             foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
  758.                 if ($roomRatePlan['RatePlanCode'] == $hotelInfo->ratePlan) {
  759.                     $roomRate[] = $roomRatePlan;
  760.                 }
  761.             }
  762.             if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  763.                 $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  764.             } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  765.                 $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  766.             } else {
  767.                 $urlAvailability $session->get($transactionId.'[availability_url]');
  768.             }
  769.             $routeParsed parse_url($urlAvailability);
  770.             $availabilityUrl $router->match($routeParsed['path']);
  771.             $rooms = [];
  772.             for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  773.                 $adult $availabilityUrl['adult'.$i];
  774.                 $child = [];
  775.                 if ('n' != $availabilityUrl['child'.$i]) {
  776.                     $child explode('-'$availabilityUrl['child'.$i]);
  777.                 }
  778.                 $rooms[$i] = ['adult' => $adult'child' => $child];
  779.             }
  780.             $detailHotel = [
  781.                 'dateIn' => $dateIn,
  782.                 'dateOut' => $dateOut,
  783.                 'roomInformation' => $rooms,
  784.                 'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
  785.                 'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
  786.                 'nights' => floor(($dateOut $dateIn) / (24 60 60)),
  787.                 'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
  788.                 'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
  789.                 'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'],
  790.                 'roomRates' => $roomRate,
  791.                 'timeSpan' => $detailHotelRaw->TimeSpan,
  792.                 'total' => $detailHotelRaw->Total,
  793.                 'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
  794.                 'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
  795.                 'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
  796.                 'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
  797.                 'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
  798.                 'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
  799.             ];
  800.             if (isset($response->Message->OTA_HotelRoomListRS['commissionPercentage'])) {
  801.                 $detailHotel['commissionPercentage'] = (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'];
  802.             }
  803.             $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  804.             $typeGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  805.             $repositoryDocumentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  806.             $queryDocumentType $repositoryDocumentType
  807.                     ->createQueryBuilder('p')
  808.                     ->where('p.paymentcode != :paymentcode')
  809.                     ->setParameter('paymentcode''')
  810.                     ->getQuery();
  811.             $documentPaymentType $queryDocumentType->getResult();
  812.             $postData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  813.             if (false !== strpos($provider->getName(), 'Juniper')) {
  814.                 $passangerTypes = [];
  815.                 for ($i 1$i <= $postData['Rooms']; ++$i) {
  816.                     $passangerTypes[$i] = [
  817.                         'ADT' => (int) $postData['Adults'.$i],
  818.                         'CHD' => (int) $postData['Children'.$i],
  819.                         'INF' => 0,
  820.                     ];
  821.                 }
  822.             } else {
  823.                 $passangerTypes[1] = [
  824.                     'ADT' => 1,
  825.                     'CHD' => 0,
  826.                     'INF' => 0,
  827.                 ];
  828.             }
  829.             $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  830.             $paymentOptions = [];
  831.             foreach ($paymentMethodAgency as $payMethod) {
  832.                 $paymentCode $payMethod->getPaymentMethod()->getCode();
  833.                 if (!in_array($paymentCode$paymentOptions) && ('p2p' == $paymentCode || 'cybersource' == $paymentCode)) {
  834.                     $paymentOptions[] = $paymentCode;
  835.                 }
  836.             }
  837.             $banks = [];
  838.             if (in_array('pse'$paymentOptions)) {
  839.                 $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  840.             }
  841.             $cybersource = [];
  842.             if (in_array('cybersource'$paymentOptions)) {
  843.                 $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  844.                 $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  845.             }
  846.             foreach ($paymentOptions as $key => $paymentOption) {
  847.                 if ('cybersource' == $paymentOption) {
  848.                     unset($paymentOptions[$key]); // strip from other renderizable payment methods
  849.                 }
  850.             }
  851.             $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_hotels');
  852.             if (isset($paymentData->cusPOptSelected)) {
  853.                 //$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData->id);
  854.                 $customerLogin $tokenStorage->getToken()->getUser();
  855.                 if (is_object($customerLogin)) {
  856.                     $paymentsSaved $customerMethodPayment->getMethodsByCustomer($customerLoginfalse);
  857.                 }
  858.             }
  859.             $responseHotelDetail = [
  860.                 'twig_readonly' => true,
  861.                 'referer' => $session->get($transactionId.'[availability_url]'),
  862.                 'passengers' => $passangerInfo ?? null,
  863.                 'billingData' => $billingData ?? null,
  864.                 'contactData' => $contactData ?? null,
  865.                 'doc_type' => $typeDocument,
  866.                 'gender' => $typeGender,
  867.                 'hotelProvidersId' => [(string) $provider->getProvideridentifier()],
  868.                 'detailHotel' => $detailHotel,
  869.                 'payment_doc_type' => $documentPaymentType,
  870.                 'services' => $passangerTypes,
  871.                 'conditions' => $conditions,
  872.                 'payment_type_form_name' => $provider->getPaymentType()->getTwig(),
  873.                 'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
  874.                 'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
  875.                 'paymentOptions' => $paymentOptions,
  876.                 'banks' => $banks,
  877.                 'cybersource' => $cybersource,
  878.                 'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  879.                 'additional' => base64_encode($transactionId.'/'.$session->get($transactionId.'[hotel]['.$correlationIdSessionName.']')),
  880.             ];
  881.             $responseHotelDetail['baloto'] ?? ($responseHotelDetail['baloto'] = false);
  882.             $responseHotelDetail['pse'] ?? ($responseHotelDetail['pse'] = true);
  883.             $responseHotelDetail['safety'] ?? ($responseHotelDetail['safety'] = true);
  884.         } else {
  885.             if (true === $request->has('referer')) {
  886.                 $session->set($transactionId.'[availability_url]'$request->get('http_referer'));
  887.                 $session->set($transactionId.'[referer]'$request->get('referer'));
  888.             } elseif (true !== $session->has($transactionId.'[availability_url]') || (false !== strpos($session->get($transactionId.'[availability_url]'), 'multi/'))) {
  889.                 try {
  890.                     $router_matched $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  891.                     if (isset($router_matched['rooms'])) {
  892.                         $session->set($transactionId.'[availability_url]'$server->get('HTTP_REFERER'));
  893.                         $session->set($transactionId.'[hotel][availability_url]'$server->get('HTTP_REFERER'));
  894.                     } elseif (('aviatur_hotel_availability_seo' == $router_matched['_route']) || ('aviatur_multi_availability_seo' == $router_matched['_route'])) {
  895.                         switch ($router_matched['_route']) {
  896.                             case 'aviatur_hotel_availability_seo'$flux 'hoteles';
  897.                                 break;
  898.                             case 'aviatur_multi_availability_seo'$flux 'multi';
  899.                                 break;
  900.                         }
  901.                         $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findOneByUrl($flux.'/'.$router_matched['url']);
  902.                         if (null != $seoUrl) {
  903.                             $maskedUrl $seoUrl->getMaskedurl();
  904.                             $parsedUrl parse_url($server->get('HTTP_REFERER'));
  905.                             $session->set($transactionId.'[availability_url]'$parsedUrl['scheme'].'://'.$parsedUrl['host'].$maskedUrl);
  906.                             $session->set($transactionId.'[hotel][availability_url]'$parsedUrl['scheme'].'://'.$parsedUrl['host'].$maskedUrl);
  907.                         } else {
  908.                             ////////Validar este errrrrooooorrrrr
  909.                             $session->set($transactionId.'[availability_url]'$server->get('HTTP_REFERER'));
  910.                         }
  911.                     } else {
  912.                         ////////Validar este errrrrooooorrrrr
  913.                         $session->set($transactionId.'[availability_url]'$server->get('HTTP_REFERER'));
  914.                     }
  915.                 } catch (\Exception $e) {
  916.                     ////////Validar este errrrrooooorrrrr
  917.                     $session->set($transactionId.'[availability_url]'$server->get('HTTP_REFERER'));
  918.                 }
  919.             }
  920.             if ($session->has('hotelAdapterId')) {
  921.                 $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($request->get('providerID'));
  922.             } else {
  923.                 $configsHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
  924.                 foreach ($configsHotelAgency as $configHotelAgency) {
  925.                     if ($request->get('providerID') == $configHotelAgency->getProvider()->getProvideridentifier()) {
  926.                         $provider $configHotelAgency->getProvider();
  927.                     }
  928.                 }
  929.             }
  930.             $session->set($transactionId.'[hotel][provider]'$provider->getId());
  931.             $correlationID $request->get('correlationId');
  932.             $session->set($transactionIdSessionName$transactionId);
  933.             $session->set($transactionId.'[hotel]['.$correlationIdSessionName.']'$correlationID);
  934.             $session->set($transactionId.'[referer]'$server->get('HTTP_REFERER'));
  935.             $startDate $request->get('startDate');
  936.             $endDate $request->get('endDate');
  937.             $dateIn strtotime($startDate);
  938.             $dateOut strtotime($endDate);
  939.             $nights floor(($dateOut $dateIn) / (24 60 60));
  940.             $searchHotelCodes = ['---''--'];
  941.             $replaceHotelCodes = ['/''|'];
  942.             $hotelCode explode('-'str_replace($searchHotelCodes$replaceHotelCodes$request->get('hotelCode')));
  943.             $country $request->get('country');
  944.             $variable = [
  945.                 'correlationId' => $correlationID,
  946.                 'start_date' => $startDate,
  947.                 'end_date' => $endDate,
  948.                 'hotel_code' => $hotelCode[0],
  949.                 'country' => $country,
  950.                 'ProviderId' => $provider->getProvideridentifier(),
  951.             ];
  952.             $hotelModel = new HotelModel();
  953.             $xmlRequest $hotelModel->getXmlDetail();
  954.             $message '';
  955.             if ($session->has($transactionId.'[hotel][detail]') && true !== $session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  956.                 $response = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  957.                 if (isset($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo)) {
  958.                     $guestsInfo $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo;
  959.                 }
  960.             } else {
  961.                 $aviaturWebService->setUrls(json_decode($session->get($domain'[parameters]')));
  962.                 $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelRoomList''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  963.                 // $response = simplexml_load_file("C:/wamp/www/aviatur/app/serviceLogs/HotelRoomList/HotelRoomList__static.xml"); ;
  964.                 if (!isset($response['error'])) {
  965.                     /* desactivamos al proveedor que esta fallando */
  966.                     $message $response->ProviderResults->ProviderResult['Message'];
  967.                     if (false !== strpos($message'El valor no puede ser nulo') || false !== strpos($message'Referencia a objeto no establecida') || false !== strpos($message'No se puede convertir un objeto')) {
  968.                         $worngProvider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  969.                         $activeWProvider $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['provider' => $worngProvider->getId(), 'agency' => $agency]);
  970.                         $badproviders $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('badProviders');
  971.                         $mailInfo '<p>El proveedor '.$worngProvider->getName().' esta presentando problemas y se procede a ser desactivado</p><p>Mensaje de error: '.$message.'</p>';
  972.                         $message = (new \Swift_Message())
  973.                                 ->setContentType('text/html')
  974.                                 ->setFrom($session->get('emailNoReply'))
  975.                                 ->setTo(json_decode($badproviders->getDescription())->email->hoteles)
  976.                                 ->setSubject('proveedor con problemas')
  977.                                 ->setBody($mailInfo);
  978.                         $mailer->send($message);
  979.                         $activeWProvider[0]->setIsactive(0);
  980.                         $em->persist($activeWProvider[0]);
  981.                         $em->flush();
  982.                     }
  983.                     // $hotelEntity = $em->getRepository(\Aviatur\HotelBundle\Entity\Hotel::class)->findOneByCodhotel($hotelCode[0]);
  984.                     $markup $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->find($hotelCode[1]);
  985.                     // if ($hotelEntity != null) {
  986.                     //     $markupValue = $hotelEntity->getMarkupValue();
  987.                     // } else {
  988.                     $markupValue $markup->getValue();
  989.                     // }
  990.                     $markupId $markup->getId();
  991.                     $parametersJson $session->get($domain.'[parameters]');
  992.                     $parameters json_decode($parametersJson);
  993.                     $tax = (float) $parameters->aviatur_payment_iva;
  994.                     $currency 'COP';
  995.                     if (strpos($provider->getName(), '-USD')) {
  996.                         $currency 'USD';
  997.                     }
  998.                     $currencyCode = (string) $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
  999.                     if ('COP' != $currencyCode && 'COP' == $currency) {
  1000.                         $trm $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
  1001.                         $trm $trm[0]['value'];
  1002.                     } else {
  1003.                         $trm 1;
  1004.                     }
  1005.                     foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay as $roomStay) {
  1006.                         $roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markupId;
  1007.                         foreach ($roomStay->RoomRates->RoomRate as $roomRate) {
  1008.                             if ('N' == $markup->getConfigHotelAgency()->getType()) {
  1009.                                 $aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markupValue / (100 $markupValue);
  1010.                             } else {
  1011.                                 $aviaturMarkup 0;
  1012.                             }
  1013.                             $roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
  1014.                             if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
  1015.                                 $roomRate->Total['AmountAviaturMarkupTax'] = 0;
  1016.                             } else {
  1017.                                 $roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup $tax;
  1018.                             }
  1019.                             $roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
  1020.                             $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round((float) ($aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
  1021.                             if ('COP' == $currencyCode) {
  1022.                                 $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
  1023.                             }
  1024.                             if (isset($roomRate->Total['RateOverrideIndicator']) || (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces']))) {
  1025.                                 $roomRate->TotalAviatur['AmountTax'] = 0;
  1026.                             } else {
  1027.                                 $roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
  1028.                             }
  1029.                             $roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
  1030.                             $roomRate->TotalAviatur['calcTripPrice'] = (float) $roomRate->TotalAviatur['AmountTotal'] * $nights;
  1031.                             $roomRate->TotalAviatur['CurrencyCode'] = $currency;
  1032.                             $roomRate->TotalAviatur['Markup'] = $markupValue;
  1033.                             $roomRate->TotalAviatur['MarkupId'] = $markupId;
  1034.                             $roomRate->TotalAviatur['MarkupType'] = $markup->getConfigHotelAgency()->getType();
  1035.                             $roomRate->TotalAviatur['calcBasePrice'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $nights;
  1036.                             if ($isMulti && !$isFront) {
  1037.                                 $postData $request->all();
  1038.                                 $postDataCountry $postData['country'] ?? '';
  1039.                                 $detailDiscount $multiHotelDiscount->setDetailDiscount($transactionId$postDataCountry$postData$agency$nights);
  1040.                                 if ('1' === $detailDiscount['availability_hasdiscount'] && false === $detailDiscount['discount_is_valid']) {
  1041.                                     $message 'Lamentamos informarte que este descuento ya no se encuentra disponible. '
  1042.                                             .'Si no estás registrado, te invitamos a hacerlo. Te mantendremos informado de nuestras ofertas. Gracias por viajar con Aviatur.com';
  1043.                                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($session->get($transactionId.'[availability_url]'), 'Descuento caducado'$message));
  1044.                                 }
  1045.                                 $detailHasDiscount $detailDiscount['discount_is_valid'];
  1046.                                 $roomRateDiscountValues $multiHotelDiscount->calculateDiscount($roomRate$nights$transactionId);
  1047.                                 $roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] = $roomRate->TotalAviatur['calcTripPrice'];
  1048.                                 $roomRate->TotalAviatur['calcTripPrice'] = $roomRateDiscountValues->calcTripPriceDiscount ?? $roomRate->TotalAviatur['calcTripPrice'];
  1049.                                 $roomRate->TotalAviatur['calcBasePriceBeforeDiscount'] = $roomRate->TotalAviatur['calcBasePrice'];
  1050.                                 $roomRate->TotalAviatur['calcBasePrice'] = $roomRateDiscountValues->calcTripBaseDiscount ?? $roomRate->TotalAviatur['calcBasePrice'];
  1051.                                 $roomRate->TotalAviatur['discountAmount'] = $roomRateDiscountValues->discountTotal ?? 0;
  1052.                                 $roomRate->TotalAviatur['AmountIncludingAviaturMarkupBeforeDiscount'] = $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'];
  1053.                                 $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = $roomRateDiscountValues->AmountIncludingAviaturMarkup ?? $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'];
  1054.                                 $roomRate->TotalAviatur['calcTripTaxDiscount'] = $roomRateDiscountValues->calcTripTaxDiscount ?? 0;
  1055.                                 if ($roomRate->TotalAviatur['AmountTax'] > 0) {
  1056.                                     $roomRate->TotalAviatur['AmountTaxBeforeDiscount'] = $roomRate->TotalAviatur['AmountTax'];
  1057.                                     $roomRate->TotalAviatur['AmountTax'] = $roomRateDiscountValues->AmountTax ?? $roomRate->TotalAviatur['AmountTax'];
  1058.                                 }
  1059.                             }
  1060.                             /*                             * **************  Validar Sesion Agent Octopus *************** */
  1061.                             $totalcommission 0;
  1062.                             $hotelCommission 0;
  1063.                             $commissionActive null;
  1064.                             if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING') && $session->get($transactionId.'_isActiveQse')) {
  1065.                                 $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] = 0;
  1066.                                 $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  1067.                                 // if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
  1068.                                 if (!empty($agent)) {
  1069.                                     $nameProduct 'hotel';
  1070.                                     $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  1071.                                     $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
  1072.                                     $infoQse json_decode($agentCommission->getQseproduct());
  1073.                                     //TODO: uncomment
  1074.                                     // $infoQse = (empty($infoQse)) ? false : (empty($infoQse->$nameProduct)) ? false : $infoQse->$nameProduct;
  1075.                                     $productCommissionPercentage $productCommission->getQsecommissionpercentage();
  1076.                                     $qseCommissionPercentage $productCommission->getQsecommissionpercentage();
  1077.                                     $tarifaCommissionPercentage $productCommission->getTacommissionpercentage();
  1078.                                     $hotelCommission = ($infoQse) ? (int) $infoQse-> hotel -> commission_money 0;
  1079.                                     $commissionActive = ($infoQse) ? (int) $infoQse-> hotel -> active 0;
  1080.                                     $commissionPercentage = ($infoQse) ? (float) $infoQse-> hotel -> commission_percentage 0;
  1081.                                     $activeDetail $agentCommission->getActivedetail();
  1082.                                     //************* Amount qse Detalles Hotel ***************\\
  1083.                                     $response->Message->OTA_HotelRoomListRS['typeAgency'] = $markup->getConfigHotelAgency()->getType();
  1084.                                     $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] = $roomRate->Total['AmountAviaturMarkup'];
  1085.                                     if ('P' == $markup->getConfigHotelAgency()->getType()) {
  1086.                                         $commissionFare round($roomRate->Total['AmountIncludingMarkup'] * ($markupValue 100));
  1087.                                         $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] = $commissionFare;
  1088.                                     }
  1089.                                     $response->Message->OTA_HotelRoomListRS['commissionActive'] = $commissionActive;
  1090.                                     if ('0' == $commissionActive) {
  1091.                                         $response->Message->OTA_HotelRoomListRS['commissionQse'] = round($hotelCommission);
  1092.                                     } elseif ('1' == $commissionActive) {
  1093.                                         $response->Message->OTA_HotelRoomListRS['commissionQse'] = round($roomRate->Total['AmountIncludingMarkup'] * $commissionPercentage);
  1094.                                     }
  1095.                                     $response->Message->OTA_HotelRoomListRS['commissionPercentage'] = $productCommissionPercentage;
  1096.                                     $response->Message->OTA_HotelRoomListRS['commissionId'] = $agentCommission->getId();
  1097.                                     $response->Message->OTA_HotelRoomListRS['activeDetail'] = $activeDetail;
  1098.                                     //$roomRate->TotalAviatur['calcBasePrice'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $nights;
  1099.                                     $commissionActive $response->Message->OTA_HotelRoomListRS['commissionActive'];
  1100.                                     $productCommissionPercentage 0;
  1101.                                     if (null != $response->Message->OTA_HotelRoomListRS['commissionId']) {
  1102.                                         if (null != $commissionActive) {
  1103.                                             if ('0' == $commissionActive) {
  1104.                                                 $totalcommission round($response->Message->OTA_HotelRoomListRS['commissionQse']);
  1105.                                             } elseif ('1' == $commissionActive) {
  1106.                                                 $totalcommission round($response->Message->OTA_HotelRoomListRS['commissionQse'] * $nights);
  1107.                                             }
  1108.                                         }
  1109.                                         $productCommissionPercentage $response->Message->OTA_HotelRoomListRS['commissionPercentage'];
  1110.                                         //$totalCommisionFare = 0;
  1111.                                         $totalCommisionFare $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'];
  1112.                                         if ('P' == $markup->getConfigHotelAgency()->getType()) {
  1113.                                             $totalCommisionFare round((float) $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] * $nights);
  1114.                                         }
  1115.                                     }
  1116.                                     $valueTax $tax 1;
  1117.                                     //$totalCommissionPay1 = round(((float) $totalCommisionFare + (float) $totalcommission) / $valueTax);
  1118.                                     $totalCommissionPay1 round((((float) $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] * $nights) / 1.19) * $tarifaCommissionPercentage);
  1119.                                     $totalCommissionPay2 round((((float) $response->Message->OTA_HotelRoomListRS['commissionQse'] * $nights) / 1.19) * $qseCommissionPercentage);
  1120.                                     $totalCommissionPay round($totalCommissionPay1 $totalCommissionPay2); // Su ganancia
  1121.                                     $isAgent true;
  1122.                                 }
  1123.                             }
  1124.                             $fullPricing = [
  1125.                                 'total' => ((float) $roomRate->TotalAviatur['AmountTotal'] * $nights) + $totalcommission,
  1126.                                 'totalPerNight' => (float) $roomRate->TotalAviatur['AmountTotal'],
  1127.                                 'totalWithoutService' => (((float) $roomRate->TotalAviatur['AmountTotal'] - (float) $roomRate->Total['AmountTotal']) * $nights) + $totalcommission,
  1128.                                 'currency' => (string) $currency,
  1129.                             ];
  1130.                             if ($isAgent) {
  1131.                                 $fullPricing['totalCommissionHotel'] = round((float) $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] * $nights); // Comisión por Tarifa
  1132.                                 $fullPricing['totalGananciaHotel'] = round(($fullPricing['totalCommissionHotel'] / 1.19) * $tarifaCommissionPercentage); // Ganacia por tarifa
  1133.                                 // $fullPricing['totalCommissionPay'] = $totalCommissionPay;
  1134.                                 $fullPricing['markupValue'] = isset($markupValue) ? (float) $markupValue 0;
  1135.                                 if (null != $commissionActive) {
  1136.                                     if ('0' == $commissionActive) {
  1137.                                         $fullPricing['totalCommissionAgent'] = (float) $response->Message->OTA_HotelRoomListRS['commissionQse'];
  1138.                                     } elseif ('1' == $commissionActive) {
  1139.                                         $fullPricing['totalCommissionAgent'] = round($response->Message->OTA_HotelRoomListRS['commissionQse'] * $nights);
  1140.                                     }
  1141.                                     $fullPricing['totalGananciaAgent'] = round(($fullPricing['totalCommissionAgent'] / 1.19) * $qseCommissionPercentage); //Ganacia QSE
  1142.                                 }
  1143.                                 $fullPricing['totalCommissionPay'] = $fullPricing['totalGananciaHotel'] +  $fullPricing['totalGananciaAgent'];
  1144.                             }
  1145.                             if (isset($roomRate->Total->Taxes)) {
  1146.                                 $i 0;
  1147.                                 $fullPricing['taxes'] = [];
  1148.                                 $fullPricing['taxes'][0] = [];
  1149.                                 $fullPricing['taxes'][1] = [];
  1150.                                 foreach ($roomRate->Total->Taxes->Tax as $subTax) {
  1151.                                     if (isset($subTax['Code'])) {
  1152.                                         $fullPricing['taxes'][(int) $subTax['Code']][$i] = [];
  1153.                                         $fullPricing['taxes'][(int) $subTax['Code']][$i][] = (string) $subTax['Type'];
  1154.                                         $fullPricing['taxes'][(int) $subTax['Code']][$i][] = ((float) $subTax['Amount']) * $nights;
  1155.                                         ++$i;
  1156.                                     }
  1157.                                 }
  1158.                             }
  1159.                             $i 0;
  1160.                             foreach ($roomRate->Rates->Rate as $rate) {
  1161.                                 $fullPricing['rooms'][$i] = ((float) $rate->Total['AmountAfterTax']) * $nights;
  1162.                                 ++$i;
  1163.                             }
  1164.                             $roomRate->TotalAviatur['FullPricing'] = base64_encode(json_encode($fullPricing));
  1165.                         }
  1166.                     }
  1167.                     $guestsInfo 'S';
  1168.                     if (isset($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo)) {
  1169.                         $guestsInfo $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo;
  1170.                     }
  1171.                     $response->Message->OTA_HotelRoomListRS['StartDate'] = $startDate;
  1172.                     $response->Message->OTA_HotelRoomListRS['EndDate'] = $endDate;
  1173.                     $response->Message->OTA_HotelRoomListRS['Adults'] = $request->get('Adults');
  1174.                     $response->Message->OTA_HotelRoomListRS['Children'] = $request->get('Children');
  1175.                     $response->Message->OTA_HotelRoomListRS['Rooms'] = $request->get('Rooms');
  1176.                     $session->set($transactionId.'[hotel][detail]'$response->asXML());
  1177.                 } else {
  1178.                     $responseHotelDetail $response;
  1179.                 }
  1180.             }
  1181.             if (!isset($responseHotelDetail['error'])) {
  1182.                 $detailHotelRaw $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay;
  1183.                 $httpsPhotos = [];
  1184.                 if (!empty($detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem)) {
  1185.                     foreach ($detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem as $httpPhoto) {
  1186.                         array_push($httpsPhotos$httpPhoto);
  1187.                     }
  1188.                 }
  1189.                 $postData $request->all();
  1190.                 $session->set($transactionId.'[hotel][availability_data_hotel]'json_encode($postData));
  1191.                 if (false !== strpos($provider->getName(), 'Juniper') || 'M' == $guestsInfo) {
  1192.                     $passangerTypes = [];
  1193.                     $passangerTypes[1] = [
  1194.                         'ADT' => (int) $request->get('Adults'),
  1195.                         'CHD' => (int) $request->get('Children'),
  1196.                         'INF' => 0,
  1197.                     ];
  1198.                 } else {
  1199.                     $passangerTypes[1] = [
  1200.                         'ADT' => 1,
  1201.                         'CHD' => 0,
  1202.                         'INF' => 0,
  1203.                     ];
  1204.                 }
  1205.                 $roomRate = [];
  1206.                 /* foreach ($detailHotelRaw->RoomRates->RoomRate as $roomRatePlan) {
  1207.                   $roomRate[] = $roomRatePlan;
  1208.                   }
  1209.                   $services = array();
  1210.                   foreach ($detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service as $service) {
  1211.                   $services[] = $service;
  1212.                   }
  1213.                   $commission = (isset($response->Message->OTA_HotelRoomListRS['commissionPercentage']) ? (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'] : null ); */
  1214.                 for ($u 0$u < (is_countable($detailHotelRaw->RoomRates->RoomRate) ? count($detailHotelRaw->RoomRates->RoomRate) : 0); ++$u) {
  1215.                     if (null != $response->Message->OTA_HotelRoomListRS['commissionId']) {
  1216.                         $qsewithCommission $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['calcBasePrice'] + $response->Message->OTA_HotelRoomListRS['commissionQse'];
  1217.                     } else {
  1218.                         $qsewithCommission $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['calcBasePrice'];
  1219.                     }
  1220.                     $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['calcBasePriceQse'] = $qsewithCommission;
  1221.                     //var_dump(json_decode(base64_decode((string)  $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['FullPricing']), true));
  1222.                 }
  1223.                 //die;
  1224.                 foreach ($detailHotelRaw->RoomRates->RoomRate as $roomRatePlan) {
  1225.                     $roomRate[] = $roomRatePlan;
  1226.                 }
  1227.                 $services = [];
  1228.                 if (isset($detailHotelRaw->TPA_Extensions->HotelInfo->Services)) {
  1229.                     foreach ($detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service as $service) {
  1230.                         $services[] = $service;
  1231.                     }
  1232.                 }
  1233.                 //$commission = (isset($response->Message->OTA_HotelRoomListRS['commissionPercentage']) ? (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'] : null );
  1234.                 if ($isAgent) {
  1235.                     $commission = (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'];
  1236.                     $commissionQse = (float) $response->Message->OTA_HotelRoomListRS['commissionQse'];
  1237.                     $parametersJson $session->get($domain.'[parameters]');
  1238.                     $parameters json_decode($parametersJson);
  1239.                     $tax = (float) $parameters->aviatur_payment_iva;
  1240.                     //$QsetoPay = round(($commissionQse / (1 + $tax)) * $commission);
  1241.                     $QsetoPay $fullPricing['totalCommissionPay'];
  1242.                     $response->Message->OTA_HotelRoomListRS['QsetoPay'] = $QsetoPay;
  1243.                 }
  1244.                 if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  1245.                     $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  1246.                 } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  1247.                     $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  1248.                 } else {
  1249.                     $urlAvailability $session->get($transactionId.'[availability_url]');
  1250.                 }
  1251.                 $routeParsed parse_url($urlAvailability);
  1252.                 if ($session->has($transactionId.'external')) {
  1253.                     $childsURL '';
  1254.                     $routeParsed['scheme'] = 'http';
  1255.                     $routeParsed['host'] = $session->get('domain');
  1256.                     if ($request->get('Children') > 0) {
  1257.                         if ($request->get('Children0') > 0) {
  1258.                             $childsURL .= $request->get('Children0');
  1259.                         }
  1260.                         if ($request->get('Children1') > 0) {
  1261.                             $childsURL .= '-'.$request->get('Children1');
  1262.                         }
  1263.                         if ($request->get('Children2') > 0) {
  1264.                             $childsURL .= '-'.$request->get('Children2');
  1265.                         }
  1266.                     } else {
  1267.                         $childsURL 'n';
  1268.                     }
  1269.                     $routeParsed['path'] = '/hoteles/'.$request->get('zone').'/'.$startDate.'+'.$endDate.'/'.$request->get('Adults').'+'.$childsURL.'';
  1270.                     $session->set('routePath'$routeParsed['path']);
  1271.                 }
  1272.                 $availabilityUrl $router->match($routeParsed['path']);
  1273.                 $rooms = [];
  1274.                 $adults 0;
  1275.                 $childs 0;
  1276.                 if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  1277.                     for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  1278.                         $adults += $availabilityUrl['adult'.$i];
  1279.                         $childrens = [];
  1280.                         if ('n' != $availabilityUrl['child'.$i]) {
  1281.                             $childAgesTemp explode('-'$availabilityUrl['child'.$i]);
  1282.                             $childs += count($childAgesTemp);
  1283.                         }
  1284.                     }
  1285.                 }
  1286.                 else {
  1287.                     $data json_decode($session->get($transactionId '[hotel][availability_data_hotel]'));
  1288.                     if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
  1289.                         $availabilityData json_decode(base64_decode($data->attributes), true);
  1290.                     } else {
  1291.                         $availabilityData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  1292.                     }
  1293.                     if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  1294.                         for ($i 0$i $availabilityData['Rooms']; ++$i) {
  1295.                             $adults += $availabilityData['Adults'.$i] ?? 0;
  1296.                             if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
  1297.                                 $childs += $availabilityData['Children'.$i];
  1298.                             }
  1299.                         }
  1300.                     }
  1301.                 }
  1302.                 $detailHotel = [
  1303.                     'dateIn' => $dateIn,
  1304.                     'dateOut' => $dateOut,
  1305.                     'dateInStr' => $startDate,
  1306.                     'dateOutStr' => $endDate,
  1307.                     'nights' => $nights,
  1308.                     'adults' => $request->get('Adults'),
  1309.                     'children' => $request->get('Children'),
  1310.                     'rooms' => $request->get('Rooms') ?? $availabilityUrl['rooms'] ?? $availabilityData['Rooms'] ?? $session->get('AvailabilityArrayhotel')['Rooms'],
  1311.                     'roomInformation' => $rooms,
  1312.                     'roomRates' => $roomRate,
  1313.                     'timeSpan' => $detailHotelRaw->TimeSpan,
  1314.                     'total' => $detailHotelRaw->Total,
  1315.                     'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
  1316.                     'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
  1317.                     'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
  1318.                     'email' => $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
  1319.                     'services' => $services,
  1320.                     'photos' => $httpsPhotos,
  1321.                 ];
  1322.                 if ($isAgent) {
  1323.                     $detailHotel['commissionAgentValue'] = $response->Message->OTA_HotelRoomListRS;
  1324.                 }
  1325.                 // END // Collection of informations to show in template (dates, passengers, hotel)
  1326.                 $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1327.                 $typeGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  1328.                 $repositoryDocumentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  1329.                 $queryDocumentType $repositoryDocumentType
  1330.                         ->createQueryBuilder('p')
  1331.                         ->where('p.paymentcode != :paymentcode')
  1332.                         ->setParameter('paymentcode''')
  1333.                         ->getQuery();
  1334.                 $documentPaymentType $queryDocumentType->getResult();
  1335.                 $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  1336.                 $paymentOptions = [];
  1337.                 foreach ($paymentMethodAgency as $payMethod) {
  1338.                     $paymentCode $payMethod->getPaymentMethod()->getCode();
  1339.                     if (!in_array($paymentCode$paymentOptions) && 'p2p' == $paymentCode || 'cybersource' == $paymentCode) {
  1340.                         $paymentOptions[] = $paymentCode;
  1341.                     }
  1342.                 }
  1343.                 $banks = [];
  1344.                 if (in_array('pse'$paymentOptions)) {
  1345.                     $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  1346.                 }
  1347.                 $cybersource = [];
  1348.                 if (in_array('cybersource'$paymentOptions)) {
  1349.                     $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  1350.                     $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  1351.                 }
  1352.                 foreach ($paymentOptions as $key => $paymentOption) {
  1353.                     if ('cybersource' == $paymentOption) {
  1354.                         unset($paymentOptions[$key]); // strip from other renderizable payment methods
  1355.                     }
  1356.                 }
  1357.                 $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_hotels');
  1358.                 $pixelInfo = [];
  1359.                 if (!$isFront) {
  1360.                     // PIXELES INFORMATION
  1361.                     $pixel['partner_datalayer'] = [
  1362.                         'event' => 'hotelCheckout',
  1363.                         'dimension1' => isset($detailHotel['basicInfos']->Address->CityName) ? (string) $detailHotel['basicInfos']->Address->CityName '',
  1364.                         'dimension2' => '',
  1365.                         'dimension3' => $detailHotel['dateInStr'],
  1366.                         'dimension4' => $detailHotel['dateOutStr'],
  1367.                         'dimension5' => 'Checkout Hotel',
  1368.                         'dimension6' => '',
  1369.                         'dimension7' => '',
  1370.                         'dimension8' => '',
  1371.                         'dimension9' => isset($detailHotel['basicInfos']['HotelCode']) ? (string) $detailHotel['basicInfos']['HotelCode'] : '',
  1372.                         'dimension10' => '',
  1373.                         'dimension11' => isset($detailHotel['adults']) ? ($detailHotel['adults'] + $detailHotel['children']) : 0,
  1374.                         'dimension12' => 'Hotel',
  1375.                         'ecommerce' => [
  1376.                             'checkout' => [
  1377.                                 'products' => [
  1378.                                     'actionField' => "{'step': 1 }",
  1379.                                     'name' => isset($detailHotel['basicInfos']['HotelCode']) ? (string) $detailHotel['basicInfos']['HotelCode'] : '',
  1380.                                     'price' => '',
  1381.                                     'brand' => isset($detailHotel['basicInfos']['HotelName']) ? (string) $detailHotel['basicInfos']['HotelName'] : '',
  1382.                                     'category' => 'Hotel',
  1383.                                     'variant' => '',
  1384.                                     'quantity' => isset($detailHotel['adults']) ? ($detailHotel['adults'] + $detailHotel['children']) : 0,
  1385.                                 ],
  1386.                             ],
  1387.                         ],
  1388.                     ];
  1389.                     if ($fullRequest->request->has('kayakclickid') || $fullRequest->query->has('kayakclickid')) {
  1390.                         if ($fullRequest->request->has('kayakclickid')) {
  1391.                             $kayakclickid $fullRequest->request->get('kayakclickid');
  1392.                         } elseif ($fullRequest->query->has('kayakclickid')) {
  1393.                             $kayakclickid $fullRequest->query->get('kayakclickid');
  1394.                         }
  1395.                         $pixel['kayakclickid'] = $kayakclickid;
  1396.                         $session->set($transactionId.'[hotel][kayakclickid]'$pixel['kayakclickid']);
  1397.                     }
  1398.                     //$pixel['dataxpand'] = true;
  1399.                     $pixelInfo $aviaturPixeles->verifyPixeles($pixel'hotel''detail'$agency->getAssetsFolder(), $transactionId);
  1400.                 }
  1401.                 $isNational true;
  1402.                 if ('CO' != $country) {
  1403.                     $isNational false;
  1404.                 }
  1405.                 $args = (object) [
  1406.                             'isNational' => $isNational,
  1407.                             'countryCode' => $postDataCountry ?? null,
  1408.                             'passangerTypes' => $passangerTypes,
  1409.                             'destinationArray' => [
  1410.                                 'Start' => $detailHotel['dateInStr'],
  1411.                                 'End' => $detailHotel['dateOutStr'],
  1412.                                 'Code' => $fullRequest->request->get('Destination'),
  1413.                                 'passangerTypes' => $passangerTypes,
  1414.                             ],
  1415.                 ];
  1416.                 if ($isMulti && !$isFront && isset($postDataCountry)) {
  1417.                     $detailCoupon $aviaturCouponDiscount->loadCoupons($agency$transactionId'hotel'$args);
  1418.                     if ($detailCoupon) {
  1419.                         $detailHasCoupon true;
  1420.                         $detailHotel['couponInfo'] = [
  1421.                             'title' => $detailCoupon->Title,
  1422.                             'description' => $detailCoupon->Title,
  1423.                             'validateUrl' => $detailCoupon->ValidateURL,
  1424.                             'couponDiscountTotal' => $detailCoupon->CoupontDiscountAmountTotal,
  1425.                             'policy' => $detailCoupon->CouponPolicies,
  1426.                         ];
  1427.                     }
  1428.                 }
  1429.                 if (!$session->has($transactionId.'[hotel][args]')) {
  1430.                     $session->set($transactionId.'[hotel][args]'json_encode($args));
  1431.                 }
  1432.                 $payoutExtras null;
  1433.                 if (!$isFront && !$isMulti) {
  1434.                     $payoutExtras $payoutExtraService->loadPayoutExtras($agency$transactionId'hotel'$args);
  1435.                 }
  1436.                 $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  1437.                 if (null != $pointRedemption) {
  1438.                     $points 0;
  1439.                     if ($fullRequest->request->has('pointRedemptionValue')) {
  1440.                         $points $fullRequest->request->get('pointRedemptionValue');
  1441.                         $session->set('point_redemption_value'$points);
  1442.                     } elseif ($fullRequest->query->has('pointRedeem')) {
  1443.                         $points $fullRequest->query->get('pointRedeem');
  1444.                         $session->set('point_redemption_value'$points);
  1445.                     } elseif ($session->has('point_redemption_value')) {
  1446.                         $points $session->get('point_redemption_value');
  1447.                     }
  1448.                     $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  1449.                 }
  1450.                 $pixel $request->get('pixelInfo'); //cambios fer
  1451.                 $responseHotelDetail = [
  1452.                     'twig_readonly' => false,
  1453.                     'referer' => $session->get($transactionId.'[availability_url]'),
  1454.                     'doc_type' => $typeDocument,
  1455.                     'gender' => $typeGender,
  1456.                     'detailHotel' => $detailHotel,
  1457.                     'payment_doc_type' => $documentPaymentType,
  1458.                     'services' => $passangerTypes,
  1459.                     'conditions' => $conditions,
  1460.                     'hotelProvidersId' => [(string) $provider->getProvideridentifier()],
  1461.                     'payment_type_form_name' => $provider->getPaymentType()->getTwig(),
  1462.                     'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
  1463.                     'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
  1464.                     'paymentOptions' => $paymentOptions,
  1465.                     'banks' => $banks,
  1466.                     'cybersource' => $cybersource,
  1467.                     'additional' => base64_encode($transactionId.'/'.$session->get($transactionId.'[hotel]['.$correlationIdSessionName.']')),
  1468.                     'payoutExtras' => $payoutExtras,
  1469.                     'pointRedemption' => $pointRedemption,
  1470.                     'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  1471.                     'pixel_info' => $pixelInfo//Cambios fer start
  1472.                     'HotelCode' => $request->get('hotelCode'),
  1473.                     'providerID' => $request->get('providerID'),
  1474.                     'correlationId' => $request->get('correlationId'),
  1475.                     'transactionId' => $request->get('transactionID'),
  1476.                     'startDate' => $request->get('startDate'),
  1477.                     'endDate' => $request->get('endDate'),
  1478.                     'country' => $request->get('country'),
  1479.                     'RateHasDiscount' => $request->get('AvailabilityHasDiscount'),
  1480.                     'pixelInfo' => $pixel['partner_datalayer'],
  1481.                     'HotelMinPrice' => $request->get('HotelMinPrice'),
  1482.                     'Rooms' => $request->get('Rooms'),
  1483.                     'Children' => $request->get('Children'),
  1484.                     'Adults' => $request->get('Adults'),
  1485.                     'Destination' => $request->get('Destination'),
  1486.                     'Children0' => $request->get('Children0'),
  1487.                     'Adults0' => $request->get('Adults0'),
  1488.                     'CurrencyCode' => $currencyCode ?? null,
  1489.                     'availableArrayHotel' => ('' != $session->get('AvailabilityArrayhotel')) ? $session->get('AvailabilityArrayhotel') : null,
  1490.                     'Code' => $args->destinationArray['Code'] ?? null,//cambios fer end
  1491.                 ];
  1492.                 $responseHotelDetail['baloto'] ?? ($responseHotelDetail['baloto'] = false);
  1493.                 $responseHotelDetail['pse'] ?? ($responseHotelDetail['pse'] = true);
  1494.                 $responseHotelDetail['safety'] ?? ($responseHotelDetail['safety'] = true);
  1495.             } else {
  1496.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl'Ha ocurrido un error inesperado'$responseHotelDetail['error']));
  1497.             }
  1498.         }
  1499.         $route $router->match(str_replace($fullRequest->getSchemeAndHttpHost(), ''$fullRequest->getUri()));
  1500.         $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  1501.         if ($isMulti) {
  1502.             $detailHotel['hasCoupon'] = $detailHasCoupon;
  1503.             if ($session->get('currentHotelDiscountSession') === $transactionId && !$isFront) {
  1504.                 $detailHotel['discountAmount'] = $session->get($transactionId.'[HotelDiscounts][discountTotal]');
  1505.                 $detailHotel['discountAmountTRM'] = $session->get($transactionId.'[HotelDiscounts][discountAmountTRM]');
  1506.                 $detailHotel['hasDiscount'] = $detailHasDiscount;
  1507.                 $policyText $session->get($transactionId.'[HotelDiscounts][discountPolicyText]');
  1508.                 $detailHotel['discountPolicyText'] = \str_replace("\r\n"'<br>&bull;'$policyText);
  1509.                 $responseHotelDetail['detailHotel'] = $detailHotel;
  1510.             }
  1511.             $context['responseHotelDetail']='responseHotelDetail';
  1512.             return $this->json($responseHotelDetail200, [], $context);
  1513.         }
  1514.         $today date('Y-m-d');
  1515.         // $diffDays = (strtotime($responseHotelDetail['detailHotel']['dateInStr']) - strtotime($today)) / 86400;
  1516.         $diffDays = (strtotime($detailHotel['dateInStr']) - strtotime($today)) / 86400;
  1517.         if ($diffDays 0) {
  1518.             $responseHotelDetail['baloto'] = true;
  1519.         }
  1520.         $responseHotelDetail['baloto'] ?? ($responseHotelDetail['baloto'] = false);
  1521.         if (('error' == $responseHotelDetail) || (isset($responseHotelDetail['error']))) {
  1522.             $session $session;
  1523.             $transactionId $session->get($transactionIdSessionName);
  1524.             $message $responseHotelDetail['error'] ?? 'Ha ocurrido un error inesperado';
  1525.             return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible'$message));
  1526.         } else {
  1527.             $responseHotelDetail['city']= $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo->Address->CityName->__toString() ?? '';
  1528.             $responseHotelDetail['nights']=$nights;
  1529.             $agencyFolder $twigFolder->twigFlux();
  1530.             $view $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/detail_info.html.twig');
  1531.             return $this->render($view$responseHotelDetail);
  1532.         }
  1533.     }
  1534.     public function detailInvalidAction(Request $requestAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerTwigFolder $twigFolderSessionInterface $sessionParameterBagInterface $parameterBag)
  1535.     {
  1536.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1537.         $server $request->server;
  1538.         if (true === $session->has($transactionIdSessionName)) {
  1539.             $transactionId $session->get($transactionIdSessionName);
  1540.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  1541.             if (true === $session->has($transactionId.'[availability_url]')) {
  1542.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible''No puedes acceder al detalle sin disponibilidad'));
  1543.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  1544.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtalo nuevamente'));
  1545.             } else {
  1546.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puedes acceder al detalle sin disponibilidad'));
  1547.             }
  1548.         } else {
  1549.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puedes acceder al detalle sin disponibilidad'));
  1550.         }
  1551.     }
  1552.     public function prePaymentStep1Action(Request $requestTokenizerService $tokenizerServiceCustomerMethodPaymentService $customerMethodPaymentTokenStorageInterface $tokenStorageAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerAviaturEncoder $aviaturEncoderTwigFolder $twigFolderSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  1553.     {
  1554.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1555.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  1556.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1557.         if ($request->isXmlHttpRequest()) {
  1558.             $request $request->request;
  1559.             $quotation $request->get('QT');
  1560.             $transactionId $session->get($transactionIdSessionName);
  1561.             $billingData $request->get('BD');
  1562.             $em $this->managerRegistry;
  1563.             $postData $request->all();
  1564.             $publicKey $aviaturEncoder->aviaturRandomKey();
  1565.             $session->remove('register-extra-data');
  1566.             if (isset($postData['PD']['card_num'])) {
  1567.                 $postDataInfo $postData;
  1568.                 if (isset($postDataInfo['PD']['cusPOptSelected'])) {
  1569.                     $customerLogin $tokenStorage->getToken()->getUser();
  1570.                     $infoMethodPaymentByClient $customerMethodPayment->getMethodsByCustomer($customerLogintrue);
  1571.                     $cardToken $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
  1572.                     $postDataInfo['PD']['card_num'] = $cardToken;
  1573.                 } else {
  1574.                     $postDataInfo['PD']['card_num'] = $tokenizerService->getToken($postData['PD']['card_num']);
  1575.                 }
  1576.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  1577.             }
  1578.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
  1579.             $formUserInfo = new FormUserInfo();
  1580.             $formUserInfo->setInfo($encodedInfo);
  1581.             $formUserInfo->setPublicKey($publicKey);
  1582.             $em->persist($formUserInfo);
  1583.             $em->flush();
  1584.             $session->set($transactionId.'[hotel][user_info]'$formUserInfo->getId());
  1585.             if ((true !== $session->has($transactionId.'[hotel][retry]')) || (true !== $session->has($transactionId.'[hotel][prepayment_check]'))) {
  1586.                 if (true === $session->has($transactionId.'[hotel][detail]')) {
  1587.                     $isFront $session->has('operatorId');
  1588.                     //$postData = $request->all();
  1589.                     $session->set($transactionId.'[hotel][detail_data_hotel]'json_encode($postData));
  1590.                     $passangersData $request->get('PI');
  1591.                     $passangerNames = [];
  1592.                     for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  1593.                         $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  1594.                         $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  1595.                     }
  1596.                     if (($isFront) && ('0' == $quotation['quotation_check'])) {
  1597.                         $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  1598.                         if (== sizeof($nameWhitelist)) {
  1599.                             $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  1600.                             if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  1601.                                     (sizeof($nameBlacklist)) ||
  1602.                                     (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  1603.                                 return $this->json(['error' => 'error''message' => 'nombre inválido']);
  1604.                             }
  1605.                         }
  1606.                     }
  1607.                     if ($isFront) {
  1608.                         $customer null;
  1609.                         $ordersProduct null;
  1610.                     } else {
  1611.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  1612.                         $ordersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
  1613.                     }
  1614.                     if (null == $ordersProduct) {
  1615.                         $documentTypes $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1616.                         $arrayDocumentTypes = [];
  1617.                         foreach ($documentTypes as $documentType) {
  1618.                             $arrayDocumentTypes[$documentType->getExternalCode()] = $documentType->getId();
  1619.                         }
  1620.                         $genders $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  1621.                         $arrayGenders = [];
  1622.                         foreach ($genders as $gender) {
  1623.                             $arrayGenders[$gender->getCode()] = $gender->getExternalCode();
  1624.                         }
  1625.                         $hotelModel = new HotelModel();
  1626.                         $xmlRequest $hotelModel->getXmlConditions();
  1627.                         $detail = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  1628.                         if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  1629.                             $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  1630.                         } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  1631.                             $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  1632.                         } else {
  1633.                             $urlAvailability $session->get($transactionId.'[availability_url]');
  1634.                         }
  1635.                         $routeParsed parse_url($urlAvailability);
  1636.                         if ($session->has($transactionId.'external')) {
  1637.                             $routeParsed['path'] = $session->get('routePath');
  1638.                         }
  1639.                         $availabilityUrl $router->match($routeParsed['path']);
  1640.                         $adults 0;
  1641.                         $childs 0;
  1642.                         if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  1643.                             for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  1644.                                 $adults += $availabilityUrl['adult'.$i];
  1645.                                 $childrens = [];
  1646.                                 if ('n' != $availabilityUrl['child'.$i]) {
  1647.                                     $childAgesTemp explode('-'$availabilityUrl['child'.$i]);
  1648.                                     $childs += count($childAgesTemp);
  1649.                                 }
  1650.                             }
  1651.                         }
  1652.                         else {
  1653.                             $data json_decode($session->get($transactionId '[hotel][availability_data_hotel]'));
  1654.                             if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
  1655.                                 $availabilityData json_decode(base64_decode($data->attributes), true);
  1656.                             } else {
  1657.                                 $availabilityData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  1658.                             }
  1659.                             if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  1660.                                 for ($i 0$i $availabilityData['Rooms']; ++$i) {
  1661.                                     $adults += $availabilityData['Adults'.$i] ?? 0;
  1662.                                     if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
  1663.                                         $childs += $availabilityData['Children'.$i];
  1664.                                     }
  1665.                                 }
  1666.                             }
  1667.                         }
  1668.                         $hotelCode explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
  1669.                         $hotelInformation $request->get('HI');
  1670.                         $gender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData['gender_1_1']);
  1671.                         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData['nationality_1_1']);
  1672.                         $session->set($transactionId.'[hotel][retry]'$aviaturPaymentRetryTimes);
  1673.                         $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  1674.                         if (null == $customer && 'Omnibees' == $provider->getName()) {
  1675.                             $inputRequired 'n/a';
  1676.                         } else {
  1677.                             $inputRequired null;
  1678.                         }
  1679.                         $variable = [
  1680.                             'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
  1681.                             'ProviderId' => $provider->getProvideridentifier(),
  1682.                             'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
  1683.                             'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
  1684.                             'RatePlan' => $hotelInformation['ratePlan'],
  1685.                             'HotelCode' => $hotelCode[0],
  1686.                             'rooms' => $availabilityData['Rooms'] ?? $availabilityUrl['rooms'],
  1687.                             'Adults' => $adults,
  1688.                             'Children' => $childs,
  1689.                             'Usuario' => $session->get('domain'),
  1690.                             'BirthDate' => null == $customer '1969-01-01' $customer->getBirthdate()->format('Y-m-d'),
  1691.                             'Gender' => $gender->getExternalcode(),
  1692.                             'GivenName' => null == $customer $billingData['first_name'] : $customer->getFirstname(),
  1693.                             'Surname' => null == $customer $billingData['last_name'] : $customer->getLastname(),
  1694.                             'PhoneNumber' => null == $customer $billingData['phone'] : $customer->getPhone(),
  1695.                             'Email' => null == $customer null $customer->getEmail(),
  1696.                             'AddressLine' => null == $customer $inputRequired $customer->getAddress(),
  1697.                             'CityName' => null == $customer $inputRequired $customer->getCity()->getDescription(),
  1698.                             'CountryName' => $country->getDescription(),
  1699.                             'DocID' => null == $customer $billingData['doc_num'] : $customer->getDocumentnumber(),
  1700.                         ];
  1701.                         $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelDetail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  1702.                         if (!isset($response['error'])) {
  1703.                             $session->set($transactionId.'[hotel][prepayment]'$response->asXML());
  1704.                             $cancelPenalties = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->CancelPenalties->CancelPenalty->PenaltyDescription->Text;
  1705.                             $comments = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Comments;
  1706.                             $ajaxUrl $this->generateUrl('aviatur_hotel_prepayment_step_2_secure');
  1707.                             $agencyFolder $twigFolder->twigFlux();
  1708.                             $info $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/policy.html.twig'), ['penalties' => $cancelPenalties'comments' => $comments]);
  1709.                             if (($isFront) && ('1' == $quotation['quotation_check'])) {
  1710.                                 return $this->json([
  1711.                                             'quotationPenalties' => $cancelPenalties,
  1712.                                             'quotationComments' => $comments,
  1713.                                             'namesClient' => $quotation['quotation_name'],
  1714.                                             'lastnamesClient' => $quotation['quotation_lastname'],
  1715.                                             'emailClient' => $quotation['quotation_email'],
  1716.                                 ]);
  1717.                             } elseif (($isFront) && ('0' == $quotation['quotation_check'])) {
  1718.                                 return $this->json(['cancelPenalties' => $info'ajax_url' => $ajaxUrl]);
  1719.                             } elseif ((!$isFront)) {
  1720.                                 return $this->json(['cancelPenalties' => $info'ajax_url' => $ajaxUrl]);
  1721.                             }
  1722.                         } else {
  1723.                             $session->remove($transactionId.'[hotel][retry]');
  1724.                             $session->remove($transactionId.'[hotel][prepayment]');
  1725.                             return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), ''$response['error'])]);
  1726.                         }
  1727.                     } else {
  1728.                         $booking = [];
  1729.                         $cus = [];
  1730.                         foreach ($ordersProduct as $orderProduct) {
  1731.                             $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  1732.                             $paymentResponse json_decode($productResponse);
  1733.                             array_push($booking'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
  1734.                             if (isset($paymentResponse->x_approval_code)) {
  1735.                                 array_push($cus$paymentResponse->x_approval_code);
  1736.                             } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  1737.                                 array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  1738.                             }
  1739.                         }
  1740.                         return $this->json([
  1741.                                     'error' => 'pending payments',
  1742.                                     'message' => 'pending_payments',
  1743.                                     'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null,
  1744.                                     'cus' => $cus,
  1745.                         ]);
  1746.                     }
  1747.                 } else {
  1748.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
  1749.                 }
  1750.             } else {
  1751.                 $request $request->request;
  1752.                 $paymentData $request->get('PD');
  1753.                 $paymentData json_decode(json_encode($paymentData));
  1754.                 $json json_decode($session->get($transactionId.'[hotel][order]'));
  1755.                 $postData $request->all();
  1756.                 if (!is_null($json)) {
  1757.                     $json->ajax_url $this->generateUrl('aviatur_hotel_prepayment_step_2_secure');
  1758.                     // reemplazar datos de pago por los nuevos.
  1759.                     $oldPostData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  1760.                     if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
  1761.                         if (isset($paymentData->cusPOptSelected)) {
  1762.                             $customerLogin $tokenStorage->getToken()->getUser();
  1763.                             $infoMethodPaymentByClient $customerMethodPayment->getMethodsByCustomer($customerLogintrue);
  1764.                             $card_num_token $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  1765.                         } else {
  1766.                             $card_num_token $tokenizerService->getToken($paymentData->card_num);
  1767.                         }
  1768.                         $card_values = ['card_num_token' => $card_num_token'card_num' => $paymentData->card_num];
  1769.                     }
  1770.                     unset($oldPostData->PD);
  1771.                     $oldPostData->PD $paymentData;
  1772.                     $oldPostData->PD->card_values $card_values;
  1773.                     $session->set($transactionId.'[hotel][detail_data_hotel]'json_encode($oldPostData));
  1774.                     $response = new Response(json_encode($json));
  1775.                     $response->headers->set('Content-Type''application/json');
  1776.                     return $response;
  1777.                 } else {
  1778.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
  1779.                 }
  1780.             }
  1781.         } else {
  1782.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  1783.         }
  1784.     }
  1785.     public function prePaymentStep2Action(Request $requestOrderController $orderControllerAuthorizationCheckerInterface $authorizationCheckerAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolderManagerRegistry $registry, \Swift_Mailer $mailerRouterInterface $routerAviaturWebService $aviaturWebServiceParameterBagInterface $parameterBag)
  1786.     {
  1787.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1788.         $order = [];
  1789.         if ($request->isXmlHttpRequest()) {
  1790.             $request $request->request;
  1791.             $em $this->managerRegistry;
  1792.             $session $this->session;
  1793.             $agency $this->agency;
  1794.             $billingData $request->get('BD');
  1795.             $detailEncodedData $request->get('DD');
  1796.             $detailData explode('/'base64_decode($detailEncodedData['additional']));
  1797.             $transactionId $detailData[0];
  1798.             $session->set($transactionId.'[hotel][prepayment_check]'true);
  1799.             if (true !== $session->has($transactionId.'[hotel][order]')) {
  1800.                 if (true === $session->has($transactionId.'[hotel][detail]')) {
  1801.                     $session->set($transactionIdSessionName$transactionId);
  1802.                     $isFront $session->has('operatorId');
  1803.                     if ($isFront) {
  1804.                         $customer $billingData;
  1805.                         $customer['isFront'] = true;
  1806.                         $status 'B2T';
  1807.                     } else {
  1808.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  1809.                         $status 'waiting';
  1810.                     }
  1811.                     if (isset($agency)) {
  1812.                         $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('HOTEL');
  1813.                         if ($isFront) {
  1814.                             $orderIdentifier '{order_product_reservation}';
  1815.                         } else {
  1816.                             $orderIdentifier '{order_product_num}';
  1817.                         }
  1818.                         $order $orderController->createAction($agency$customer$productType$orderIdentifier$status);
  1819.                         $orderId str_replace('ON'''$order['order']);
  1820.                         $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  1821.                         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  1822.                             $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  1823.                             if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
  1824.                                 $detailResponse = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  1825.                                 $orderProductEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find(str_replace('PN'''$order['products']));
  1826.                                 $postData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  1827.                                 $hotelInfo $postData->HI;
  1828.                                 foreach ($detailResponse->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
  1829.                                     if ($roomRatePlan['RatePlanCode'] == $hotelInfo->ratePlan) {
  1830.                                         $roomRate $roomRatePlan;
  1831.                                     }
  1832.                                 }
  1833.                                 $commissionPay json_decode($hotelInfo->commissionPay);
  1834.                                 //$taAmount = (float) $detailResponse->Message->OTA_HotelRoomListRS['TotalCommissionFare'];
  1835.                                 $taAmount abs((float) $commissionPay->amountTarifa);
  1836.                                 //$commissionPercentage = (float) $detailResponse->Message->OTA_HotelRoomListRS['commissionPercentage'];
  1837.                                 $nameProduct 'hotel';
  1838.                                 $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  1839.                                 $qsePercentage $productCommission->getQsecommissionpercentage();
  1840.                                 $commissionPercentage $productCommission->getTacommissionpercentage();
  1841.                                 //$qseAmount = abs((float) $commissionPay->amountQse - $taAmount);
  1842.                                 $qseAmount abs((float) $commissionPay->amountQse);
  1843.                                 $startDate strtotime((string) $detailResponse->Message->OTA_HotelRoomListRS['StartDate']);
  1844.                                 $endDate strtotime((string) $detailResponse->Message->OTA_HotelRoomListRS['EndDate']);
  1845.                                 $datediff $endDate $startDate;
  1846.                                 $travelDays floor($datediff / (60 60 24));
  1847.                                 $agentTransaction = new AgentTransaction();
  1848.                                 $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
  1849.                                 $agentTransaction->setOrderProduct($orderProductEntity);
  1850.                                 $agentTransaction->setAgent($agent);
  1851.                                 $agentTransaction->setAgentCommission($agentCommission);
  1852.                                 //$agentTransaction->setCommissionvalue(round((float) ($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $travelDays * (float) $detailResponse->Message->OTA_HotelRoomListRS['commissionPercentage'])));
  1853.                                 $agentTransaction->setCommissionvalue(round((float) ($commissionPay->commissionQse)));
  1854.                                 $agentTransaction->setAmountQse($qseAmount);
  1855.                                 $agentTransaction->setCommissionQse(round((((float) $qseAmount) / 1.19) * $qsePercentage));
  1856.                                 $agentTransaction->setAmountTarifa($taAmount);
  1857.                                 $agentTransaction->setCommissionTarifa(round((($taAmount) / 1.19) * $commissionPercentage));
  1858.                                 $agentTransaction->setAmountProduct($commissionPay->amountProduct);
  1859.                                 $agentTransaction->setPercentageTarifa($commissionPay->markupValue);
  1860.                                 $em->persist($agentTransaction);
  1861.                                 $em->flush();
  1862.                             }
  1863.                         }
  1864.                         $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[hotel][user_info]'));
  1865.                         $formUserInfo->setOrder($orderEntity);
  1866.                         $em->persist($formUserInfo);
  1867.                         $em->flush();
  1868.                         if ($isFront) {
  1869.                             $order['url'] = $this->makeReservation($session$mailer$aviaturWebService$aviaturErrorHandler$router$registry$parameterBag$transactionId$stateDb null);
  1870.                         } else {
  1871.                             // Cambiar nombre en condición
  1872.                             if ($agency->getName() === 'QA Aval') {
  1873.                                 $order['url'] = $this->generateUrl('tuplus_hotel_payment_secure');
  1874.                             } else {
  1875.                                 $order['url'] = $this->generateUrl('aviatur_hotel_payment_secure');
  1876.                             }
  1877.                         }
  1878.                         return $this->json($order);
  1879.                     } else {
  1880.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró la agencia con el dominio: '.$request->getHost()));
  1881.                         // redireccionar al home y enviar mensaje modal
  1882.                     }
  1883.                 } else {
  1884.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
  1885.                 }
  1886.             } else {
  1887.                 // Cambiar nombre en condición
  1888.                 if ($agency->getName() === 'QA Aval') {
  1889.                     $order['url'] = $this->generateUrl('tuplus_hotel_payment_secure');
  1890.                 } else {
  1891.                     $order['url'] = $this->generateUrl('aviatur_hotel_payment_secure');
  1892.                 }
  1893.                 return $this->json($order);
  1894.             }
  1895.         } else {
  1896.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  1897.         }
  1898.     }
  1899.     private function makeReservation(SessionInterface $session, \Swift_Mailer $mailerAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerManagerRegistry $registryParameterBagInterface $parameterBag$transactionId$stateDb null)
  1900.     {
  1901.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  1902.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1903.         $userData null;
  1904.         $isFront $session->has('operatorId');
  1905.         if ($isFront) {
  1906.             $usuario $session->get('operatorId');
  1907.             $customerModel = new CustomerModel();
  1908.             $userData null;
  1909.             try {
  1910.                 $userData $aviaturWebService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$customerModel->getXmlAgent($usuario));
  1911.                 $session->set($transactionId.'[user]'$userData->asXml());
  1912.                 $userEmail = (string) $userData->CORREO_ELECTRONICO;
  1913.             } catch (\Exception $e) {
  1914.                 $userEmail $session->get('domain').'@'.$session->get('domain');
  1915.             }
  1916.         } else {
  1917.             $userEmail $session->get('domain').'@'.$session->get('domain');
  1918.         }
  1919.         $hotelModel = new HotelModel();
  1920.         $xmlRequestArray $hotelModel->getXmlReservation();
  1921.         $detail = \simplexml_load_string((string) $session->get($transactionId.'[hotel][detail]'));
  1922.         if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  1923.             $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  1924.         } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  1925.             $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  1926.         } else {
  1927.             $urlAvailability $session->get($transactionId.'[availability_url]');
  1928.         }
  1929.         $routeParsed parse_url($urlAvailability);
  1930.         if ($session->has($transactionId.'external')) {
  1931.             $routeParsed['path'] = $session->get('routePath');
  1932.         }
  1933.         $availabilityUrl $router->match($routeParsed['path']);
  1934.         $adults 0;
  1935.         $childs 0;
  1936.         if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  1937.             for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  1938.                 $adults += $availabilityUrl['adult'.$i];
  1939.                 $childrens = [];
  1940.                 if ('n' != $availabilityUrl['child'.$i]) {
  1941.                     $childAgesTemp explode('-'$availabilityUrl['child'.$i]);
  1942.                     $childs += count($childAgesTemp);
  1943.                 }
  1944.             }
  1945.         }
  1946.         else {
  1947.             $availabilityData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  1948.             if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  1949.                 for ($i 0$i $availabilityData['Rooms']; ++$i) {
  1950.                     $adults += $availabilityData['Adults'.$i] ?? 0;
  1951.                     if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
  1952.                         $childs += $availabilityData['Children'.$i];
  1953.                     }
  1954.                 }
  1955.             }
  1956.         }
  1957.         $hotelCode explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
  1958.         $postData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  1959.         $passangersData $postData->PI;
  1960.         $hotelInformation $postData->HI;
  1961.         $ratePlanCode $hotelInformation->ratePlan;
  1962.         $em $this->managerRegistry;
  1963.         $gender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData->gender_1_1);
  1964.         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData->nationality_1_1);
  1965.         $session->set($transactionId.'[hotel][retry]'$aviaturPaymentRetryTimes);
  1966.         if ($isFront) {
  1967.             $customer null;
  1968.             $dbState 0//pending of payment with penalty policies autocancelation
  1969.         } else {
  1970.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  1971.             $dbState = (null != $stateDb) ? $stateDb 2//pending of payment with same day autocancelation
  1972.         }
  1973.         $passangersData->DocType_1_1 $passangersData->doc_type_1_1;
  1974.         if (false !== strpos($passangersData->first_name_1_1'***')) {
  1975.             $passangersData->first_name_1_1 $customer->getFirstname();
  1976.             $passangersData->last_name_1_1 $customer->getLastname();
  1977.             $passangersData->phone_1_1 $customer->getPhone();
  1978.             $passangersData->email_1_1 $customer->getEmail();
  1979.             $passangersData->address_1_1 $customer->getAddress();
  1980.             $passangersData->doc_num_1_1 $customer->getDocumentnumber();
  1981.         }
  1982.         $orderProductCode $session->get($transactionId.'[hotel][order]');
  1983.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1984.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1985.         $detailInfo = \simplexml_load_string((string) $session->get($transactionId.'[hotel][detail]'));
  1986.         $prepaymentInfo = \simplexml_load_string((string) $session->get($transactionId.'[hotel][prepayment]'));
  1987.         $startDate strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['StartDate']);
  1988.         $endDate strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['EndDate']);
  1989.         $this->generate_email($session$registry$orderProduct$detailInfo$prepaymentInfo$startDate$endDate);
  1990.         $orderRequestArray explode('<FILTRO>'str_replace('</FILTRO>''<FILTRO>'$orderProduct->getAddproductdata()));
  1991.         $orderRequest = \simplexml_load_string($orderRequestArray[1]);
  1992.         $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  1993.         if (null == $customer && 'Omnibees' == $provider->getName()) {
  1994.             $inputRequired 'n/a';
  1995.         } else {
  1996.             $inputRequired null;
  1997.         }
  1998.         $variable = [
  1999.             'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
  2000.             'ProviderId' => $provider->getProvideridentifier(),
  2001.             'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
  2002.             'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
  2003.             'RatePlanCode' => $ratePlanCode,
  2004.             'AmountAfterTax' => (string) $orderRequest->product->cost_data->fare->total_amount,
  2005.             'CurrencyCode' => false !== strpos($provider->getName(), 'USD') ? 'USD' 'COP',
  2006.             'HotelCode' => $hotelCode[0],
  2007.             'Rooms' => $availabilityData['Rooms'] ?? $availabilityUrl['rooms'],
  2008.             'Adults' => $adults,
  2009.             'Children' => $childs,
  2010.             'Usuario' => $userEmail,
  2011.             'EstadoBD' => $dbState,
  2012.             'BirthDate' => null == $customer '1980-01-01' $customer->getBirthdate()->format('Y-m-d'),
  2013.             'Gender' => $gender->getExternalcode(),
  2014.             'GivenName' => null == $customer $postData->BD->first_name $customer->getFirstname(),
  2015.             'Surname' => null == $customer $postData->BD->last_name $customer->getLastname(),
  2016.             'PhoneNumber' => null == $customer $postData->BD->phone $customer->getPhone(),
  2017.             'Email' => null == $customer null $customer->getEmail(),
  2018.             'AddressLine' => null == $customer $inputRequired $customer->getAddress(),
  2019.             'CityName' => null == $customer $inputRequired $customer->getCity()->getDescription(),
  2020.             'CountryName' => $country->getDescription(),
  2021.             'DocID' => null == $customer $postData->BD->doc_num $customer->getDocumentnumber(),
  2022.         ];
  2023.         //        $postDataArray = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'), true);
  2024.         $search = [
  2025.             '{Guest_DocID}',
  2026.             '{Guest_Name}',
  2027.             '{Guest_Surname}',
  2028.             '{Guest_Datebirth}',
  2029.             '{Guest_Gender}',
  2030.             '{Guest_Nationality}',
  2031.             '{Guest_DocType}',
  2032.             '{Guest_Type}',
  2033.             '{Guest_Email}',
  2034.             '{Guest_Phone}',
  2035.         ];
  2036.         $replace = [];
  2037.         $xmlRequest $xmlRequestArray[0];
  2038.         $xmlRequest .= $xmlRequestArray['RoomType'][0];
  2039.         $passangersDataArray json_decode(json_encode($passangersData), true);
  2040.         $totalGuests $passangersDataArray['person_count_1']; //$postDataArray['Adults'] + $postDataArray['Children'];
  2041.         for ($i 1$i <= $totalGuests; ++$i) {
  2042.             $gender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersDataArray['gender_1'.'_'.$i]);
  2043.             $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersDataArray['nationality_1'.'_'.$i]);
  2044.             $replace = [
  2045.                 '{doc_num_1'.'_'.$i.'}',
  2046.                 '{first_name_1'.'_'.$i.'}',
  2047.                 '{last_name_1'.'_'.$i.'}',
  2048.                 '{birthday_1'.'_'.$i.'}',
  2049.                 '{gender_1'.'_'.$i.'}',
  2050.                 '{nationality_1'.'_'.$i.'}',
  2051.                 '{DocType_1'.'_'.$i.'}',
  2052.                 '{passanger_type_1'.'_'.$i.'}',
  2053.                 (== $i) ? $passangersDataArray['email_1_1'] : '',
  2054.                 (== $i) ? $postData->CD->phone '',
  2055.             ];
  2056.             $xmlRequest .= str_replace($search$replace$xmlRequestArray['RoomType'][1]);
  2057.             $passangersDataArray['DocType_1'.'_'.$i] = $passangersDataArray['doc_type_1'.'_'.$i];
  2058.             $variable['doc_num_1'.'_'.$i] = $passangersDataArray['doc_num_1'.'_'.$i];
  2059.             $variable['first_name_1'.'_'.$i] = $passangersDataArray['first_name_1'.'_'.$i];
  2060.             $variable['last_name_1'.'_'.$i] = $passangersDataArray['last_name_1'.'_'.$i];
  2061.             $variable['birthday_1'.'_'.$i] = $passangersDataArray['birthday_1'.'_'.$i];
  2062.             $variable['gender_1'.'_'.$i] = $gender->getExternalcode();
  2063.             $variable['nationality_1'.'_'.$i] = $country->getIatacode();
  2064.             $variable['DocType_1'.'_'.$i] = $passangersDataArray['doc_type_1'.'_'.$i];
  2065.             $variable['passanger_type_1'.'_'.$i] = $passangersDataArray['passanger_type_1'.'_'.$i];
  2066.         }
  2067.         $xmlRequest .= $xmlRequestArray['RoomType'][2];
  2068.         $xmlRequest .= $xmlRequestArray[1];
  2069.         $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelRes''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  2070.         if (isset($response->Message->OTA_HotelResRS->HotelReservations)) {
  2071.             $reservationId = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->UniqueID['ID'];
  2072.             $orderProduct->setEmissiondata($reservationId);
  2073.             $orderProduct->setUpdatingdate(new \DateTime());
  2074.             $reservationId2 = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'];
  2075.             $session->set($transactionId.'[hotel][reservation]'$response->asXml());
  2076.             $contactNumber 'No info';
  2077.             if (isset($response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers) && isset($response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'])) {
  2078.                 $contactNumber = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'];
  2079.             }
  2080.             $search = ['{order_product_reservation}''{order_product_reservation_2}''{property_name_2}''{contact_number}'];
  2081.             $replace = [$reservationId$reservationId2, (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Payable$contactNumber];
  2082.             if ('Omnibees' == $provider->getName()) {
  2083.                 $reservation explode('-'$reservationId);
  2084.                 $search[] = '{incoming_office}';
  2085.                 $replace[] = $reservation[1];
  2086.             }
  2087.             $orderXml str_replace($search$replace$orderProduct->getAddProductData());
  2088.             $orderProduct->setAddProductData($orderXml);
  2089.             $orderProduct->setBooking($reservationId);
  2090.             $em->persist($orderProduct);
  2091.             $em->flush();
  2092.             if ($isFront) {
  2093.                 try {
  2094.                     $responseOrder $aviaturWebService->busWebServiceAmadeus(nullnull$orderXml);
  2095.                 } catch (\Exception $e) {
  2096.                 }
  2097.             }
  2098.             if ($isFront && isset($postData->HI->refundInfo) && 'NRF' == $postData->HI->refundInfo) {
  2099.                 $toEmails $userData->CORREO_ELECTRONICO;
  2100.                 $ccMails = ['w_aldana@aviatur.com'];
  2101.                 switch ((string) $provider->getProvideridentifier()) {
  2102.                     case '70'://hotelbeds pruebas
  2103.                     case '42'://hotelbeds produccion
  2104.                         $ccMails[] = 'johanna.briceno@aviatur.com';
  2105.                         break;
  2106.                     case '87'://Expedia pruebas
  2107.                     case '54'://Expedia producción
  2108.                         $ccMails[] = 'luz.ramirez@aviatur.com';
  2109.                         break;
  2110.                     case '102'://Bookohotel pruebas
  2111.                     case '108'//Lots Pruebas
  2112.                     case '62'://Bookohotel producción
  2113.                     case '68'://Lots producción
  2114.                         $ccMails[] = 'madeleine.garcia@aviatur.com';
  2115.                         break;
  2116.                 }
  2117.                 $bccMails 'errores.prod.web@aviatur.com';
  2118.                 $mailInfo '<p>Estimado '.$userData->NOMBRE_AGENTE.': </p><p> Teniendo en cuenta que usted acaba de generar un reserva bajo tarifa no reembolsable según las condiciones '
  2119.                         .'del proveedor, usted debió reconfirmar al cliente y generar la factura respectiva de cobro con el fin de evitar entrar en costos '
  2120.                         .'sobre dicha reserva y por lo cual es 100% su aceptación de dicho cobro.</p>';
  2121.                 $message = (new \Swift_Message())
  2122.                         ->setContentType('text/html')
  2123.                         ->setFrom($session->get('emailNoReply'))
  2124.                         ->setTo($toEmails)
  2125.                         ->setCc($ccMails)
  2126.                         ->setBcc($bccMails)
  2127.                         ->setSubject('Reserva generada en gastos: '.$reservationId2)
  2128.                         ->setBody($mailInfo);
  2129.                 $mailer->send($message);
  2130.             }
  2131.             if (!$isFront) {
  2132.                 $emailContent 'Hotel reservation '.$orderProduct->getEmissiondata().', the product id is: '.$orderProduct->getId().', the customer id is: '.$customer->getId().'</b> Email customer new DB: <b>'.$customer->getEmail().'</b>, the info is: '.$orderProduct->getEmail();
  2133.                 $message = (new \Swift_Message())
  2134.                         ->setContentType('text/html')
  2135.                         ->setFrom('noreply@aviatur.com.co')
  2136.                         ->setSubject('Hotel Reservation')
  2137.                         ->setTo(['soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co'])
  2138.                         ->setCc(['supervisorescallcenter@aviatur.com''hotelesenlineaaviatur@aviatur.com'])
  2139.                         ->setBcc(['notificacionessitioweb@aviatur.com''sebastian.huertas@aviatur.com'])
  2140.                         ->setBody($emailContent);
  2141.                 $mailer->send($message);
  2142.             }
  2143.             if ($isFront) {
  2144.                 return $this->generateUrl('aviatur_hotel_reservation_success_secure');
  2145.             } else {
  2146.                 // return $this->generateUrl('aviatur_hotel_payment_secure');
  2147.                 return true;
  2148.             }
  2149.         } else {
  2150.             $orderProduct->setEmissiondata('No Reservation');
  2151.             $orderProduct->setUpdatingdate(new \DateTime());
  2152.             $em->persist($orderProduct);
  2153.             $em->flush();
  2154.             $message 'Ha ocurrido un error realizando la reserva del hotel, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción';
  2155.             if (isset($response->ProviderResults->ProviderResult['Message']) && isset($response->ProviderResults->ProviderResult['Provider'])) {
  2156.                 if ('71' == $response->ProviderResults->ProviderResult['Provider']) {
  2157.                     $message $response->ProviderResults->ProviderResult['Message'];
  2158.                 }
  2159.             }
  2160.             if (!$isFront) {
  2161.                 $emailContent '
  2162.                 <b>No se realizó la reserva de hotel, tiene pago aprobado.</b><br/>
  2163.                 Info:<br/>
  2164.                 Referer in posaereos: '.$orderProduct->getBooking().'<br/>
  2165.                 The product id is: '.$orderProduct->getId().'<br/>
  2166.                 The customer id is: '.$customer->getId().'<br/></b>
  2167.                 Email customer DB: <b>'.$customer->getEmail().'</b>,<br/>
  2168.                 The info is: '.$orderProduct->getEmail();
  2169.                 $emailMessage = (new \Swift_Message())
  2170.                         ->setContentType('text/html')
  2171.                         ->setFrom('noreply@aviatur.com.co')
  2172.                         ->setSubject('Hotel reservation failed with payment approved')
  2173.                         ->setTo(['soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co'])
  2174.                         ->setCc(['supervisorescallcenter@aviatur.com''hotelesenlineaaviatur@aviatur.com'])
  2175.                         ->setBcc(['notificacionessitioweb@aviatur.com''sebastian.huertas@aviatur.com'])
  2176.                         ->setBody($emailContent);
  2177.                 $mailer->send($emailMessage);
  2178.                 return false;
  2179.             }
  2180.             return $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), ''$message);
  2181.         }
  2182.     }
  2183.     /**
  2184.      * Metodo creado para acceder desde la clase HotelTuPlusController.
  2185.      */
  2186.     protected function makeReservationTuPlus(SessionInterface $session, \Swift_Mailer $mailerAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerManagerRegistry $registryParameterBagInterface $parameterBag$transactionId$stateDb null)
  2187.     {
  2188.         return $this->makeReservation($session$mailer$aviaturWebService$aviaturErrorHandler$router$registry$parameterBag$transactionId$stateDb);
  2189.     }
  2190.     public function paymentAction(Request $request, \Swift_Mailer $mailerCashController $cashPayControllerSafetypayController $safetyPayControllerPSEController $psePaymentController,WorldPayController $worldPaymentController ,P2PController $p2pPaymentControllerMultiHotelDiscount $multiHotelDiscountPayoutExtraService $payoutExtraServiceAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerTwigFolder $twigFolderManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBagTokenizerService $tokenizerServiceCustomerMethodPaymentService $customerMethodPaymentAviaturLogSave $aviaturLogSaveOrderController $orderController)
  2191.     {
  2192.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2193.         $aviaturPaymentOnline $parameterBag->get('aviatur_payment_online');
  2194.         $aviaturPaymentOnRequest $parameterBag->get('aviatur_payment_on_request');
  2195.         $emailNotification $parameterBag->get('email_notification');
  2196.         $orderProduct = [];
  2197.         $roomRate = [];
  2198.         $paymentResponse null;
  2199.         $return null;
  2200.         $emissionData = [];
  2201.         $response null;
  2202.         $array = [];
  2203.         $em $this->managerRegistry;
  2204.         $session $this->session;
  2205.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  2206.         $aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
  2207.         $transactionId $session->get($transactionIdSessionName);
  2208.         $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  2209.         $providerId $provider->getProvideridentifier();
  2210.         $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  2211.         $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  2212.         if ($provider->getPaymentType()->getCode() == $aviaturPaymentOnRequest) {
  2213.             // pago en destino
  2214.             return $this->redirect($this->generateUrl('aviatur_hotel_confirmation'));
  2215.         } elseif ($provider->getPaymentType()->getcode() == $aviaturPaymentOnline) {
  2216.             // pago online
  2217.             $detailInfo = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  2218.             $prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
  2219.             $postData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  2220.             if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  2221.                 $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  2222.             } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  2223.                 $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  2224.             } else {
  2225.                 $urlAvailability $session->get($transactionId.'[availability_url]');
  2226.             }
  2227.             $routeParsed parse_url($urlAvailability);
  2228.             if ($session->has($transactionId.'external')) {
  2229.                 $routeParsed['path'] = $session->get('routePath');
  2230.             }
  2231.             $availabilityUrl $router->match($routeParsed['path']);
  2232.             $hotelName $detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo;
  2233.             $orderInfo json_decode($session->get($transactionId.'[hotel][order]'));
  2234.             $productId str_replace('PN'''$orderInfo->products);
  2235.             $orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2236.             $hotelInfo $postData->HI;
  2237.             foreach ($detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
  2238.                 if ($roomRatePlan['RatePlanCode'] == $hotelInfo->ratePlan) {
  2239.                     $roomRate $roomRatePlan;
  2240.                 }
  2241.             }
  2242.             $startDate strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['StartDate']);
  2243.             $endDate strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['EndDate']);
  2244.             $destination $availabilityUrl['destination1'] ?? $availabilityUrl['destination'] ?? json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true)['Destination'];
  2245.             //Agregar todos los cuartos a la descripción!!!!!!!!!!!!!!!!!
  2246.             $description 'Hotel - '.(string) $hotelName['HotelName'].'('.(string) $roomRate->Rates->Rate->RateDescription->Text.' '.(string) $roomRate['RatePlanCategory'].') - '.$destination.'('.date('d/m/Y'$startDate).' - '.date('d/m/Y'$endDate).')';
  2247.             $datediff $endDate $startDate;
  2248.             $travelDays floor($datediff / (60 60 24));
  2249.             $paymentData $postData->PD;
  2250.             // COLLECT INFORMATION TO PERSIST OrderProduct->Email
  2251.             $this->generate_email($session$registry$orderProduct[0], $detailInfo$prepaymentInfo$startDate$endDate);
  2252.             $discountTransactionID $session->get('currentHotelDiscountSession');
  2253.             $discountAmount 0;
  2254.             $discountTax 0;
  2255.             $_x_tax 0;
  2256.             $payoutExtrasValues null;
  2257.             if (isset($postData->payoutExtrasSelection) && !$isMulti) {
  2258.                 $payoutExtrasValues $payoutExtraService->getPayoutExtrasValues($postData->payoutExtrasSelection$transactionId);
  2259.             }
  2260.             if ($transactionId === $discountTransactionID) {
  2261.                 $discountValues $multiHotelDiscount->getPaymentDiscountValues($transactionId$roomRate);
  2262.                 $discountAmount = (float) $discountValues->discountAmount;
  2263.                 $discountTax = (float) $discountValues->discountTax;
  2264.                 $_x_tax = (float) $discountValues->x_tax;
  2265.             }
  2266.             $minimumAmount 1000;
  2267.             if (true === (bool) $session->get($transactionId.'[CouponDiscount][hotel][validationResult]')) {
  2268.                 $discountAmount = (float) $session->get($transactionId.'[CouponDiscount][discountTotal]');
  2269.                 $discountTax = (float) $session->get($transactionId.'[CouponDiscount][discountTax]');
  2270.                 if ((float) $roomRate->TotalAviatur['discountAmount'] > 0) {
  2271.                     $discountTripPrice = ($roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] - $discountAmount) >= $minimumAmount ? ($roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] - $discountAmount) : $minimumAmount;
  2272.                     $baseDiscounted round($discountTripPrice / ($aviaturPaymentIva));
  2273.                     $tripTaxDiscounted round($baseDiscounted $aviaturPaymentIva);
  2274.                     $AmountIncludingAviaturMarkup $roomRate->TotalAviatur['AmountIncludingAviaturMarkupBeforeDiscount'] - $discountAmount;
  2275.                 } else {
  2276.                     $discountTripPrice = ($roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] - $discountAmount) >= $minimumAmount ? ($roomRate->TotalAviatur['calcTripPrice'] - $discountAmount) : $minimumAmount;
  2277.                     $baseDiscounted round($discountTripPrice / ($aviaturPaymentIva));
  2278.                     $tripTaxDiscounted round($baseDiscounted $aviaturPaymentIva);
  2279.                 }
  2280.                 $_x_tax $roomRate->TotalAviatur['calcTripTaxDiscount'];
  2281.             }
  2282.             $qseAmount 0;
  2283.             if (!empty($hotelInfo->qseAmount)) {
  2284.                 $qseAmount $hotelInfo->qseAmount;
  2285.             }
  2286.             if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
  2287.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2288.                 if (false !== strpos($paymentData->address'***')) {
  2289.                     $paymentData->address $customer->getAddress();
  2290.                 }
  2291.                 if (false !== strpos($paymentData->phone'***')) {
  2292.                     $paymentData->phone $customer->getPhone();
  2293.                 }
  2294.                 if (false !== strpos($paymentData->email'***')) {
  2295.                     $paymentData->email $customer->getEmail();
  2296.                 }
  2297.                 $x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
  2298.                 $x_amount_total $x_amount_total $qseAmount;
  2299.                 if ($x_amount_total $minimumAmount) {
  2300.                     $x_amount_total $minimumAmount;
  2301.                 }
  2302.                 $x_amount_tax != (float) $roomRate->TotalAviatur['AmountTax'] ? (float) $x_amount_total $aviaturPaymentIva 0;
  2303.                 $x_amount_base != (float) $roomRate->TotalAviatur['AmountTax'] ? $x_amount_total $x_amount_tax 0;
  2304.                 $array = [
  2305.                     'x_currency_code' => (string) $roomRate->TotalAviatur['CurrencyCode'],
  2306.                     'x_amount' => $x_amount_total,
  2307.                     'x_tax' => number_format($x_amount_tax2'.'''),
  2308.                     'x_amount_base' => number_format($x_amount_base2'.'''),
  2309.                     //'x_amount_base' =>  number_format(round((float) ($roomRate->TotalAviatur['AmountTax'] != 0 ? $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $travelDays : 0)), 2, '.', ''),
  2310.                     'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  2311.                     'x_first_name' => $paymentData->first_name,
  2312.                     'x_last_name' => $paymentData->last_name,
  2313.                     'x_description' => $description,
  2314.                     'x_city' => $customer->getCity()->getIatacode(),
  2315.                     'x_country_id' => $customer->getCountry()->getIatacode(),
  2316.                     'x_cust_id' => $paymentData->doc_type.' '.$paymentData->doc_num,
  2317.                     'x_address' => $paymentData->address,
  2318.                     'x_phone' => $paymentData->phone,
  2319.                     'x_email' => $paymentData->email,
  2320.                     'x_card_num' => $paymentData->card_num,
  2321.                     'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
  2322.                     'x_card_code' => $paymentData->card_code,
  2323.                     'x_differed' => $paymentData->differed,
  2324.                     'x_client_id' => $postData->BD->id,
  2325.                     'product_type' => 'hotel',
  2326.                     'productId' => str_replace('PN'''$orderInfo->products),
  2327.                     'orderId' => str_replace('ON'''$orderInfo->order),
  2328.                     'franchise' => $paymentData->franquise,
  2329.                 ];
  2330.                 if (isset($paymentData->card_values)) {
  2331.                     $array['card_values'] = (array) $paymentData->card_values;
  2332.                 }
  2333.                 if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  2334.                     foreach ($payoutExtrasValues as $payoutExtraValues) {
  2335.                         $array['x_amount'] += round((float) $payoutExtraValues->values->fare->total);
  2336.                         $array['x_tax'] += round((float) $payoutExtraValues->values->fare->tax);
  2337.                         $array['x_amount_base'] += round((float) $payoutExtraValues->values->fare->base);
  2338.                     }
  2339.                     $array['x_amount'] = $array['x_amount'] + $qseAmount;
  2340.                 }
  2341.                 $payoutExtrasValues $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
  2342.                 $array['x_cancelation_date'] = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->CancellationPolicy['FechaEntradaGasto'];
  2343.                 if (isset($paymentData->cusPOptSelected)) {
  2344.                     $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  2345.                 }
  2346.                 if ('p2p' == $paymentData->type) {
  2347.                     if (isset($paymentData->savePaymProc)) {
  2348.                         $array['x_provider_id'] = 1;
  2349.                     } elseif (isset($paymentData->cusPOptSelected)) {
  2350.                         if (isset($paymentData->cusPOptSelectedStatus)) {
  2351.                             if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
  2352.                                 $array['x_provider_id'] = 1;
  2353.                             } else {
  2354.                                 $array['x_provider_id'] = 2;
  2355.                             }
  2356.                         } else {
  2357.                             $array['x_provider_id'] = 2;
  2358.                         }
  2359.                     }
  2360.                 }
  2361.                 if ('p2p' == $paymentData->type) {
  2362.                     $paymentResponse $p2pPaymentController->placetopayAction($parameterBag$tokenizerService$customerMethodPayment$mailer$aviaturLogSave$array$combination false$segment nullfalse);
  2363.                     $return $this->redirect($this->generateUrl('aviatur_hotel_payment_p2p_return_url_secure', [], true));
  2364.                 } elseif ('world' == $paymentData->type) {
  2365.                     $array['city'] = $customer->getCity()->getIatacode();
  2366.                     $array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
  2367.                     $paymentResponse $worldPaymentController->worldAction($request$mailer$aviaturLogSave$customerMethodPayment$parameterBag$array);
  2368.                     $return $this->redirect($this->generateUrl('aviatur_hotel_payment_world_return_url_secure', [], true));
  2369.                 }
  2370.                 unset($array['x_client_id']);
  2371.                 if (null != $paymentResponse) {
  2372.                     return $return;
  2373.                 } else {
  2374.                     $orderProduct[0]->setStatus('pending');
  2375.                     $em->persist($orderProduct[0]);
  2376.                     $em->flush();
  2377.                     return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  2378.                 }
  2379.             } elseif ('pse' == $paymentData->type) {
  2380.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2381.                 $x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
  2382.                 if ($x_amount_total $minimumAmount) {
  2383.                     $x_amount_total $minimumAmount;
  2384.                 }
  2385.                 $x_amount_tax != (float) $roomRate->TotalAviatur['AmountTax'] ? (float) $x_amount_total $aviaturPaymentIva 0;
  2386.                 $x_amount_base != (float) $roomRate->TotalAviatur['AmountTax'] ? $x_amount_total $x_amount_tax 0;
  2387.                 $array = ['x_doc_num' => $customer->getDocumentnumber(),
  2388.                     'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  2389.                     'x_first_name' => $customer->getFirstname(),
  2390.                     'x_last_name' => $customer->getLastname(),
  2391.                     'x_company' => 'Aviatur',
  2392.                     'x_email' => $customer->getEmail(),
  2393.                     'x_address' => $customer->getAddress(),
  2394.                     'x_city' => $customer->getCity()->getDescription(),
  2395.                     'x_province' => $customer->getCity()->getDescription(),
  2396.                     'x_country' => $customer->getCountry()->getDescription(),
  2397.                     'x_phone' => $customer->getPhone(),
  2398.                     'x_mobile' => $customer->getCellphone(),
  2399.                     'x_bank' => $postData->PD->pse_bank,
  2400.                     'x_type' => $postData->PD->pse_type,
  2401.                     'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  2402.                     'x_description' => $description,
  2403.                     'x_currency' => (string) $roomRate->TotalAviatur['CurrencyCode'],
  2404.                     'x_total_amount' => $x_amount_total,
  2405.                     'x_tax_amount' => number_format(round($x_amount_tax), 2'.'''),
  2406.                     'x_devolution_base' => number_format(round($x_amount_base), 2'.'''),
  2407.                     'x_tip_amount' => number_format(round(0), 2'.'''),
  2408.                     'product_type' => 'hotel',
  2409.                 ];
  2410.                 if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  2411.                     foreach ($payoutExtrasValues as $payoutExtraValues) {
  2412.                         $array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
  2413.                         $array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
  2414.                         $array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
  2415.                     }
  2416.                 }
  2417.                 $payoutExtrasValues $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
  2418.                 $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  2419.                 $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  2420.                 if ($isMulti) {
  2421.                     return $this->json($array);
  2422.                 }
  2423.                 $array['x_providerId'] = $providerId;
  2424.                 $paymentResponse $psePaymentController->sendPaymentAction($array$orderProduct);
  2425.                 if (!isset($paymentResponse->error)) {
  2426.                     switch ($paymentResponse->createTransactionResult->returnCode) {
  2427.                         case 'SUCCESS':
  2428.                             return $this->redirect($paymentResponse->createTransactionResult->bankURL);
  2429.                         case 'FAIL_EXCEEDEDLIMIT':
  2430.                             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Tu reserva fue realizada exitosamente, sin embargo, el monto excede los límites establecidos, comuníate con nosotros a  los teléfonos 57 1 5879640 o 57 1 3821616 o  vía e-mail al correo soportepagoelectronico@aviatur.com.co para completar tu transacción.'));
  2431.                         case 'FAIL_BANKUNREACHEABLE':
  2432.                             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''Tu entidad financiera no pudo ser contactada para iniciar la transacción, por favor inténtalo nuevamente'));
  2433.                         default:
  2434.                             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''No se pudo crear la transacción con tu banco, por favor inténtalo nuevamente'));
  2435.                     }
  2436.                 } else {
  2437.                     return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), 'Error al procesar el pago''Ocurrió un problema al intentar crear tu transacción, '.$paymentResponse->error));
  2438.                 }
  2439.             } elseif ('safety' == $paymentData->type) {
  2440.                 $orderProductCode json_decode($session->get($transactionId.'[hotel][order]'));
  2441.                 $transactionUrl $this->generateUrl('aviatur_payment_safetypay', [], true);
  2442.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2443.                 $productId str_replace('PN'''$orderProductCode->products);
  2444.                 $Product $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2445.                 $x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
  2446.                 if ($x_amount_total $minimumAmount) {
  2447.                     $x_amount_total $minimumAmount;
  2448.                 }
  2449.                 $x_amount_tax != (float) $roomRate->TotalAviatur['AmountTax'] ? (float) $x_amount_total $aviaturPaymentIva 0;
  2450.                 $x_amount_base != (float) $roomRate->TotalAviatur['AmountTax'] ? $x_amount_total $x_amount_tax 0;
  2451.                 $array = ['x_doc_num' => $customer->getDocumentnumber(),
  2452.                     'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  2453.                     'x_first_name' => $customer->getFirstname(),
  2454.                     'x_last_name' => $customer->getLastname(),
  2455.                     'x_company' => 'Aviatur',
  2456.                     'x_email' => $customer->getEmail(),
  2457.                     'x_address' => $customer->getAddress(),
  2458.                     'x_city' => $customer->getCity()->getDescription(),
  2459.                     'x_province' => $customer->getCity()->getDescription(),
  2460.                     'x_country' => $customer->getCountry()->getDescription(),
  2461.                     'x_phone' => $customer->getPhone(),
  2462.                     'x_mobile' => $customer->getCellphone(),
  2463.                     'x_reference' => $orderInfo->products,
  2464.                     'x_booking' => $Product->getBooking(),
  2465.                     'x_description' => $description,
  2466.                     'x_currency' => (string) $roomRate->TotalAviatur['CurrencyCode'],
  2467.                     'x_total_amount' => $x_amount_total,
  2468.                     'x_tax_amount' => number_format(round($x_amount_tax), 2'.'''),
  2469.                     'x_devolution_base' => number_format(round($x_amount_base), 2'.'''),
  2470.                     'x_tip_amount' => number_format(round(0), 2'.'''),
  2471.                     'x_payment_data' => $paymentData->type,
  2472.                     'x_type_description' => $orderProduct[0]->getDescription(),
  2473.                 ];
  2474.                 if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  2475.                     foreach ($payoutExtrasValues as $payoutExtraValues) {
  2476.                         $array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
  2477.                         $array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
  2478.                         $array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
  2479.                     }
  2480.                 }
  2481.                 $payoutExtrasValues $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
  2482.                 $parametMerchant = [
  2483.                     'MerchantSalesID' => $array['x_reference'],
  2484.                     'Amount' => $array['x_total_amount'],
  2485.                     'transactionUrl' => $transactionUrl,
  2486.                     'dataTrans' => $array,
  2487.                 ];
  2488.                 $safeTyPay $safetyPayController->safetyAction($router$parameterBag$mailer$parametMerchant$array);
  2489.                 if ('ok' == $safeTyPay['status']) {
  2490.                     if ('baloto' == $paymentData->type) {
  2491.                         $cash '&CountryId=COL&ChannelId=CASH';
  2492.                         $session->set($transactionId.'[hotel][retry]'0);
  2493.                         return $this->redirect($safeTyPay['response'].$cash);
  2494.                     } else {
  2495.                         return $this->redirect($safeTyPay['response']);
  2496.                     }
  2497.                 } else {
  2498.                     $emissionData->x_booking $array['x_booking'];
  2499.                     $emissionData->x_first_name $array['x_first_name'];
  2500.                     $emissionData->x_last_name $array['x_last_name'];
  2501.                     $emissionData->x_doc_num $array['x_doc_num'];
  2502.                     $emissionData->x_reference $array['x_reference'];
  2503.                     $emissionData->x_description $array['x_description'];
  2504.                     $emissionData->x_total_amount $array['x_total_amount'];
  2505.                     $emissionData->x_email $array['x_email'];
  2506.                     $emissionData->x_address $array['x_address'];
  2507.                     $emissionData->x_phone $array['x_phone'];
  2508.                     $emissionData->x_type_description $array['x_type_description'];
  2509.                     $emissionData->x_resultSafetyPay $safeTyPay;
  2510.                     $mailInfo print_r($emissionDatatrue).'<br>'.print_r($responsetrue);
  2511.                     $message = (new \Swift_Message())
  2512.                             ->setContentType('text/html')
  2513.                             ->setFrom($session->get('emailNoReply'))
  2514.                             ->setTo($emailNotification)
  2515.                             ->setSubject('Error Creación Token SafetyPay'.$emissionData->x_reference)
  2516.                             ->setBody($mailInfo);
  2517.                     $mailer->send($message);
  2518.                     return $this->redirect($this->generateUrl('aviatur_hotel_payment_rejected_secure'));
  2519.                 }
  2520.             } elseif ('cash' == $paymentData->type) {
  2521.                 $x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
  2522.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2523.                 $agency $this->agency;
  2524.                 $agencyName $agency->getOfficeId();
  2525.                 $array['x_officeId'] = $agencyName;
  2526.                 $array['x_doc_num'] = $customer->getDocumentnumber();
  2527.                 $array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
  2528.                 $array['x_first_name'] = $customer->getFirstname();
  2529.                 $array['x_last_name'] = $customer->getLastname();
  2530.                 $array['x_company'] = 'Aviatur';
  2531.                 $array['x_email'] = $customer->getEmail();
  2532.                 $array['x_address'] = $customer->getAddress();
  2533.                 $array['x_city'] = $customer->getCity()->getDescription();
  2534.                 $array['x_province'] = $customer->getCity()->getDescription();
  2535.                 $array['x_country'] = $customer->getCountry()->getDescription();
  2536.                 $array['x_phone'] = $customer->getPhone();
  2537.                 $array['x_mobile'] = $customer->getCellphone();
  2538.                 $array['x_payment_data'] = $paymentData->type;
  2539.                 $array['x_type_description'] = $orderProduct[0]->getDescription();
  2540.                 $array['x_reference'] = $orderInfo->products;
  2541.                 $array['x_total_amount'] = $x_amount_total >= 100 number_format(round($x_amount_total), 2'.''') : 100;
  2542.                 $array['x_currency'] = (string) $roomRate->TotalAviatur['CurrencyCode'];
  2543.                 $array['x_description'] = $description;
  2544.                 $array['x_booking'] = $orderProduct[0]->getBooking();
  2545.                 if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  2546.                     foreach ($payoutExtrasValues as $payoutExtraValues) {
  2547.                         $array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
  2548.                     }
  2549.                 }
  2550.                 $payoutExtrasValues $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
  2551.                 $fecha $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
  2552.                 $fechalimite $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
  2553.                 $nuevafecha strtotime('+2 hour'strtotime($fecha));
  2554.                 $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  2555.                 if (strcmp($fechavigencia$fechalimite) > 0) {
  2556.                     $fechavigencia $fechalimite;
  2557.                 }
  2558.                 $array['x_fechavigencia'] = $fechavigencia;
  2559.                 $array['x_transactionId'] = $transactionId;
  2560.                 $retryCount = (int) $session->get($transactionId.'[hotel][retry]');
  2561.                 $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  2562.                 $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  2563.                 if ($isMulti) {
  2564.                     return $this->json($array);
  2565.                 } elseif ($session->has($transactionId.'[hotel][detail_cash]')) {
  2566.                     $detail_cash json_decode($session->get($transactionId.'[hotel][detail_cash]'));
  2567.                     if ('error' == $detail_cash->status) {
  2568.                         $cashPay $cashPayController->cashAction($array);
  2569.                     } else {
  2570.                         $cashPay json_decode($session->get($transactionId.'[hotel][detail_cash]'));
  2571.                     }
  2572.                 } else {
  2573.                     $cashPay $cashPayController->cashAction($array);
  2574.                     $session->set($transactionId.'[hotel][detail_cash]'json_encode($cashPay));
  2575.                 }
  2576.                 if ('ok' == $cashPay->status) {
  2577.                     $session->set($transactionId.'[hotel][cash_result]'json_encode($cashPay));
  2578.                     return $this->redirect($this->generateUrl('aviatur_hotel_confirmation_success_secure'));
  2579.                 } else {
  2580.                     $emissionData['x_first_name'] = $array['x_first_name'];
  2581.                     $emissionData['x_last_name'] = $array['x_last_name'];
  2582.                     $emissionData['x_doc_num'] = $array['x_doc_num'];
  2583.                     $emissionData['x_reference'] = $array['x_reference'];
  2584.                     $emissionData['x_description'] = $array['x_description'];
  2585.                     $emissionData['x_total_amount'] = $array['x_total_amount'];
  2586.                     $emissionData['x_email'] = $array['x_email'];
  2587.                     $emissionData['x_address'] = $array['x_address'];
  2588.                     $emissionData['x_phone'] = $array['x_phone'];
  2589.                     $emissionData['x_type_description'] = $array['x_type_description'];
  2590.                     $emissionData['x_error'] = $cashPay->status;
  2591.                     $mailInfo print_r($emissionDatatrue).'<br>'.print_r($cashPaytrue);
  2592.                     $toEmails = ['soportepagoelectronico@aviatur.com.co''soptepagelectronic@aviatur.com'$emailNotification];
  2593.                     $message = (new \Swift_Message())
  2594.                             ->setContentType('text/html')
  2595.                             ->setFrom($session->get('emailNoReply'))
  2596.                             ->setTo($toEmails)
  2597.                             ->setBcc($emailNotification)
  2598.                             ->setSubject('Error Creación Transacción Efectivo'.$emissionData['x_reference'])
  2599.                             ->setBody($mailInfo);
  2600.                     $mailer->send($message);
  2601.                     $session->set($transactionId.'[hotel][retry]'$retryCount 1);
  2602.                     return $this->redirect($this->generateUrl('aviatur_hotel_payment_rejected_secure'));
  2603.                 }
  2604.             } else {
  2605.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''El tipo de pago es invalido'));
  2606.             }
  2607.         } else {
  2608.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''El provedor arrojó un método de pago inesperado'));
  2609.         }
  2610.     }
  2611.     public function p2pCallbackAction(OrderController $orderControllerValidateSanctionsRenewal $validateSanctionsTokenStorageInterface $tokenStorageCustomerMethodPaymentService $customerMethodPaymentAviaturMailer $aviaturMailerPayoutExtraService $payoutExtraServiceAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBagAviaturWebService $aviaturWebServiceRouterInterface $router, \Swift_Mailer $mailer)
  2612.     {
  2613.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2614.         $em $this->managerRegistry;
  2615.         $session $this->session;
  2616.         $transactionId $session->get($transactionIdSessionName);
  2617.         $orderProductCode $session->get($transactionId.'[hotel][order]');
  2618.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  2619.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2620.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  2621.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  2622.         if (null != $decodedResponse) {
  2623.             $agency $orderProduct->getOrder()->getAgency();
  2624.             $prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
  2625.             $twig '';
  2626.             $additionalQS '';
  2627.             $retryCount = (int) $session->get($transactionId.'[hotel][retry]');
  2628.             $jsonSendEmail $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
  2629.             if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
  2630.                 $email json_decode($jsonSendEmail->getDescription())->email->CallBack;
  2631.             }
  2632.             $reference str_replace('{"order":"'''$orderProductCode);
  2633.             $reference str_replace('","products":"''-'$reference);
  2634.             $reference str_replace('"}'''$reference);
  2635.             $references $reference;
  2636.             $bookings $orderProduct->getBooking();
  2637.             switch ($decodedResponse->x_response_code) {
  2638.                 case isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber):
  2639.                     //rechazado cybersource
  2640.                     $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  2641.                     if ($parameters) {
  2642.                         if (== $parameters->getValue()) {
  2643.                             if (== $decodedResponse->x_response_code) {
  2644.                                 $postData json_decode($session->get($transactionId '[hotel][detail_data_hotel]'));
  2645.                                 if (isset($postData->PD->savePaymProc)) {
  2646.                                     $customerLogin $tokenStorage->getToken()->getUser();
  2647.                                     $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2648.                                 }
  2649.                                 if (isset($postData->PD->cusPOptSelected)) {
  2650.                                     if (isset($postData->PD->cusPOptSelectedStatus)) {
  2651.                                         if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  2652.                                             $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  2653.                                             $customerLogin $tokenStorage->getToken()->getUser();
  2654.                                             $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2655.                                         }
  2656.                                     }
  2657.                                 }
  2658.                             }
  2659.                         }
  2660.                     }
  2661.                     // Aquí NO se hace la reserva en ningún caso
  2662.                     // if (($emissionData != 'No Reservation') && ($emissionData != '') && ($emissionData != null)) {
  2663.                     //     $rs = $this->makeReservation($transactionId);
  2664.                     // }
  2665.                     $twig 'aviatur_hotel_payment_rejected_secure';
  2666.                     // no break
  2667.                 case 3:// pendiente p2p
  2668.                     $twig '' != $twig $twig 'aviatur_hotel_payment_pending_secure';
  2669.                     $emissionData 'No Reservation';
  2670.                     $orderProduct->setEmissiondata(json_encode($emissionData));
  2671.                     $orderProduct->setUpdatingdate(new \DateTime());
  2672.                     $em->persist($orderProduct);
  2673.                     $em->flush();
  2674.                     $retryCount 1;
  2675.                     break;
  2676.                 case 0:// error p2p
  2677.                     $twig 'aviatur_hotel_payment_error_secure';
  2678.                     if (isset($email)) {
  2679.                         $from $session->get('emailNoReply');
  2680.                         $error $twig;
  2681.                         $subject $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
  2682.                         $body '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  2683.                         $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  2684.                     }
  2685.                     // no break
  2686.                 case 2:// rechazada p2p
  2687.                     $twig '' != $twig $twig 'aviatur_hotel_payment_rejected_secure';
  2688.                     if (isset($email)) {
  2689.                         $from $session->get('emailNoReply');
  2690.                         $error $twig;
  2691.                         $subject $orderProduct->getDescription().':Transacción rechazada';
  2692.                         $body '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  2693.                         $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  2694.                     }
  2695.                     break;
  2696.                 case 1:// aprobado p2p
  2697.                     $postData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  2698.                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2699.                     if (isset($postData->PD->savePaymProc)) {
  2700.                         $customerLogin $tokenStorage->getToken()->getUser();
  2701.                         $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2702.                     }
  2703.                     if (isset($postData->PD->cusPOptSelected)) {
  2704.                         if (isset($postData->PD->cusPOptSelectedStatus)) {
  2705.                             if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  2706.                                 $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  2707.                                 $customerLogin $tokenStorage->getToken()->getUser();
  2708.                                 $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2709.                             }
  2710.                         }
  2711.                     }
  2712.                     $decodedRequest->product_type 'hotel';
  2713.                     $decodedResponse->product_type 'hotel';
  2714.                     $encodedRequest $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
  2715.                     $encodedResponse $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
  2716.                     $orderProduct->setPayrequest($encodedRequest);
  2717.                     $orderProduct->setPayresponse($encodedResponse);
  2718.                     $twig 'aviatur_hotel_payment_success_secure';
  2719.                     if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
  2720.                         $additionalQS '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
  2721.                     }
  2722.                     //Reemplazar por consumo de reserva!!!!
  2723.                     $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  2724.                     $providerId $provider->getProvideridentifier();
  2725.                     $orderController->updatePaymentAction($orderProductfalsenull);
  2726.                     $rs $this->makeReservation($session$mailer$aviaturWebService$aviaturErrorHandler$router$registry$parameterBag$transactionId1);
  2727.                     $reservationInfo = \simplexml_load_string($session->get($transactionId.'[hotel][reservation]'));
  2728.                     if (isset($reservationInfo->Message->OTA_HotelResRS) && isset($reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'])) {
  2729.                         $reservationId2 $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'];
  2730.                     } else {
  2731.                         $reservationId2 'PN'.$orderProduct->getId();
  2732.                     }
  2733.                     $orderUpdatePayment str_replace(
  2734.                         ['{web_book_id}''{hotel_book_id}'],
  2735.                         ['PN'.$orderProduct->getId(), (string) $reservationId2],
  2736.                         $orderProduct->getUpdatePaymentData()
  2737.                     );
  2738.                     $orderProduct->setUpdatePaymentData($orderUpdatePayment);
  2739.                     $em->persist($orderProduct);
  2740.                     $em->flush();
  2741.                     break;
  2742.             }
  2743.             $payoutExtraService->payoutExtrasCallback($twig$transactionId'hotel'$agency);
  2744.             $session->set($transactionId.'[hotel][retry]'$retryCount 1);
  2745.             $urlResume $this->generateUrl($twig);
  2746.             $urlResume .= $additionalQS;
  2747.             //////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
  2748.             /*
  2749.             if ($session->has('Marked_name') && $session->has('Marked_document')) {
  2750.                 $product = 'Hotel';
  2751.                 $validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
  2752.             }
  2753.             */
  2754.             /* Pero solo si hay condicionados (no bloqueados) y que paguen con Tarjeta */
  2755.             if ($session->has('Marked_users')) {
  2756.                 $product 'Hotel';
  2757.                 $validateSanctions->sendMarkedEmail($orderProductCode$session$agency$orderProduct$transactionId$product);
  2758.             }
  2759.             ////////////////////////////////////////////////////////////////////////////////////
  2760.             return $this->redirect($urlResume);
  2761.         } else {
  2762.             $orderProduct->setStatus('pending');
  2763.             $em->persist($orderProduct);
  2764.             $em->flush();
  2765.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  2766.         }
  2767.     }
  2768.     public function pseCallbackAction(Request $requestConfirmationWebservice $hotelConfirmationWebServicePSEController $psePaymentControllerOrderController $orderControllerPayoutExtraService $payoutExtraServiceAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolderParameterBagInterface $parameterBag$transaction)
  2769.     {
  2770.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2771.         $status null;
  2772.         $twig null;
  2773.         $em $this->managerRegistry;
  2774.         $session $this->session;
  2775.         if ($session->has('agencyId')) {
  2776.             $agency $this->agency;
  2777.         } else {
  2778.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1);
  2779.         }
  2780.         $paymentMethod $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pse');
  2781.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findOneBy(['agency' => $agency'paymentMethod' => $paymentMethod]);
  2782.         $tranKey $paymentMethodAgency->getTrankey();
  2783.         $decodedUrl json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
  2784.         $transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
  2785.         $orders $decodedUrl['x_orders'];
  2786.         if (isset($orders['hotel'])) {
  2787.             $hotelOrders explode('+'$orders['hotel']);
  2788.             $orderProductCode $hotelOrders[0];
  2789.             $productId $hotelOrders[0];
  2790.             $retryCount 1;
  2791.         } else {
  2792.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontro identificador de la transacción'));
  2793.         }
  2794.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2795.         if (empty($orderProduct)) {
  2796.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  2797.         } else {
  2798.             if ('approved' == $orderProduct->getStatus()) {
  2799.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  2800.             }
  2801.             $agency $orderProduct->getOrder()->getAgency();
  2802.             $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  2803.             if (isset($decodedResponse->createTransactionResult)) {
  2804.                 $pseTransactionId $decodedResponse->createTransactionResult->transactionID;
  2805.                 $paymentResponse $psePaymentController->pseCallbackAction($pseTransactionId);
  2806.                 if (!isset($paymentResponse->error)) {
  2807.                     if (!$session->has($transactionId.'[hotel][detail_data_hotel]')) {
  2808.                         $message 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
  2809.                         return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra'$message));
  2810.                     }
  2811.                     $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  2812.                     $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  2813.                     $orderProduct->setUpdatingdate(new \DateTime());
  2814.                     $em->persist($orderProduct);
  2815.                     $em->flush();
  2816.                     if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
  2817.                         switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
  2818.                             case 'OK':
  2819.                                 $twig 'aviatur_hotel_payment_success_secure';
  2820.                                 $status 'approved';
  2821.                                 break;
  2822.                             case 'PENDING':
  2823.                                 $twig 'aviatur_hotel_payment_pending_secure';
  2824.                                 $status 'pending';
  2825.                                 break;
  2826.                             case 'NOT_AUTHORIZED':
  2827.                                 $twig 'aviatur_hotel_payment_error_secure';
  2828.                                 $status 'rejected';
  2829.                                 break;
  2830.                             case 'FAILED':
  2831.                                 $twig 'aviatur_hotel_payment_error_secure';
  2832.                                 $status 'failed';
  2833.                                 break;
  2834.                         }
  2835.                         $orderProduct->setStatus($status);
  2836.                         $orderProduct->getOrder()->setStatus($status);
  2837.                         $orderProduct->setUpdatingdate(new \DateTime());
  2838.                         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  2839.                         $em->persist($orderProduct);
  2840.                         $em->flush();
  2841.                         $payoutExtraService->payoutExtrasCallback($twig$transactionId'hotel'$agency);
  2842.                         if ('approved' == $status) {
  2843.                             //Reemplazar por consumo de reserva!!!!
  2844.                             if ($session->has($transactionId.'[hotel][provider]')) {
  2845.                                 $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  2846.                                 $providerId $provider->getProvideridentifier();
  2847.                             } elseif (isset($decodedUrl['x_providerId'])) {
  2848.                                 $providerId $decodedUrl['x_providerId'];
  2849.                             }
  2850.                             $orderController->updatePaymentAction($orderProductfalsenull);
  2851.                             $request = new \stdClass();
  2852.                             $request->Reserva = (string) $orderProduct->getEmissiondata();
  2853.                             if (isset($providerId) && '58' == $providerId) {
  2854.                                 $request->Expediente 0;
  2855.                                 $request->Usuario 'INTERNET';
  2856.                             }
  2857.                             $hotelConfirmationWebService->callServiceConfirmation('ConfirmarReserva'$request$orderProduct->getId());
  2858.                         }
  2859.                     } elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
  2860.                         echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  2861.         PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  2862.         unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  2863.         forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  2864.         comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  2865.         inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  2866.         transacción <#CUS> .';
  2867.                         $orderProduct->setEmissiondata('error');
  2868.                         $orderProduct->setUpdatingdate(new \DateTime());
  2869.                         $em->persist($orderProduct);
  2870.                         $em->flush();
  2871.                         $twig 'aviatur_hotel_payment_error_secure';
  2872.                     }
  2873.                     if ($session->has($transactionId.'[hotel][retry]')) {
  2874.                         $session->set($transactionId.'[hotel][retry]'$retryCount 1);
  2875.                     }
  2876.                     return $this->redirect($this->generateUrl($twig));
  2877.                 } else {
  2878.                     $decodedResponse->getTransactionInformationResult $paymentResponse;
  2879.                     $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  2880.                     $orderProduct->setUpdatingdate(new \DateTime());
  2881.                     $em->persist($orderProduct);
  2882.                     $em->flush();
  2883.                     return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  2884.                 }
  2885.             } else {
  2886.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  2887.             }
  2888.         }
  2889.     }
  2890.     public function safetyCallbackOkAction(Request $requestSafetypayController $safetyPayControllerConfirmationWebservice $hotelConfirmationWebServiceOrderController $orderControllerPayoutExtraService $payoutExtraServiceAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerAviaturEncoder $aviaturEncoderTwigFolder $twigFolderSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  2891.     {
  2892.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2893.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  2894.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  2895.         $status null;
  2896.         $twig null;
  2897.         $em $this->managerRegistry;
  2898.         $safeTyPay $safetyPayController->safetyok();
  2899.         if (true === $session->has($transactionIdSessionName)) {
  2900.             $transactionId $session->get($transactionIdSessionName);
  2901.             if (true === $session->has($transactionId.'[hotel][order]')) {
  2902.                 $orderProductCode $session->get($transactionId.'[hotel][order]');
  2903.                 $productId str_replace('PN'''json_decode($orderProductCode)->products);
  2904.                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2905.                 $agency $orderProduct->getOrder()->getAgency();
  2906.                 $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  2907.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  2908.                 $payError $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
  2909.                 $notifyError $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
  2910.                 if (isset($decodedResponse->payResponse->OperationResponse)) {
  2911.                     if (== $payError) {
  2912.                         $retryCount = (int) $session->get($transactionId.'[hotel][retry]');
  2913.                         if (== $notifyError) {
  2914.                             switch ($payError) {
  2915.                                 case 0:
  2916.                                     $twig 'aviatur_hotel_payment_success_secure';
  2917.                                     $status 'approved';
  2918.                                     break;
  2919.                                 case 2:
  2920.                                     $twig 'aviatur_hotel_payment_error_secure';
  2921.                                     $status 'failed';
  2922.                                     break;
  2923.                             }
  2924.                             $orderProduct->setStatus($status);
  2925.                             $orderProduct->getOrder()->setStatus($status);
  2926.                             $orderProduct->setUpdatingdate(new \DateTime());
  2927.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  2928.                             $em->persist($orderProduct);
  2929.                             $em->flush();
  2930.                             $orderController->updatePaymentAction($orderProduct);
  2931.                             $payoutExtraService->payoutExtrasCallback($twig$transactionId'hotel'$agency);
  2932.                             if (== $payError) {
  2933.                                 if ('approved' == $status) {
  2934.                                     //Reemplazar por consumo de reserva!!!!
  2935.                                     $hotelModel = new HotelModel();
  2936.                                     $xmlRequestArray $hotelModel->getXmlReservation();
  2937.                                     $xmlRequest $xmlRequestArray[0].$xmlRequestArray['RoomType'][0].$xmlRequestArray['RoomType'][1].$xmlRequestArray['RoomType'][2].$xmlRequestArray[1];
  2938.                                     $detail = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  2939.                                     if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  2940.                                         $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  2941.                                     } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  2942.                                         $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  2943.                                     } else {
  2944.                                         $urlAvailability $session->get($transactionId.'[availability_url]');
  2945.                                     }
  2946.                                     $routeParsed parse_url($urlAvailability);
  2947.                                     $availabilityUrl $router->match($routeParsed['path']);
  2948.                                     $adults 0;
  2949.                                     $childs 0;
  2950.                                     if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  2951.                                         for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  2952.                                             $adults += $availabilityUrl['adult'.$i];
  2953.                                             $childrens = [];
  2954.                                             if ('n' != $availabilityUrl['child'.$i]) {
  2955.                                                 $childAgesTemp explode('-'$availabilityUrl['child'.$i]);
  2956.                                                 $childs += count($childAgesTemp);
  2957.                                             }
  2958.                                         }
  2959.                                     }
  2960.                                     else {
  2961.                                         $data json_decode($session->get($transactionId '[hotel][availability_data_hotel]'));
  2962.                                         if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
  2963.                                             $availabilityData json_decode(base64_decode($data->attributes), true);
  2964.                                         } else {
  2965.                                             $availabilityData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  2966.                                         }
  2967.                                         if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  2968.                                             for ($i 0$i $availabilityData['Rooms']; ++$i) {
  2969.                                                 $adults += $availabilityData['Adults'.$i] ?? 0;
  2970.                                                 if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
  2971.                                                     $childs += $availabilityData['Children'.$i];
  2972.                                                 }
  2973.                                             }
  2974.                                         }
  2975.                                     }
  2976.                                     $hotelCode explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
  2977.                                     $postData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  2978.                                     $passangersData $postData->PI;
  2979.                                     $hotelInformation $postData->HI;
  2980.                                     $ratePlanCode $hotelInformation->ratePlan;
  2981.                                     $gender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData->gender_1_1);
  2982.                                     $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData->nationality_1_1);
  2983.                                     $session->set($transactionId.'[hotel][retry]'$aviaturPaymentRetryTimes);
  2984.                                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2985.                                     $passangersData->DocType_1_1 $passangersData->doc_type_1_1;
  2986.                                     if (false !== strpos($passangersData->first_name_1_1'***')) {
  2987.                                         $passangersData->first_name_1_1 $customer->getFirstname();
  2988.                                         $passangersData->last_name_1_1 $customer->getLastname();
  2989.                                         $passangersData->phone_1_1 $customer->getPhone();
  2990.                                         $passangersData->email_1_1 $customer->getEmail();
  2991.                                         $passangersData->address_1_1 $customer->getAddress();
  2992.                                         $passangersData->doc_num_1_1 $customer->getDocumentnumber();
  2993.                                     }
  2994.                                     $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  2995.                                     $providerId $provider->getProvideridentifier();
  2996.                                     $variable = [
  2997.                                         'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
  2998.                                         'ProviderId' => $providerId,
  2999.                                         'Guest_DocID' => $passangersData->doc_num_1_1,
  3000.                                         'Guest_Name' => $passangersData->first_name_1_1,
  3001.                                         'Guest_Surname' => $passangersData->last_name_1_1,
  3002.                                         'Guest_Datebirth' => $passangersData->birthday_1_1,
  3003.                                         'Guest_Gender' => $gender->getExternalcode(),
  3004.                                         'Guest_Nationality' => $country->getIatacode(),
  3005.                                         'Guest_DocType' => $passangersData->DocType_1_1,
  3006.                                         'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
  3007.                                         'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
  3008.                                         'RatePlanCode' => $ratePlanCode,
  3009.                                         'AmountAfterTax' => number_format($decodedRequest->totalAmount2','''),
  3010.                                         'CurrencyCode' => 'COP',
  3011.                                         'HotelCode' => $hotelCode[0],
  3012.                                         'Rooms' => $availabilityUrl['rooms'] ?? $availabilityData['Rooms'],
  3013.                                         'Adults' => $adults,
  3014.                                         'Children' => $childs,
  3015.                                         'Usuario' => $session->get('domain').'@'.$session->get('domain'),
  3016.                                         'EstadoBD' => 1,
  3017.                                         'BirthDate' => $customer->getBirthdate()->format('Y-m-d'),
  3018.                                         'Gender' => $gender->getExternalcode(),
  3019.                                         'GivenName' => $customer->getFirstname(),
  3020.                                         'Surname' => $customer->getLastname(),
  3021.                                         'PhoneNumber' => $customer->getPhone(),
  3022.                                         'Email' => $customer->getEmail(),
  3023.                                         'AddressLine' => $customer->getAddress(),
  3024.                                         'CityName' => $customer->getCity()->getDescription(),
  3025.                                         'CountryName' => $country->getDescription(),
  3026.                                         'DocID' => $customer->getDocumentnumber(),
  3027.                                     ];
  3028.                                     $request = new \stdClass();
  3029.                                     $request->Reserva = (string) $orderProduct->getEmissiondata();
  3030.                                     if ('58' == $providerId) {
  3031.                                         $request->Expediente 0;
  3032.                                         $request->Usuario 'INTERNET';
  3033.                                     }
  3034.                                     $response $hotelConfirmationWebService->callServiceConfirmation('ConfirmarReserva'$request$orderProduct->getId());
  3035.                                 }
  3036.                             }
  3037.                         } else {
  3038.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  3039.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  3040.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  3041.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  3042.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  3043.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  3044.                             transacción <#CUS> .';
  3045.                             $orderProduct->setEmissiondata('error');
  3046.                             $orderProduct->setUpdatingdate(new \DateTime());
  3047.                             $em->persist($orderProduct);
  3048.                             $em->flush();
  3049.                             $twig 'aviatur_hotel_payment_error_secure';
  3050.                         }
  3051.                         $session->set($transactionId.'[hotel][retry]'$retryCount 1);
  3052.                         return $this->redirect($this->generateUrl($twig));
  3053.                     } else {
  3054.                         $decodedResponse->payResponse->OperationResponse->ListOfOperations $paymentResponse;
  3055.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  3056.                         $orderProduct->setUpdatingdate(new \DateTime());
  3057.                         $em->persist($orderProduct);
  3058.                         $em->flush();
  3059.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  3060.                     }
  3061.                 } else {
  3062.                     return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción, por favor comuniquese con nosotros'));
  3063.                 }
  3064.             } else {
  3065.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  3066.             }
  3067.         } else {
  3068.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontro identificador de la transacción'));
  3069.         }
  3070.     }
  3071.     public function safetyCallbackErrorAction(AviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionTwigFolder $twigFolderParameterBagInterface $parameterBag)
  3072.     {
  3073.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3074.         $status null;
  3075.         $em $this->managerRegistry;
  3076.         $transactionId $session->get($transactionIdSessionName);
  3077.         $retryCount = (int) $session->get($transactionId.'[hotel][retry]');
  3078.         $orderProductCode $session->get($transactionId.'[hotel][order]');
  3079.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  3080.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3081.         $payResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  3082.         $payRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
  3083.         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
  3084.         if ('baloto' == $payRequest->dataTransf->x_payment_data) {
  3085.             $status 'pending';
  3086.             $payResponse->dataTransf->x_response_code 100;
  3087.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
  3088.         } elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
  3089.             $status 'rejected';
  3090.             $payResponse->dataTransf->x_response_code 100;
  3091.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
  3092.         }
  3093.         $orderProduct->setStatus($status);
  3094.         $orderProduct->setUpdatingdate(new \DateTime());
  3095.         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  3096.         $order $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
  3097.         $order->setStatus($status);
  3098.         $em->persist($order);
  3099.         $em->persist($orderProduct);
  3100.         $em->flush();
  3101.         if (true === $session->has($transactionId.'[hotel][order]')) {
  3102.             $orderProductCode $session->get($transactionId.'[hotel][order]');
  3103.         } else {
  3104.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  3105.         }
  3106.         $session->set($transactionId.'[hotel][retry]'$retryCount 1);
  3107.         return $this->redirect($this->generateUrl('aviatur_hotel_payment_rejected_secure'));
  3108.     }
  3109.     public function worldCallbackAction(Request $requestConfirmationWebservice $hotelConfirmationWebServiceOrderController $orderControllerPayoutExtraService $payoutExtraServiceAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerAviaturEncoder $aviaturEncoderSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  3110.     {
  3111.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3112.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  3113.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  3114.         $em $this->managerRegistry;
  3115.         $transactionId $session->get($transactionIdSessionName);
  3116.         $orderProductCode $session->get($transactionId.'[hotel][order]');
  3117.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  3118.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3119.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  3120.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  3121.         if (null != $decodedResponse) {
  3122.             $agency $orderProduct->getOrder()->getAgency();
  3123.             $prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
  3124.             $twig 'aviatur_hotel_payment_rejected_secure';
  3125.             $retryCount = (int) $session->get($transactionId.'[hotel][retry]');
  3126.             if (isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber)) {
  3127.                 $decodedResponse->x_response_code_case 99;
  3128.             } else {
  3129.                 if (isset($decodedResponse->resultado->reply->orderStatus->payment->lastEvent)) {
  3130.                     $decodedResponse->x_response_code_case = (string) $decodedResponse->resultado->reply->orderStatus->payment->lastEvent;
  3131.                 } elseif (isset($decodedResponse->resultado->reply->orderStatusEvent->payment->lastEvent)) {
  3132.                     $decodedResponse->x_response_code_case 'REFUSED';
  3133.                 } elseif (isset($decodedResponse->resultado->reply->error)) {
  3134.                     $decodedResponse->x_response_code_case 'REFUSED';
  3135.                 }
  3136.             }
  3137.             switch ($decodedResponse->x_response_code_case) {
  3138.                 case 99:
  3139.                     $twig 'aviatur_hotel_payment_rejected_secure';
  3140.                     break;
  3141.                 case 'ERROR':
  3142.                     $twig 'aviatur_hotel_payment_error_secure';
  3143.                     break;
  3144.                 case 'AUTHORISED':
  3145.                     $decodedRequest->product_type 'hotel';
  3146.                     $decodedResponse->product_type 'hotel';
  3147.                     $encodedRequest $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
  3148.                     $encodedResponse $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
  3149.                     $orderProduct->setPayrequest($encodedRequest);
  3150.                     $orderProduct->setPayresponse($encodedResponse);
  3151.                     $twig 'aviatur_hotel_payment_success_secure';
  3152.                     //Reemplazar por consumo de reserva!!!!
  3153.                     $hotelModel = new HotelModel();
  3154.                     $xmlRequestArray $hotelModel->getXmlReservation();
  3155.                     $detail = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  3156.                     if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  3157.                         $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  3158.                     } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  3159.                         $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  3160.                     } else {
  3161.                         $urlAvailability $session->get($transactionId.'[availability_url]');
  3162.                     }
  3163.                     $routeParsed parse_url($urlAvailability);
  3164.                     $availabilityUrl $router->match($routeParsed['path']);
  3165.                     $adults 0;
  3166.                     $childs 0;
  3167.                     if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  3168.                         for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  3169.                             $adults += $availabilityUrl['adult'.$i];
  3170.                             $childrens = [];
  3171.                             if ('n' != $availabilityUrl['child'.$i]) {
  3172.                                 $childAgesTemp explode('-'$availabilityUrl['child'.$i]);
  3173.                                 $childs += count($childAgesTemp);
  3174.                             }
  3175.                         }
  3176.                     }
  3177.                     else {
  3178.                         $data json_decode($session->get($transactionId '[hotel][availability_data_hotel]'));
  3179.                         if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
  3180.                             $availabilityData json_decode(base64_decode($data->attributes), true);
  3181.                         } else {
  3182.                             $availabilityData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  3183.                         }
  3184.                         if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  3185.                             for ($i 0$i $availabilityData['Rooms']; ++$i) {
  3186.                                 $adults += $availabilityData['Adults'.$i] ?? 0;
  3187.                                 if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
  3188.                                     $childs += $availabilityData['Children'.$i];
  3189.                                 }
  3190.                             }
  3191.                         }
  3192.                 }
  3193.                     $hotelCode explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
  3194.                     $postData json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  3195.                     $passangersData $postData->PI;
  3196.                     $hotelInformation $postData->HI;
  3197.                     $ratePlanCode $hotelInformation->ratePlan;
  3198.                     $gender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData->gender_1_1);
  3199.                     $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData->nationality_1_1);
  3200.                     $session->set($transactionId.'[hotel][retry]'$aviaturPaymentRetryTimes);
  3201.                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  3202.                     $passangersData->DocType_1_1 $passangersData->doc_type_1_1;
  3203.                     if (false !== strpos($passangersData->first_name_1_1'***')) {
  3204.                         $passangersData->first_name_1_1 $customer->getFirstname();
  3205.                         $passangersData->last_name_1_1 $customer->getLastname();
  3206.                         $passangersData->phone_1_1 $customer->getPhone();
  3207.                         $passangersData->email_1_1 $customer->getEmail();
  3208.                         $passangersData->address_1_1 $customer->getAddress();
  3209.                         $passangersData->doc_num_1_1 $customer->getDocumentnumber();
  3210.                     }
  3211.                     $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
  3212.                     $providerId $provider->getProvideridentifier();
  3213.                     $variable = [
  3214.                         'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
  3215.                         'ProviderId' => $providerId,
  3216.                         'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
  3217.                         'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
  3218.                         'RatePlanCode' => $ratePlanCode,
  3219.                         'AmountAfterTax' => number_format($decodedRequest->x_amount2','''),
  3220.                         'CurrencyCode' => 'COP',
  3221.                         'HotelCode' => $hotelCode[0],
  3222.                         'Rooms' => $availabilityUrl['rooms'] ?? $availabilityData['Rooms'],
  3223.                         'Adults' => $adults,
  3224.                         'Children' => $childs,
  3225.                         'Usuario' => $session->get('domain').'@'.$session->get('domain'),
  3226.                         'EstadoBD' => 1,
  3227.                         'BirthDate' => $customer->getBirthdate()->format('Y-m-d'),
  3228.                         'Gender' => $gender->getExternalcode(),
  3229.                         'GivenName' => $customer->getFirstname(),
  3230.                         'Surname' => $customer->getLastname(),
  3231.                         'PhoneNumber' => $customer->getPhone(),
  3232.                         'Email' => $customer->getEmail(),
  3233.                         'AddressLine' => $customer->getAddress(),
  3234.                         'CityName' => $customer->getCity()->getDescription(),
  3235.                         'CountryName' => $country->getDescription(),
  3236.                         'DocID' => $customer->getDocumentnumber(),
  3237.                     ];
  3238.                     $search = [
  3239.                         '{Guest_DocID}',
  3240.                         '{Guest_Name}',
  3241.                         '{Guest_Surname}',
  3242.                         '{Guest_Datebirth}',
  3243.                         '{Guest_Gender}',
  3244.                         '{Guest_Nationality}',
  3245.                         '{Guest_DocType}',
  3246.                         '{Guest_Type}',
  3247.                         '{Guest_Email}',
  3248.                         '{Guest_Phone}',
  3249.                     ];
  3250.                     $replace = [];
  3251.                     $xmlRequest $xmlRequestArray[0];
  3252.                     $xmlRequest .= $xmlRequestArray['RoomType'][0];
  3253.                     $passangersDataArray json_decode(json_encode($passangersData), true);
  3254.                     $totalGuests $passangersDataArray['person_count_1']; //$postDataArray['Adults'] + $postDataArray['Children'];
  3255.                     for ($i 1$i <= $totalGuests; ++$i) {
  3256.                         $gender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersDataArray['gender_1'.'_'.$i]);
  3257.                         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersDataArray['nationality_1'.'_'.$i]);
  3258.                         $replace = [
  3259.                             '{doc_num_1'.'_'.$i.'}',
  3260.                             '{first_name_1'.'_'.$i.'}',
  3261.                             '{last_name_1'.'_'.$i.'}',
  3262.                             '{birthday_1'.'_'.$i.'}',
  3263.                             '{gender_1'.'_'.$i.'}',
  3264.                             '{nationality_1'.'_'.$i.'}',
  3265.                             '{DocType_1'.'_'.$i.'}',
  3266.                             '{passanger_type_1'.'_'.$i.'}',
  3267.                             (== $i) ? $passangersDataArray['email_1_1'] : '',
  3268.                             (== $i) ? $postData->CD->phone '',
  3269.                         ];
  3270.                         $xmlRequest .= str_replace($search$replace$xmlRequestArray['RoomType'][1]);
  3271.                         $passangersDataArray['DocType_1'.'_'.$i] = $passangersDataArray['doc_type_1'.'_'.$i];
  3272.                         $variable['doc_num_1'.'_'.$i] = $passangersDataArray['doc_num_1'.'_'.$i];
  3273.                         $variable['first_name_1'.'_'.$i] = $passangersDataArray['first_name_1'.'_'.$i];
  3274.                         $variable['last_name_1'.'_'.$i] = $passangersDataArray['last_name_1'.'_'.$i];
  3275.                         $variable['birthday_1'.'_'.$i] = $passangersDataArray['birthday_1'.'_'.$i];
  3276.                         $variable['gender_1'.'_'.$i] = $gender->getExternalcode();
  3277.                         $variable['nationality_1'.'_'.$i] = $country->getIatacode();
  3278.                         $variable['DocType_1'.'_'.$i] = $passangersDataArray['DocType_1'.'_'.$i];
  3279.                         $variable['passanger_type_1'.'_'.$i] = $passangersDataArray['passanger_type_1'.'_'.$i];
  3280.                     }
  3281.                     $xmlRequest .= $xmlRequestArray['RoomType'][2];
  3282.                     $xmlRequest .= $xmlRequestArray[1];
  3283.                     $orderController->updatePaymentAction($orderProductfalsenull);
  3284.                     $request = new \stdClass();
  3285.                     $request->Reserva = (string) $orderProduct->getEmissiondata();
  3286.                     if ('58' == $providerId) {
  3287.                         $request->Expediente 0;
  3288.                         $request->Usuario 'INTERNET';
  3289.                     }
  3290.                     $response $hotelConfirmationWebService->callServiceConfirmation('ConfirmarReserva'$request$orderProduct->getId());
  3291.                     break;
  3292.                 case 'REFUSED':
  3293.                     $twig 'aviatur_hotel_payment_rejected_secure';
  3294.                     break;
  3295.                 default:
  3296.                     $twig 'aviatur_hotel_payment_pending_secure';
  3297.                     $emissionData 'No Reservation';
  3298.                     $orderProduct->setEmissiondata(json_encode($emissionData));
  3299.                     $orderProduct->setUpdatingdate(new \DateTime());
  3300.                     $em->persist($orderProduct);
  3301.                     $em->flush();
  3302.                     $retryCount 1;
  3303.                     break;
  3304.             }
  3305.             $payoutExtraService->payoutExtrasCallback($twig$transactionId'hotel'$agency);
  3306.             $session->set($transactionId.'[hotel][retry]'$retryCount 1);
  3307.             return $this->redirect($this->generateUrl($twig));
  3308.         } else {
  3309.             $orderProduct->setStatus('pending');
  3310.             $em->persist($orderProduct);
  3311.             $em->flush();
  3312.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  3313.         }
  3314.     }
  3315.     public function paymentOutputAction(Request $requestExceptionLog $exceptionLog, \Swift_Mailer $mailerAviaturPixeles $aviaturPixelesPdf $pdfAuthorizationCheckerInterface $authorizationCheckerRouterInterface $routerAviaturEncoder $aviaturEncoderTwigFolder $twigFolderParameterBagInterface $parameterBag)
  3316.     {
  3317.         $projectDir $parameterBag->get('kernel.project_dir');
  3318.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3319.         $emailNotification $parameterBag->get('email_notification');
  3320.         $clientFranquice = [];
  3321.         $paymentResume = [];
  3322.         $voucherFile null;
  3323.         $em $this->managerRegistry;
  3324.         $session $this->session;
  3325.         $agency $this->agency;
  3326.         $transactionId $session->get($transactionIdSessionName);
  3327.         $travellerInfo json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
  3328.         if ($session->has($transactionId.'[crossed]'.'[url-hotel]') && !$session->has($transactionId.'[multi]'.'[validation]')) {
  3329.             $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  3330.         } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  3331.             $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  3332.         } else {
  3333.             $urlAvailability $session->get($transactionId.'[availability_url]');
  3334.         }
  3335.         $routeParsed parse_url($urlAvailability);
  3336.         if ($session->has($transactionId.'external')) {
  3337.             $routeParsed['path'] = $session->get('routePath');
  3338.         }
  3339.         $availabilityUrl $router->match($routeParsed['path']);
  3340.         $traveller = [];
  3341.         $traveller['firstName'] = $travellerInfo->PI->first_name_1_1;
  3342.         $traveller['lastName'] = $travellerInfo->PI->last_name_1_1;
  3343.         if (false !== strpos($traveller['firstName'], '*')) {
  3344.             $postDataJson $session->get($transactionId.'[hotel][detail_data_hotel]');
  3345.             $paymentData json_decode($postDataJson);
  3346.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->BD->id);
  3347.             $traveller['firstName'] = $customer->getFirstname();
  3348.             $traveller['lastName'] = $customer->getLastname();
  3349.         }
  3350.         $orderProductCode $session->get($transactionId.'[hotel][order]');
  3351.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  3352.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3353.         $emailData json_decode($orderProduct->getEmail(), true);
  3354.         if ($session->has($transactionId.'[hotel][reservation]')) {
  3355.             $reservationInfo = \simplexml_load_string($session->get($transactionId.'[hotel][reservation]'));
  3356.             $reservationId = (string) $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->UniqueID['ID'];
  3357.             $reservationId2 = (string) $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'];
  3358.             $traveller['ReservationID'] = $reservationId;
  3359.             $traveller['HotelReservationID'] = $reservationId2;
  3360.             if (('' == $emailData['journeySummary']['phone']) && isset($reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers) && isset($reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'])) {
  3361.                 $emailData['journeySummary']['phone'] = (string) $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'];
  3362.             }
  3363.         } else {
  3364.             $traveller['ReservationID'] = null;
  3365.         }
  3366.         $rooms = [];
  3367.         $response = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  3368.         foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
  3369.             if ($roomRatePlan['RatePlanCode'] == $travellerInfo->HI->ratePlan) {
  3370.                 $i 1;
  3371.                 foreach ($roomRatePlan->Rates->Rate as $roomRateText) {
  3372.                     for ($j 0$j < ((int) $roomRateText['NumberOfUnits']); ++$j) {
  3373.                         $rooms[$j $i]['text'] = (string) $roomRateText->RateDescription->Text;
  3374.                         break;
  3375.                     }
  3376.                     $i $i $j;
  3377.                 }
  3378.                 $rooms[1]['roomRates'] = $roomRatePlan;
  3379.                 $rooms[1]['fullPricing'] = json_decode(base64_decode((string) $roomRatePlan->TotalAviatur['FullPricing']), true);
  3380.             }
  3381.         }
  3382.         $adults 0;
  3383.         $childs 0;
  3384.         // Implementar logica para obtener el numero de adultos y niños en Tu Plus
  3385.         if (!$agency->getName() === 'QA Aval') {
  3386.             if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  3387.                 for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  3388.                     $adults += $availabilityUrl['adult' $i];
  3389.                     $childrens = [];
  3390.                     if ('n' != $availabilityUrl['child' $i]) {
  3391.                         $childAgesTemp explode('-'$availabilityUrl['child' $i]);
  3392.                         $childs += count($childAgesTemp);
  3393.                     }
  3394.                 }
  3395.             } else {
  3396.                 $availabilityData json_decode($session->get($transactionId '[hotel][availability_data_hotel]'), TRUE);
  3397.                 if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  3398.                     for ($i 0$i $availabilityData['Rooms']; ++$i) {
  3399.                         $adults += $availabilityData['Adults' $i] ?? 0;
  3400.                         if (isset($availabilityData['Children' $i]) && $availabilityData['Children' $i] > 0) {
  3401.                             $childs += $availabilityData['Children' $i];
  3402.                         }
  3403.                     }
  3404.                 }
  3405.             }
  3406.         } else {
  3407.             for ($i 1$i <= $availabilityUrl['rooms']; $i++) {
  3408.                 if ($availabilityUrl['child' $i] == "n") {
  3409.                     $rooms[$i]['child'] = 0;
  3410.                 } else {
  3411.                     $rooms[$i]['child'] = substr_count($availabilityUrl['child' $i], '-') + 1;
  3412.                     $rooms[$i]['childAges'] = $availabilityUrl['child' $i];
  3413.                 }
  3414.                 $rooms[$i]['adult'] = $availabilityUrl['adult' $i];
  3415.             }
  3416.         }
  3417.         $postDataJson $session->get($transactionId.'[hotel][detail_data_hotel]');
  3418.         $paymentData json_decode($postDataJson);
  3419.         $opRequestInitial json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  3420.         $opRequest $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
  3421.         $opResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  3422.         //Destroy session URL TripAdvisor
  3423.         if ($session->has($transactionId.'external')) {
  3424.             $session->remove($transactionId.'external');
  3425.         }
  3426.         if ((null != $opRequest) && (null != $opResponse)) {
  3427.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->BD->id);
  3428.             if (isset($opResponse->x_description)) {
  3429.                 $paymentResume = [
  3430.                     'transaction_state' => $opResponse->x_response_code,
  3431.                     'ta_transaction_state' => $opResponse->x_ta_response_code,
  3432.                     'id' => $orderProduct->getBooking(),
  3433.                     'id_context' => $opRequest->x_invoice_num,
  3434.                     'total_amount' => $opResponse->x_amount,
  3435.                     'currency' => $opResponse->x_bank_currency,
  3436.                     'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  3437.                     'iva' => $opRequest->x_tax,
  3438.                     'ip_address' => $opRequest->x_customer_ip,
  3439.                     'bank_name' => $opResponse->x_bank_name,
  3440.                     'cuotas' => $opRequest->x_differed,
  3441.                     'card_num' => '************'.substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  3442.                     'reference' => $opResponse->x_transaction_id,
  3443.                     'auth' => $opResponse->x_approval_code,
  3444.                     'transaction_date' => $opResponse->x_transaction_date,
  3445.                     'description' => $opResponse->x_description,
  3446.                     'reason_code' => $opResponse->x_response_reason_code,
  3447.                     'reason_description' => $opResponse->x_response_reason_text,
  3448.                     'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
  3449.                     'client_email' => $opResponse->x_email,
  3450.                 ];
  3451.             } elseif (isset($opRequest->dataTransf)) {
  3452.                 if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
  3453.                     $state $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
  3454.                 if (102 == $state):
  3455.                         $state 1;
  3456.                 $reason_description 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
  3457.                         $state 2;
  3458.                 $reason_description 'Transacción creada';
  3459.                 endif;
  3460.                 $paymentResume = [
  3461.                         'transaction_state' => $state,
  3462.                         'id' => $orderProduct->getBooking(),
  3463.                         'currency' => $opRequest->dataTransf->x_currency,
  3464.                         'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
  3465.                         'amount' => null,
  3466.                         'iva' => null,
  3467.                         'ip_address' => $opRequest->dataTransf->dirIp,
  3468.                         'airport_tax' => null,
  3469.                         'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
  3470.                         'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
  3471.                         'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
  3472.                         'description' => $opRequest->dataTransf->x_description,
  3473.                         'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
  3474.                         'reason_description' => $reason_description,
  3475.                         'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  3476.                         'client_email' => $opRequest->dataTransf->x_email,
  3477.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  3478.                         'client_franquice' => ['description' => 'SafetyPay'],
  3479.                     ]; else:
  3480.                     $paymentResume = [
  3481.                         'transaction_state' => 2,
  3482.                         'id' => $orderProduct->getBooking(),
  3483.                         'currency' => $opRequest->dataTransf->x_currency,
  3484.                         'total_amount' => $opRequest->dataTransf->x_total_amount,
  3485.                         'amount' => null,
  3486.                         'iva' => null,
  3487.                         'ip_address' => $opRequest->dataTransf->dirIp,
  3488.                         'airport_tax' => null,
  3489.                         'reference' => $opRequest->dataTransf->x_reference,
  3490.                         'auth' => null,
  3491.                         'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
  3492.                         'description' => $opRequest->dataTransf->x_description,
  3493.                         'reason_code' => 101,
  3494.                         'reason_description' => 'Transacción creada',
  3495.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  3496.                         'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  3497.                         'client_email' => $opRequest->dataTransf->x_email,
  3498.                     ];
  3499.                 endif;
  3500.                 if ('baloto' == $opRequest->dataTransf->x_payment_data) {
  3501.                     $paymentResume['transaction_state'] = 3;
  3502.                 }
  3503.             } elseif (isset($opRequest->infoCash)) {
  3504.                 $paymentResume = [
  3505.                     'transaction_state' => 2,
  3506.                     'id' => $orderProduct->getBooking(),
  3507.                     'id_context' => $opRequest->infoCash->x_reference,
  3508.                     'currency' => $opRequest->infoCash->x_currency,
  3509.                     'total_amount' => $opRequest->infoCash->x_total_amount,
  3510.                     'client_franquice' => ['description' => 'Efectivo'],
  3511.                     'amount' => null,
  3512.                     'iva' => null,
  3513.                     'ip_address' => $opRequest->infoCash->dirIp,
  3514.                     'airport_tax' => null,
  3515.                     'reference' => $opRequest->infoCash->x_reference,
  3516.                     'auth' => null,
  3517.                     'transaction_date' => $opRequest->infoCash->x_fechavigencia,
  3518.                     'description' => $opRequest->infoCash->x_description,
  3519.                     'reason_code' => 101,
  3520.                     'reason_description' => 'Transacción creada',
  3521.                     'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
  3522.                     'client_email' => $opRequest->infoCash->x_email,
  3523.                     'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
  3524.                 ];
  3525.                 $cash_result json_decode($session->get($transactionId.'[hotel][cash_result]'));
  3526.                 $paymentResume['transaction_state'] = 3;
  3527.                 if ('' == $cash_result) {
  3528.                     $paymentResume['transaction_state'] = 2;
  3529.                 }
  3530.             } else {
  3531.                 $bank_info $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
  3532.                 $bank_name $bank_info->getName();
  3533.                 $clientFranquice['description'] = 'PSE';
  3534.                 $paymentResume = [
  3535.                     'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
  3536.                     'id' => $orderProduct->getBooking(),
  3537.                     'id_context' => $opRequest->reference,
  3538.                     'currency' => $opRequest->currency,
  3539.                     'total_amount' => $opRequest->totalAmount,
  3540.                     'amount' => $opRequest->devolutionBase,
  3541.                     'iva' => $opRequest->taxAmount,
  3542.                     'ip_address' => $opRequest->ipAddress,
  3543.                     'bank_name' => $bank_name,
  3544.                     'client_franquice' => $clientFranquice,
  3545.                     'reference' => $opResponse->createTransactionResult->transactionID,
  3546.                     'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
  3547.                     'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
  3548.                     'description' => $opRequest->description,
  3549.                     'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
  3550.                     'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
  3551.                     'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
  3552.                     'client_email' => $opRequest->payer->emailAddress,
  3553.                 ];
  3554.             }
  3555.         } else {
  3556.             $customer null;
  3557.             $paymentResume['id'] = $orderProduct->getBooking();
  3558.         }
  3559.         if (isset($opRequest->redemptionPoints)) {
  3560.             $paymentResume['pointsRedemption'] = $opRequest->redemptionPoints;
  3561.         }
  3562.         if (isset($opRequest->onlyRedemption)) {
  3563.             $paymentResume['onlyRedemption'] = true;
  3564.         }
  3565.         $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  3566.         if (false !== strpos($paymentData->BD->first_name'***')) {
  3567.             $facturationResume = [
  3568.                 'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  3569.                 'customer_address' => $customer->getAddress(),
  3570.                 'customer_doc_num' => $customer->getDocumentnumber(),
  3571.                 'customer_phone' => $customer->getPhone(),
  3572.                 'customer_email' => $customer->getEmail(),
  3573.             ];
  3574.         } else {
  3575.             $facturationResume = [
  3576.                 'customer_names' => $paymentData->BD->first_name.' '.$paymentData->BD->last_name,
  3577.                 'customer_address' => $paymentData->BD->address ?? null,
  3578.                 'customer_doc_num' => $paymentData->BD->doc_num,
  3579.                 'customer_phone' => $paymentData->BD->phone,
  3580.                 'customer_email' => $paymentData->BD->email ?? null,
  3581.             ];
  3582.         }
  3583.         $clientFranquice '';
  3584.         $retryCount = (int) $session->get($transactionId.'[hotel][retry]');
  3585.         if ($session->has($transactionId.'[user]')) {
  3586.             $responseOrder = \simplexml_load_string($session->get($transactionId.'[user]'));
  3587.         } else {
  3588.             $responseOrder null;
  3589.         }
  3590.         $emailData += [
  3591.             'retry_count' => $retryCount,
  3592.             'paymentResume' => $paymentResume,
  3593.             'currency' => isset($paymentResume['currency']) ? $paymentResume['currency'] : '',
  3594.             'facturationResume' => $facturationResume,
  3595.             'agencyData' => $emailData['agencyData'],
  3596.             'journeySummary' => $emailData['journeySummary'],
  3597.             'transactionID' => $transactionId,
  3598.             'rooms' => $rooms,
  3599.             'traveller' => $traveller,
  3600.             'ratePlan' => $travellerInfo->HI->ratePlan,
  3601.             'agent' => $responseOrder,
  3602.         ];
  3603.         //validacion de parametros vacios usando en twig
  3604.         $emailData["paymentResume"]["reason_description"] = isset($emailData["paymentResume"]["reason_description"]) ? $emailData["paymentResume"]["reason_description"] : "";
  3605.         $emailData["paymentResume"]["auth"] = isset($emailData["paymentResume"]["auth"]) ? $emailData["paymentResume"]["auth"] : "";
  3606.         $emailData["paymentResume"]["reason_code"] = isset($emailData["paymentResume"]["reason_code"]) ? $emailData["paymentResume"]["reason_code"] : "";
  3607.         $emailData["paymentResume"]["reference"] = isset($emailData["paymentResume"]["reference"]) ? $emailData["paymentResume"]["reference"] : "";
  3608.         $emailData["paymentResume"]["total_amount"] = isset($emailData["paymentResume"]["total_amount"]) ? $emailData["paymentResume"]["total_amount"] : "";
  3609.         $emailData["paymentResume"]["currency"] = isset($emailData["paymentResume"]["currency"]) ? $emailData["paymentResume"]["currency"] : "";
  3610.         $orderProduct->setEmail(json_encode($emailData));
  3611.         $em->persist($orderProduct);
  3612.         $em->flush();
  3613.         $isFront $session->has('operatorId');
  3614.         $pixelInfo = [];
  3615.         $routeName $request->get('_route');
  3616.         if (!$isFront) {
  3617.             // PIXELES INFORMATION
  3618.             if (!$session->has('operatorId') && == $paymentResume['transaction_state']) {
  3619.                 $pixel json_decode($session->get($transactionId.'[pixeles_info]'), true);
  3620.                 $pixel['partner_datalayer']['event'] = 'hotelPurchase';
  3621.                 if (!isset($emailData['rooms'][1]['child'], $emailData['rooms'][1]['adult'])){
  3622.                     $quantity json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  3623.                 }
  3624.                 $products = [
  3625.                     'actionField' => "{'id': '".$paymentResume['id_context']."', 'affiliation': 'Portal Web', 'revenue': '".$paymentResume['total_amount']."', 'tax':'".$paymentResume['iva']."', 'coupon': ''}",
  3626.                     'name' => $emailData['journeySummary']['hotelName'],
  3627.                     'price' => $paymentResume['total_amount'],
  3628.                     'brand' => $emailData['journeySummary']['hotelName'],
  3629.                     'category' => 'Hotel',
  3630.                     'variant' => $emailData['rooms'][1]['text'] ?? '',
  3631.                     'quantity' => isset($emailData['rooms'][1]['child'], $emailData['rooms'][1]['adult'])
  3632.                     ? ($emailData['rooms'][1]['child'] + $emailData['rooms'][1]['adult'])
  3633.                     : (($quantity['Children'] ?? 0) + ($quantity['Adults'] ?? 0)),
  3634.                 ];
  3635.                 unset($pixel['partner_datalayer']['ecommerce']['checkout']);
  3636.                 $pixel['partner_datalayer']['ecommerce']['purchase']['products'] = $products;
  3637.                 //$pixel['dataxpand'] = true;
  3638.                 //$pixel['pickback'] = true;
  3639.                 if ($session->get($transactionId.'[hotel][kayakclickid]')) {
  3640.                     $pixel['kayakclickid'] = $session->get($transactionId.'[hotel][kayakclickid]');
  3641.                     if (isset($pixel['kayakclickid']) && 'aviatur_hotel_payment_success_secure' == $routeName) {
  3642.                         $kayakclickid = [
  3643.                             'kayakclickid' => $pixel['kayakclickid'],
  3644.                             'price' => $paymentResume['total_amount'],
  3645.                             'currency' => $paymentResume['currency'],
  3646.                             'confirmation' => $paymentResume['id_context'],
  3647.                             'rand' => microtime(true),
  3648.                         ];
  3649.                         $pixel['kayakclickid'] = $kayakclickid;
  3650.                     }
  3651.                 }
  3652.                 $pixelInfo $aviaturPixeles->verifyPixeles($pixel'hotel''resume'$agency->getAssetsFolder(), false);
  3653.             }
  3654.         }
  3655.         $agencyFolder $twigFolder->twigFlux();
  3656.         $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/resume.html.twig');
  3657.         $emailData['journeySummary']['infoDataFlight'] = json_decode($session->get($transactionId.'[crossed]'.'[infoDataFlight]'), true);
  3658.         /*         * *
  3659.          * Agente Octopus
  3660.          * Cambiar logo Correo Gracias por su compra.
  3661.          */
  3662.         $isAgent false;
  3663.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
  3664.             $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  3665.             if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
  3666.                 $isAgent true;
  3667.                 $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  3668.                 $idAgentLogo $agent->getId();
  3669.                 $folderImg 'assets/octopus_assets/img/custom/logoAgent/'.$idAgentLogo.'.png';
  3670.                 $domain 'https://'.$agency->getDomain();
  3671.                 $folderLogoAgent $domain.'/'.$folderImg;
  3672.                 if (file_exists($folderImg)) {
  3673.                     $emailData['imgLogoAgent'] = $folderLogoAgent;
  3674.                 }
  3675.             }
  3676.         }
  3677.         if ((('aviatur_hotel_payment_success_secure' == $routeName) || ('aviatur_hotel_reservation_success_secure' == $routeName)) && !$session->has($transactionId.'[multi][detail_cash]')) {
  3678.             $voucherFile $projectDir.'/app/serviceLogs/HotelVoucher/ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId().'_'.$transactionId.'.pdf';
  3679.             if (!file_exists($voucherFile)) {
  3680.                 $bccMails = [$agency->getMailvouchers()];
  3681.                 if (!$isFront) {
  3682.                     $emissionData $orderProduct->getEmissiondata();
  3683.                     if (('No Reservation' != $emissionData) && ('' != $emissionData) && (null != $emissionData)) {
  3684.                         $setTo = (null == $customer) ? null $customer->getEmail();
  3685.                     } else {
  3686.                         $setTo 'soptepagelectronic@aviatur.com';
  3687.                     }
  3688.                     if ($session->has('whitemark')) {
  3689.                         if ('' != $session->get('whitemarkMail')) {
  3690.                             $bccMails[] = $session->get('whitemarkMail');
  3691.                             $bccMails[] = 'sebastian.huertas@aviatur.com';
  3692.                         }
  3693.                     }
  3694.                     try {
  3695.                         $infoPdfHotel = ['retry_count' => $retryCount,
  3696.                             'paymentResume' => $paymentResume,
  3697.                             'facturationResume' => $facturationResume,
  3698.                             'agencyData' => $emailData['agencyData'],
  3699.                             'journeySummary' => $emailData['journeySummary'],
  3700.                             'transactionID' => $transactionId,
  3701.                             'rooms' => $rooms,
  3702.                             'traveller' => $traveller,
  3703.                             'agent' => $responseOrder,
  3704.                             'pdfGenerator' => true,
  3705.                             // dd($rooms),
  3706.                         ];
  3707.                         if ($isAgent) {
  3708.                             $infoPdfHotel['imgLogoAgent'] = $emailData['imgLogoAgent'];
  3709.                         }
  3710.                         $pdf->generateFromHtml(
  3711.                             $this->renderView($urlResume$infoPdfHotel),
  3712.                             $voucherFile
  3713.                         );
  3714.                         $bccMails[] = 'supervisorescallcenter@aviatur.com';
  3715.                         $setSubject 'Gracias por su compra';
  3716.                         $message = (new \Swift_Message())
  3717.                                 ->setContentType('text/html')
  3718.                                 ->setFrom($session->get('emailNoReply'))
  3719.                                 ->setTo($setTo)
  3720.                                 ->setBcc($bccMails)
  3721.                                 ->setSubject($session->get('agencyShortName').' - '.$setSubject)
  3722.                                 ->attach(\Swift_Attachment::fromPath($voucherFile))
  3723.                                 ->setBody(
  3724.                                     $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
  3725.                                 );
  3726.                     } catch (\Exception $e) {
  3727.                         $bccMails[] = 'lida.lugo@aviatur.com';
  3728.                         $emissionData $orderProduct->getEmissiondata();
  3729.                         if (('No Reservation' != $emissionData) && ('' != $emissionData) && (null != $emissionData)) {
  3730.                             $setTo = (null == $customer) ? null $customer->getEmail();
  3731.                         } else {
  3732.                             $setTo 'soptepagelectronic@aviatur.com';
  3733.                         }
  3734.                         $setSubject 'Gracias por su compra';
  3735.                         if (file_exists($voucherFile)) {
  3736.                             $message = (new \Swift_Message())
  3737.                                     ->setContentType('text/html')
  3738.                                     ->setFrom($session->get('emailNoReply'))
  3739.                                     ->setTo($setTo)
  3740.                                     ->setBcc($bccMails)
  3741.                                     ->setSubject($session->get('agencyShortName').' - '.$setSubject)
  3742.                                     ->attach(\Swift_Attachment::fromPath($voucherFile))
  3743.                                     ->setBody(
  3744.                                         $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
  3745.                                     );
  3746.                         } else {
  3747.                             $message = (new \Swift_Message())
  3748.                                     ->setContentType('text/html')
  3749.                                     ->setFrom($session->get('emailNoReply'))
  3750.                                     ->setTo($setTo)
  3751.                                     ->setBcc($bccMails)
  3752.                                     ->setSubject($session->get('agencyShortName').' - '.$setSubject)
  3753.                                     ->setBody(
  3754.                                         $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
  3755.                                     );
  3756.                         }
  3757.                     }
  3758.                 } else {
  3759.                     $bccMails[] = 'lida.lugo@aviatur.com';
  3760.                     $setTo = isset($responseOrder->CORREO_ELECTRONICO) ? (string) $responseOrder->CORREO_ELECTRONICO null;
  3761.                     $setSubject 'Gracias por tu reserva';
  3762.                     $emailData['front'] = true;
  3763.                     $message = (new \Swift_Message())
  3764.                             ->setContentType('text/html')
  3765.                             ->setFrom($session->get('emailNoReply'))
  3766.                             ->setTo($setTo)
  3767.                             ->setBcc($bccMails)
  3768.                             ->setSubject($session->get('agencyShortName').' - '.$setSubject)
  3769.                             ->setBody(
  3770.                                 $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
  3771.                             );
  3772.                 }
  3773.                 try {
  3774.                     $mailer->send($message);
  3775.                     $session->set($transactionId.'[emission_email]''emailed');
  3776.                     /*
  3777.                      * Agente Octopus
  3778.                      * Email de la reserva del agente hijo enviado al agente Padre Octopus.
  3779.                      */
  3780.                     if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
  3781.                         $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  3782.                         if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
  3783.                             $request $request;
  3784.                             $parent $agent->getparentAgent();
  3785.                             if (!= $parent) {
  3786.                                 $myParent $em->createQuery('SELECT a,b FROM AviaturAgentBundle:Agent a  JOIN a.customer b WHERE a.id= :idAgent');
  3787.                                 $myParent $myParent->setParameter('idAgent'$parent);
  3788.                                 $parentInfo $myParent->getResult();
  3789.                                 $emailParent $parentInfo[0]->getCustomer()->getEmail();
  3790.                                 $emailData['infoSubAgent'] = ['nameSubAgent' => strtoupper($agent->getCustomer()->__toString()), 'emailSubAgent' => strtoupper($agent->getCustomer()->getEmail())];
  3791.                                 $messageAgent = (new \Swift_Message())
  3792.                                         ->setContentType('text/html')
  3793.                                         ->setFrom($session->get('emailNoReply'))
  3794.                                         ->setTo([$agent->getCustomer()->getEmail(), $emailParent])
  3795.                                         ->setBcc($bccMails)
  3796.                                         ->setSubject($session->get('agencyShortName').' - Gracias por su compra - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
  3797.                                         ->setBody(
  3798.                                             $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
  3799.                                         );
  3800.                                 $mailer->send($messageAgent);
  3801.                             } else {
  3802.                                 $messageAgent = (new \Swift_Message())
  3803.                                         ->setContentType('text/html')
  3804.                                         ->setFrom($session->get('emailNoReply'))
  3805.                                         ->setTo($agent->getCustomer()->getEmail())
  3806.                                         ->setBcc($bccMails)
  3807.                                         ->setSubject($session->get('agencyShortName').' - Gracias por su compra - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
  3808.                                         ->setBody(
  3809.                                             $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
  3810.                                         );
  3811.                                 $mailer->send($messageAgent);
  3812.                             }
  3813.                         }
  3814.                     }
  3815.                 } catch (Exception $ex) {
  3816.                     $exceptionLog->log(
  3817.                         var_dump($message),
  3818.                         $ex
  3819.                     );
  3820.                 }
  3821.             }
  3822.             // END Send confirmation email if success
  3823.         }
  3824.         $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  3825.         $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  3826.         if ($isMulti) {
  3827.             if ($session->has($transactionId.'[multi][cash_result]')) {
  3828.                 $paymentResume['transaction_state'] = 3;
  3829.             }
  3830.             return $this->json([
  3831.                         'retry_count' => $retryCount,
  3832.                         'paymentResume' => $paymentResume,
  3833.                         'facturationResume' => $facturationResume,
  3834.                         'agencyData' => $emailData['agencyData'],
  3835.                         'journeySummary' => $emailData['journeySummary'],
  3836.                         'transactionID' => $transactionId,
  3837.                         'rooms' => $rooms,
  3838.                         'traveller' => $traveller,
  3839.                         'agent' => $responseOrder,
  3840.             ]);
  3841.         }
  3842.         // delete items for geNerate other reservation of hotel after crossed sale
  3843.         if (isset($paymentResume['transaction_state']) && == $paymentResume['transaction_state'] && $session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  3844.             $session->remove($transactionId.'[hotel]'.'[retry]');
  3845.             $session->remove($transactionId.'[hotel]'.'[prepayment_check]');
  3846.             $session->remove($transactionId.'[hotel]'.'[order]');
  3847.         }
  3848.         if ($session->has($transactionId.'[hotel][cash_result]')) {
  3849.             $paymentResume['cash_result'] = json_decode($session->get($transactionId.'[hotel][cash_result]'));
  3850.         }
  3851.         if (isset($paymentResume['id_context'])) {
  3852.             $voucherFile $projectDir.'/app/serviceLogs/CashTransaction/ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  3853.             if (file_exists($voucherFile)) {
  3854.                 $paymentResume['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  3855.             }
  3856.         }
  3857.         if (($session->has($transactionId.'[hotel][cash_result]') && !$isMulti) && !$session->has($transactionId.'[emission_baloto_email]')) {
  3858.             $paymentResume['exportPDF'] = true;
  3859.             $paymentResume['infos'][0]['agencyData'] = $emailData['agencyData'];
  3860.             $paymentResume['infos'][0]['paymentResume']['id'] = $paymentResume['id_context'];
  3861.             $paymentResume['infos'][0]['paymentResume']['total_amount'] = $paymentResume['total_amount'];
  3862.             $paymentResume['infos'][0]['paymentResume']['fecha_vigencia'] = $paymentResume['fecha_vigencia'];
  3863.             $paymentResume['infos'][0]['paymentResume']['description'] = $paymentResume['description'];
  3864.             $ruta '@AviaturTwig/'.$agencyFolder.'/General/Templates/email_cash.html.twig';
  3865.             if (!file_exists($voucherFile)) {
  3866.                 $pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $paymentResume), $voucherFile);
  3867.                 $paymentResume['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  3868.             }
  3869.             $clientEmail $paymentResume['client_email'];
  3870.             $setTo = ['soportepagoelectronico@aviatur.com.co''soptepagelectronic@aviatur.com'$clientEmail];
  3871.             $paymentResume['exportPDF'] = false;
  3872.             $message = (new \Swift_Message())
  3873.                     ->setContentType('text/html')
  3874.                     ->setFrom($session->get('emailNoReply'))
  3875.                     ->setTo($setTo)
  3876.                     ->setBcc($emailNotification)
  3877.                     ->setSubject($session->get('agencyShortName').' - '.'Transacción Efectivo Creada '.$paymentResume['id_context'])
  3878.                     ->attach(\Swift_Attachment::fromPath($voucherFile))
  3879.                     ->setBody(
  3880.                         $this->renderView($twigFolder->twigExists($ruta), $paymentResume)
  3881.                     );
  3882.             try {
  3883.                 $mailer->send($message);
  3884.                 $session->set($transactionId.'[emission_baloto_email]''emailed');
  3885.             } catch (Exception $ex) {
  3886.                 $exceptionLog->log(var_dump($message), $ex);
  3887.             }
  3888.         }
  3889.         return $this->render($urlResume, [
  3890.                     'retry_count' => $retryCount,
  3891.                     'paymentResume' => $paymentResume,
  3892.                     'facturationResume' => $facturationResume,
  3893.                     'agencyData' => $emailData['agencyData'],
  3894.                     'journeySummary' => $emailData['journeySummary'],
  3895.                     'transactionID' => $transactionId,
  3896.                     'rooms' => $rooms,
  3897.                     'traveller' => $traveller,
  3898.                     'agent' => $responseOrder,
  3899.                     'pixel_info' => $pixelInfo,
  3900.         ]);
  3901.     }
  3902.     public function confirmationAction(SessionInterface $sessionAviaturXsltRender $renderxsltTwigFolder $twigFolderManagerRegistry $registryParameterBagInterface $parameterBag)
  3903.     {
  3904.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3905.         $em $this->managerRegistry;
  3906.         $transactionId $session->get($transactionIdSessionName);
  3907.         $response $session->get($transactionId.'[rates]');
  3908.         $xml simplexml_load_string((string) $response)->TotalAviatur;
  3909.         $postDataJson $session->get($transactionId.'[hotel][detail_data_hotel]');
  3910.         $postData json_decode($postDataJson);
  3911.         $docType '';
  3912.         $docNumber '';
  3913.         $names '';
  3914.         $lastNames '';
  3915.         $address '';
  3916.         $phone '';
  3917.         $email '';
  3918.         if (strpos($postData->BD->first_name'***') > 0) {
  3919.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  3920.             $docType $customer->getDocumentType()->getExternalcode();
  3921.             $docNumber $customer->getDocumentnumber();
  3922.             $names $customer->getFirstname();
  3923.             $lastNames $customer->getLastname();
  3924.             $address $customer->getAddress();
  3925.             $phone $customer->getPhone();
  3926.             $email $customer->getEmail();
  3927.         } else {
  3928.             $docType $postData->BD->doc_type;
  3929.             $docNumber $postData->BD->doc_num;
  3930.             $names $postData->BD->first_name;
  3931.             $lastNames $postData->BD->last_name;
  3932.             $address $postData->BD->address;
  3933.             $phone $postData->BD->phone;
  3934.             $email $postData->BD->email;
  3935.         }
  3936.         $iataOrigin = (string) $xml->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
  3937.         $iataDestinity = (string) $xml->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
  3938.         $from $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($iataOrigin);
  3939.         $to $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($iataDestinity);
  3940.         $plantilla $renderxslt->render($xml->asXML(), 'Hotel''Resume');
  3941.         $agencyFolder $twigFolder->twigFlux();
  3942.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/confirmation.html.twig'), [
  3943.                     'from_iata' => $iataOrigin,
  3944.                     'to_iata' => $iataDestinity,
  3945.                     'from' => $from->getDescription(),
  3946.                     'to' => $to->getDescription(),
  3947.                     'template' => $plantilla,
  3948.                     'docType' => $docType,
  3949.                     'docNumber' => $docNumber,
  3950.                     'names' => $names,
  3951.                     'lastNames' => $lastNames,
  3952.                     'address' => $address,
  3953.                     'phone' => $phone,
  3954.                     'email' => $email,
  3955.                     'total_amount' => (string) $xml['TotalAmount'],
  3956.                     'currency_code' => (string) $xml['CurrencyCode'],
  3957.         ]);
  3958.     }
  3959.     public function metasearchAvailabilityAction(Request $requestSessionInterface $sessionManagerRegistry $registryAuthorizationCheckerInterface $authorizationCheckerParameterBagInterface $parameterBag$token)
  3960.     {
  3961.         $projectDir $parameterBag->get('kernel.project_dir');
  3962.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3963.         $aviaturServiceWebInvoker $parameterBag->get('aviatur_service_web_invoker');
  3964.         $aviaturServiceWebRequestId $parameterBag->get('aviatur_service_web_request_id');
  3965.         $AvailabilityArray = [];
  3966.         $providers = [];
  3967.         $makeLogin null;
  3968.         $options = [];
  3969.         $starttime microtime(true);
  3970.         $em $this->managerRegistry;
  3971.         $metasearch $em->getRepository(\Aviatur\GeneralBundle\Entity\Metasearch::class)->findOneByToken($token);
  3972.         if (null != $metasearch) {
  3973.             $fullRequest $request;
  3974.             $session $fullRequest->getSession();
  3975.             $agency $metasearch->getAgency();
  3976.             $tempRequest explode('<OTA_HotelAvailRQ'file_get_contents('php://input'));
  3977.             $tempRequest explode('</OTA_HotelAvailRQ'$tempRequest[1]);
  3978.             $request '<OTA_HotelAvailRQ'.$tempRequest[0].'</OTA_HotelAvailRQ>';
  3979.             $xmlRequestObject simplexml_load_string($request);
  3980.             $rooms 0;
  3981.             $child1 null;
  3982.             $adult2 null;
  3983.             $child2 null;
  3984.             $adult3 null;
  3985.             $child3 null;
  3986.             $services = [];
  3987.             foreach ($xmlRequestObject->AvailRequestSegments->AvailRequestSegment->RoomStayCandidates->RoomStayCandidate as $roomStay) {
  3988.                 ++$rooms;
  3989.                 ${'adult'.$rooms} = 0;
  3990.                 $childArray = [];
  3991.                 $services[$rooms]['adults'] = 0;
  3992.                 $services[$rooms]['childrens'] = [];
  3993.                 foreach ($roomStay->GuestCounts->GuestCount as $guestCount) {
  3994.                     if (!isset($guestCount['Age'])) {
  3995.                         ${'adult'.$rooms} += (int) $guestCount['Count'];
  3996.                         $services[$rooms]['adults'] = ${'adult'.$rooms};
  3997.                     } else {
  3998.                         $childArray[] = (string) $guestCount['Age'];
  3999.                         ${'child'.$rooms} = implode('-'$childArray);
  4000.                         $services[$rooms]['childrens'] = $childArray;
  4001.                     }
  4002.                 }
  4003.             }
  4004.             $destination = (string) $xmlRequestObject->AvailRequestSegments->AvailRequestSegment->HotelSearchCriteria->Criterion->HotelRef['HotelCityCode'];
  4005.             $date1 = (string) $xmlRequestObject->AvailRequestSegments->AvailRequestSegment->StayDateRange['Start'];
  4006.             $date2 = (string) $xmlRequestObject->AvailRequestSegments->AvailRequestSegment->StayDateRange['End'];
  4007.             $destinationObject $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination);
  4008.             if (null != $destinationObject) {
  4009.                 $AvailabilityArray['cityName'] = $destinationObject->getCity();
  4010.                 $AvailabilityArray['countryCode'] = $destinationObject->getCountrycode();
  4011.             } else {
  4012.                 $response = new \SimpleXMLElement('<Response></Response>');
  4013.                 $response->addChild('error''La ciudad ingresada no es válida');
  4014.             }
  4015.             if ($destinationObject) {
  4016.                 $currency 'COP';
  4017.                 if ($session->has('hotelAdapterId')) {
  4018.                     $providers explode(';'$session->get('hotelAdapterId'));
  4019.                     $providerObjects $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findByProvideridentifier($providers);
  4020.                     $configsHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['provider' => $providerObjects'agency' => $agency]);
  4021.                 } else {
  4022.                     $configsHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
  4023.                 }
  4024.                 if ($configsHotelAgency) {
  4025.                     $providers = [];
  4026.                     foreach ($configsHotelAgency as $configHotelAgency) {
  4027.                         $providers[] = $configHotelAgency->getProvider()->getProvideridentifier();
  4028.                         if (strpos($configHotelAgency->getProvider()->getName(), '-USD')) {
  4029.                             $currency 'USD';
  4030.                         }
  4031.                     }
  4032.                 } else {
  4033.                     $response = new \SimpleXMLElement('<Response></Response>');
  4034.                     $response->addChild('error''No se encontró agencias para consultar disponibilidad.');
  4035.                 }
  4036.                 $hotelModel = new HotelModel();
  4037.                 $xmlTemplate $hotelModel->getXmlAvailability();
  4038.                 $xmlRequest $xmlTemplate[0];
  4039.                 $provider implode(';'$providers);
  4040.                 $requestLanguage mb_strtoupper($fullRequest->getLocale());
  4041.                 $variable = [
  4042.                     'ProviderId' => $provider,
  4043.                     'date1' => $date1,
  4044.                     'date2' => $date2,
  4045.                     'destination' => $destination,
  4046.                     'country' => $destinationObject->getCountrycode(),
  4047.                     'language' => $requestLanguage,
  4048.                     'currency' => $currency,
  4049.                     'userIp' => $fullRequest->getClientIp(),
  4050.                     'userAgent' => $fullRequest->headers->get('User-Agent'),
  4051.                 ];
  4052.                 $i 1;
  4053.                 foreach ($services as $room) {
  4054.                     $xmlRequest .= str_replace('templateAdults''adults_'.$i$xmlTemplate[1]);
  4055.                     $j 1;
  4056.                     foreach ($room['childrens'] as $child) {
  4057.                         $xmlRequest .= str_replace('templateChild''child_'.$i.'_'.$j$xmlTemplate[2]);
  4058.                         $variable['child_'.$i.'_'.$j] = $child;
  4059.                         ++$j;
  4060.                     }
  4061.                     $variable['adults_'.$i] = $room['adults'];
  4062.                     $xmlRequest .= $xmlTemplate[3];
  4063.                     ++$i;
  4064.                 }
  4065.                 $xmlRequest .= $xmlTemplate[4];
  4066.                 $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/'$variable['ProviderId']);
  4067.                 if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  4068.                     $response = new \SimpleXMLElement('<Response></Response>');
  4069.                     $response->addChild('error''Estamos experimentando dificultades técnicas en este momento.');
  4070.                     $aviaturErrorHandler->errorRedirect('''Error MPA''No se creo Login!');
  4071.                 }
  4072.                 $transactionId = (string) $transactionIdResponse;
  4073.                 $variable['transaction'] = $transactionId;
  4074.                 $session->set($transactionIdSessionName$transactionId);
  4075.                 $metatransaction = new Metatransaction();
  4076.                 $metatransaction->setTransactionId((string) $transactionId);
  4077.                 $metatransaction->setDatetime(new \DateTime());
  4078.                 $metatransaction->setIsactive(true);
  4079.                 $metatransaction->setMetasearch($metasearch);
  4080.                 $em->persist($metatransaction);
  4081.                 $em->flush();
  4082.                 $preResponse $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  4083.                 if (isset($preResponse['error'])) {
  4084.                     if (false === strpos($preResponse['error'], '66002')) {
  4085.                         $aviaturErrorHandler->errorRedirect($fullRequest->server->get('REQUEST_URI'), 'Error disponibilidad hoteles'$preResponse['error']);
  4086.                     }
  4087.                     $preResponse $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variable$makeLogin);
  4088.                     if (isset($preResponse['error'])) {
  4089.                         if (false === strpos($preResponse['error'], '66002')) {
  4090.                             $aviaturErrorHandler->errorRedirect($fullRequest->server->get('REQUEST_URI'), 'Error disponibilidad hoteles'$preResponse['error']);
  4091.                         }
  4092.                         $response = new \SimpleXMLElement('<Response></Response>');
  4093.                         $response->addChild('error'$preResponse['error']);
  4094.                     }
  4095.                 } elseif (empty((array) $preResponse->Message)) {
  4096.                     $aviaturErrorHandler->errorRedirect($fullRequest->server->get('REQUEST_URI'), 'Error disponibilidad hoteles'$preResponse->Message);
  4097.                     $response = new \SimpleXMLElement('<Response></Response>');
  4098.                     $response->addChild('error''No hemos encontrado información para el destino solicitado.');
  4099.                 }
  4100.                 if (!isset($response)) {
  4101.                     $searchImages = ['hotelbeds.com/giata/small''/100x100/''_tn.jpg''&lt;p&gt;&lt;b&gt;Ubicaci&#xF3;n del establecimiento&lt;/b&gt; &lt;br /&gt;'];
  4102.                     $replaceImages = ['hotelbeds.com/giata''/200x200/''.jpg'''];
  4103.                     $response simplexml_load_string(str_replace($searchImages$replaceImages$preResponse->asXML()));
  4104.                     $response->Message->OTA_HotelAvailRS['StartDate'] = $date1;
  4105.                     $response->Message->OTA_HotelAvailRS['EndDate'] = $date2;
  4106.                     $response->Message->OTA_HotelAvailRS['Country'] = $variable['country'];
  4107.                     $configHotelAgencyIds = [];
  4108.                     foreach ($configsHotelAgency as $configHotelAgency) {
  4109.                         $configHotelAgencyIds[] = $configHotelAgency->getId();
  4110.                         $providerOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getProvider()->getProvideridentifier();
  4111.                         $typeOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getType();
  4112.                     }
  4113.                     $markups $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->getMarkups($configHotelAgencyIds$destinationObject->getId());
  4114.                     $domain $fullRequest->getHost();
  4115.                     $parametersJson $session->get($domain.'[parameters]');
  4116.                     $parameters json_decode($parametersJson);
  4117.                     $tax = (float) $parameters->aviatur_payment_iva;
  4118.                     $currencyCode = (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
  4119.                     if ('COP' != $currencyCode && 'COP' == $currency) {
  4120.                         $trm $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
  4121.                         $trm $trm[0]['value'];
  4122.                     } else {
  4123.                         $trm 1;
  4124.                     }
  4125.                     $key 0;
  4126.                     $searchHotelCodes = ['|''/'];
  4127.                     $replaceHotelCodes = ['--''---'];
  4128.                     //load discount info if applicable
  4129.                     //$aviaturLogSave->logSave(print_r($session, true), 'Bpcs', 'availSession');
  4130.                     foreach ($response->Message->OTA_HotelAvailRS->RoomStays->RoomStay as $roomStay) {
  4131.                         $roomStay['Show'] = '1';
  4132.                         $roomStay->BasicPropertyInfo['HotelCode'] = str_replace($searchHotelCodes$replaceHotelCodes, (string) $roomStay->BasicPropertyInfo['HotelCode']);
  4133.                         $hotelCode $roomStay->BasicPropertyInfo['HotelCode'];
  4134.                         $hotelEntity $em->getRepository(\Aviatur\HotelBundle\Entity\Hotel::class)->findOneByCodhotel($hotelCode);
  4135.                         $hotel $hotelEntity $hotelEntity->getId() : null;
  4136.                         $roomRate $roomStay->RoomRates->RoomRate;
  4137.                         $i 0;
  4138.                         $markup false;
  4139.                         while (!$markup) {
  4140.                             if (($markups[$i]['hotel_id'] == $hotel || null == $markups[$i]['hotel_id']) && ($providerOfConfig[$markups[$i]['config_hotel_agency_id']] == (string) $roomStay->TPA_Extensions->HotelInfo->providerID)) {
  4141.                                 // if ($hotelEntity != null) {
  4142.                                 //     $markups[$i]['value'] = $hotelEntity->getMarkupValue();
  4143.                                 // }
  4144.                                 if ('N' == $typeOfConfig[$markups[$i]['config_hotel_agency_id']]) {
  4145.                                     $aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markups[$i]['value'] / (100 $markups[$i]['value']);
  4146.                                 } else {
  4147.                                     $aviaturMarkup 0;
  4148.                                 }
  4149.                                 $roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
  4150.                                 if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
  4151.                                     $roomRate->Total['AmountAviaturMarkupTax'] = 0;
  4152.                                 } else {
  4153.                                     $roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup $tax;
  4154.                                 }
  4155.                                 $roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
  4156.                                 $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round(((float) $aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
  4157.                                 if ('COP' == $currencyCode) {
  4158.                                     $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
  4159.                                 }
  4160.                                 if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
  4161.                                     $roomRate->TotalAviatur['AmountTax'] = 0;
  4162.                                 } else {
  4163.                                     $roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
  4164.                                 }
  4165.                                 $roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
  4166.                                 $roomRate->TotalAviatur['CurrencyCode'] = $currency;
  4167.                                 $roomRate->TotalAviatur['Markup'] = $markups[$i]['value'];
  4168.                                 $roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markups[$i]['id'];
  4169.                                 $roomRate->TotalAviatur['MarkupId'] = $markups[$i]['id'];
  4170.                                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING') && $session->get($transactionId.'_isActiveQse')) {
  4171.                                     $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  4172.                                     if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
  4173.                                         /*                                         * revisar */
  4174.                                         $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
  4175.                                         $commissionPercentage $agentCommission->getHotelcommission();
  4176.                                         $roomRate->TotalAviatur['AgentComission'] = round($commissionPercentage $roomRate->TotalAviatur['AmountIncludingAviaturMarkup']);
  4177.                                     }
  4178.                                 }
  4179.                                 if (false == $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) {
  4180.                                     $roomRate->TotalAviatur['submitBuy'] = '1';
  4181.                                 }
  4182.                                 $markup true;
  4183.                             }
  4184.                             ++$i;
  4185.                         }
  4186.                         $roomStay->TPA_Extensions->HotelInfo->Category['Code'] = (int) $roomStay->TPA_Extensions->HotelInfo->Category['Code'];
  4187.                         $dividerStar explode(' '$roomStay->TPA_Extensions->HotelInfo->Category['CodeDetail']);
  4188.                         $roomStay->TPA_Extensions->HotelInfo->Category['CodeDetail'] = (int) $dividerStar[0].' '.$dividerStar[1];
  4189.                         $options[$key]['amount'] = (float) $roomStay->RoomRates->RoomRate->TotalAviatur['AmountTotal'];
  4190.                         $options[$key]['xml'] = $roomStay->asXml();
  4191.                         ++$key;
  4192.                     }
  4193.                     usort($options, fn($a$b) => $a['amount'] - $b['amount']);
  4194.                     $responseXml explode('<RoomStay>'str_replace(['</RoomStay>''<RoomStay InfoSource="B2C" Show="1">''<RoomStay InfoSource="B2C" Show="0">'], '<RoomStay>'$response->asXml()));
  4195.                     $orderedResponse $responseXml[0];
  4196.                     foreach ($options as $option) {
  4197.                         $orderedResponse .= $option['xml'];
  4198.                     }
  4199.                     $orderedResponse .= $responseXml[sizeof($responseXml) - 1];
  4200.                     $response = \simplexml_load_string($orderedResponse);
  4201.                     $response->Version = ('' != $response->Version) ? $response->Version '2.0';
  4202.                     $response->Language = ('' != $response->Language) ? $response->Language 'es';
  4203.                     $response->ResponseType = ('' != $response->ResponseType) ? $response->ResponseType 'XML';
  4204.                     $response->ExecutionMessages->Fecha ??= date('d/m/Y H:i:s');
  4205.                     $response->ExecutionMessages->Servidor ??= 'MPB';
  4206.                     $response->Message->OTA_HotelAvailRS['Version'] = '';
  4207.                     $response->Message->OTA_HotelAvailRS['SequenceNmbr'] = '1';
  4208.                     $response->Message->OTA_HotelAvailRS['CorrelationID'] = '';
  4209.                     $response->Message->OTA_HotelAvailRS['TransactionIdentifier'] = $transactionId.'||'.$metasearch->getId();
  4210.                     $response->Message->OTA_HotelAvailRS['TransactionID'] = $transactionId.'||'.$metasearch->getId();
  4211.                     $endtime microtime(true);
  4212.                     $response->ExecutionMessages->TiempoEjecucion $endtime $starttime;
  4213.                 }
  4214.             } elseif (isset($xmlResponse['error'])) {
  4215.                 $response = new \SimpleXMLElement('<Response></Response>');
  4216.                 $response->addChild('error'$xmlResponse['error']);
  4217.             } else {
  4218.                 $response = new \SimpleXMLElement('<Response></Response>');
  4219.                 $response->addChild('error''Respuesta vacia del servicio');
  4220.             }
  4221.         } else {
  4222.             $feeVariables null;
  4223.             $xmlResponse null;
  4224.             $aviaturErrorHandler->errorRedirect(json_encode($feeVariables), '''Claves Invalidas');
  4225.             $response = new \SimpleXMLElement('<Response></Response>');
  4226.             $response->addChild('error''Invalid Keys');
  4227.         }
  4228.         $path $projectDir.'/app/xmlService/aviaturResponse.xml';
  4229.         $arrayIndex = [
  4230.             '{xmlBody}',
  4231.             '{service}',
  4232.             '{invoker}',
  4233.             '{provider}',
  4234.             '{requestId}',
  4235.         ];
  4236.         $arrayValues = [
  4237.             str_replace('<?xml version="1.0"?>'''$response->asXML()),
  4238.             'SERVICIO_MPT',
  4239.             $aviaturServiceWebInvoker,
  4240.             'dummy|http://www.aviatur.com.co/dummy/',
  4241.             $aviaturServiceWebRequestId,
  4242.         ];
  4243.         $xmlBase simplexml_load_file($path)->asXML();
  4244.         $metaResponse str_replace($arrayIndex$arrayValues$xmlBase);
  4245.         return new Response($metaResponseResponse::HTTP_OK, ['content-type' => 'text/xml']);
  4246.     }
  4247.     public function generate_email(SessionInterface $sessionManagerRegistry $registry$orderProduct$detailInfo$prepaymentInfo$startDate$endDate)
  4248.     {
  4249.         $em $registry->getManager();
  4250.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  4251.         $agencyData = [
  4252.             'agency_name' => $agency->getName(),
  4253.             'agency_nit' => $agency->getNit(),
  4254.             'agency_phone' => $agency->getPhone(),
  4255.             'agency_email' => $agency->getMailContact(),
  4256.         ];
  4257.         $emailInfos $detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo;
  4258.         $emailInfos2 $detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo;
  4259.         $i 0;
  4260.         $pictures = [];
  4261.         foreach ($emailInfos2->MultimediaDescription->ImageItems->ImageItem as $picture) {
  4262.             if ($i 3) {
  4263.                 $pictures[] = (string) $picture->ImageFormat->URL;
  4264.             }
  4265.             ++$i;
  4266.         }
  4267.         if (== sizeof($pictures)) {
  4268.             $domain 'https://'.$agency->getDomain();            
  4269.             $pictures[0] = $domain.'/assets/aviatur_assets/img/error/noHotelPicture.jpg';
  4270.         }
  4271.         $cancelPolicies = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->CancelPenalties->CancelPenalty->PenaltyDescription->Text;
  4272.         $checkinInstructions = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Comments;
  4273.         $payable = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Payable;
  4274.         $journeySummary = [
  4275.             'hotelName' => (string) $emailInfos['HotelName'],
  4276.             'stars' => (string) $emailInfos2->Category['Code'],
  4277.             'startDate' => $startDate,
  4278.             'endDate' => $endDate,
  4279.             'address' => (string) $emailInfos->Address->AddressLine.', '.(string) $emailInfos->Address->CityName,
  4280.             'phone' => (string) $emailInfos->ContactNumbers->ContactNumber['PhoneNumber'],
  4281.             'email' => (string) $emailInfos2->Email,
  4282.             'pictures' => $pictures,
  4283.             'latitude' => (string) $emailInfos->Position['Latitude'],
  4284.             'longitude' => (string) $emailInfos->Position['Longitude'],
  4285.             'cancelPolicies' => $cancelPolicies,
  4286.             'checkinInstructions' => $checkinInstructions,
  4287.             'payable' => $payable,
  4288.         ];
  4289.         $emailData = [
  4290.             'agencyData' => $agencyData,
  4291.             'journeySummary' => $journeySummary,
  4292.         ];
  4293.         $orderProduct->setEmail(json_encode($emailData));
  4294.         $em->persist($orderProduct);
  4295.         $em->flush();
  4296.     }
  4297.     public function indexAction(Request $fullRequestAuthorizationCheckerInterface $authorizationCheckerPaginatorInterface $knpPaginatorAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolder$page$active$search null)
  4298.     {
  4299.         $em $this->managerRegistry;
  4300.         $session $this->session;
  4301.         $agency $this->agency;
  4302.         $routeParams $fullRequest->attributes->get('_route_params');
  4303.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $routeParams);
  4304.         $agencyId $session->get('agencyId');
  4305.         $agencyFolder $twigFolder->twigFlux();
  4306.         if ($fullRequest->isXmlHttpRequest()) {
  4307.             $query $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  4308.             $query $query->setParameter('agency'$agency);
  4309.             $query $query->setParameter('id'$search);
  4310.             $queryIn $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  4311.             $queryIn $queryIn->setParameter('agency'$agency);
  4312.             $queryIn $queryIn->setParameter('id'$search);
  4313.             $path '/Hotel/Hotel/Ajaxindex_content.html.twig';
  4314.             $urlReturn '@AviaturTwig/'.$agencyFolder.$path;
  4315.             if ('activo' == $active) {
  4316.                 $articulos $query->getResult();
  4317.             } elseif ('inactivo' == $active) {
  4318.                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
  4319.                     $articulos $queryIn->getResult();
  4320.                 } else {
  4321.                     return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'));
  4322.                 }
  4323.             }
  4324.             $actualArticles = [];
  4325.             foreach ($articulos as $articulo) {
  4326.                 $description json_decode($articulo->getDescription(), true);
  4327.                 if ($description && is_array($description)) {
  4328.                     $actualArticles[] = $articulo;
  4329.                     $type $description['type2'];
  4330.                 }
  4331.             }
  4332.             if (empty($actualArticles)) {
  4333.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/''''No existen contenidos para esta agencia.'));
  4334.             }
  4335.             $cantdatos count($actualArticles);
  4336.             $cantRegis 10;
  4337.             $totalRegi ceil($cantdatos $cantRegis);
  4338.             $paginator $knpPaginator;
  4339.             $pagination $paginator->paginate($actualArticles$fullRequest->query->get('page'$page), $cantRegis);
  4340.             if (isset($type)) {
  4341.                 return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $pagination'page' => $page'active' => $active'totalRegi' => $totalRegi'ajaxUrl' => $requestUrl'typeArticle' => $type]);
  4342.             } else {
  4343.                 return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $pagination'page' => $page'active' => $active'totalRegi' => $totalRegi'ajaxUrl' => $requestUrl]);
  4344.             }
  4345.         } else {
  4346.             return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/index_hotel.html.twig'), ['agencyId' => $agencyId]);
  4347.         }
  4348.     }
  4349.     public function listAction(Request $fullRequestAuthorizationCheckerInterface $authorizationCheckerPaginatorInterface $knpPaginatorAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolder$page$active$type)
  4350.     {
  4351.         $em $this->managerRegistry;
  4352.         $session $this->session;
  4353.         $agency $this->agency;
  4354.         $routeParams $fullRequest->attributes->get('_route_params');
  4355.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $routeParams);
  4356.         $agencyId $session->get('agencyId');
  4357.         $agencyFolder $twigFolder->twigFlux();
  4358.         $query $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  4359.         $query $query->setParameter('agency'$agency);
  4360.         $queryIn $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  4361.         $queryIn $queryIn->setParameter('agency'$agency);
  4362.         $path '/Hotel/Hotel/index_content.html.twig';
  4363.         $urlReturn '@AviaturTwig/'.$agencyFolder.$path;
  4364.         $booking false;
  4365.         $configHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['agency' => $agencyId]);
  4366.         foreach ($configHotelAgency as $agency) {
  4367.             if ('B' == $agency->getType()) {
  4368.                 $booking true;
  4369.                 $domain $agency->getWsUrl();
  4370.             }
  4371.         }
  4372.         if ($session->has('operatorId')) {
  4373.             $operatorId $session->get('operatorId');
  4374.         }
  4375.         $colombia = [];
  4376.         $america = [];
  4377.         $oceania = [];
  4378.         $europa = [];
  4379.         $africa = [];
  4380.         $asia = [];
  4381.         $destino = [];
  4382.         $cantRegis 9;
  4383.         if ('activo' == $active) {
  4384.             $articulos $query->getResult();
  4385.         } elseif ('inactivo' == $active) {
  4386.             if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
  4387.                 $articulos $queryIn->getResult();
  4388.                 foreach ($articulos as $articulo) {
  4389.                     $description json_decode($articulo->getDescription(), true);
  4390.                     if ($description && is_array($description)) {
  4391.                         if (isset($description['type']) && 'hoteles' == $description['type']) {
  4392.                             if (isset($description['type2'])) {
  4393.                                 if ('colombia' == $description['type2']) {
  4394.                                     $colombia[] = $articulo;
  4395.                                 }
  4396.                                 if ('america' == $description['type2']) {
  4397.                                     $america[] = $articulo;
  4398.                                 }
  4399.                                 if ('oceania' == $description['type2']) {
  4400.                                     $oceania[] = $articulo;
  4401.                                 }
  4402.                                 if ('europa' == $description['type2']) {
  4403.                                     $europa[] = $articulo;
  4404.                                 }
  4405.                                 if ('africa' == $description['type2']) {
  4406.                                     $africa[] = $articulo;
  4407.                                 }
  4408.                                 if ('asia' == $description['type2']) {
  4409.                                     $asia[] = $articulo;
  4410.                                 }
  4411.                                 if ('destino' == $description['type2']) {
  4412.                                     $destino[] = $articulo;
  4413.                                 }
  4414.                             }
  4415.                         }
  4416.                     }
  4417.                 }
  4418.                 if (empty($colombia) && empty($america) && empty($oceania) && empty($europa) && empty($africa) && empty($asia)) {
  4419.                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/''''No existen contenidos para esta agencia.'));
  4420.                 }
  4421.                 /* Redireccion hoteles por division */
  4422.                 if ('colombia' == $type) {
  4423.                     $cantDestinosC count($colombia);
  4424.                     $totalDestinosC ceil($cantDestinosC $cantRegis);
  4425.                     $paginator $knpPaginator;
  4426.                     $pagination $paginator->paginate($colombia$fullRequest->query->get('page'$page), $cantRegis);
  4427.                     $cookieArray = [];
  4428.                     $cookieArray['destination'] = 'SMR';
  4429.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4430.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4431.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4432.                     } else {
  4433.                         $cookieArray['destinationLabel'] = '';
  4434.                     }
  4435.                     $cookieArray['adults'] = '';
  4436.                     $cookieArray['children'] = '';
  4437.                     $cookieArray['childAge'] = '';
  4438.                     $cookieArray['date1'] = '';
  4439.                     $cookieArray['date2'] = '';
  4440.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $colombia'page' => $page'active' => $active'totalRegi' => $totalDestinosC'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4441.                 }
  4442.                 if ('america' == $type) {
  4443.                     $cantDestinosA count($america);
  4444.                     $totalDestinosA ceil($cantDestinosA $cantRegis);
  4445.                     $paginator $knpPaginator;
  4446.                     $pagination $paginator->paginate($america$fullRequest->query->get('page'$page), $cantRegis);
  4447.                     $cookieArray = [];
  4448.                     $cookieArray['destination'] = 'MIA';
  4449.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4450.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4451.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4452.                     } else {
  4453.                         $cookieArray['destinationLabel'] = '';
  4454.                     }
  4455.                     $cookieArray['adults'] = '';
  4456.                     $cookieArray['children'] = '';
  4457.                     $cookieArray['childAge'] = '';
  4458.                     $cookieArray['date1'] = '';
  4459.                     $cookieArray['date2'] = '';
  4460.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $america'page' => $page'active' => $active'totalRegi' => $totalDestinosA'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4461.                 }
  4462.                 if ('oceania' == $type) {
  4463.                     $cantDestinosO count($oceania);
  4464.                     $totalDestinosO ceil($cantDestinosO $cantRegis);
  4465.                     $paginator $knpPaginator;
  4466.                     $pagination $paginator->paginate($oceania$fullRequest->query->get('page'$page), $cantRegis);
  4467.                     $cookieArray = [];
  4468.                     $cookieArray['destination'] = 'SYD';
  4469.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4470.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4471.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4472.                     } else {
  4473.                         $cookieArray['destinationLabel'] = '';
  4474.                     }
  4475.                     $cookieArray['adults'] = '';
  4476.                     $cookieArray['children'] = '';
  4477.                     $cookieArray['childAge'] = '';
  4478.                     $cookieArray['date1'] = '';
  4479.                     $cookieArray['date2'] = '';
  4480.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $oceania'page' => $page'active' => $active'totalRegi' => $totalDestinosO'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4481.                 }
  4482.                 if ('europa' == $type) {
  4483.                     $cantDestinosE count($europa);
  4484.                     $totalDestinosE ceil($cantDestinosE $cantRegis);
  4485.                     $paginator $knpPaginator;
  4486.                     $pagination $paginator->paginate($europa$fullRequest->query->get('page'$page), $cantRegis);
  4487.                     $cookieArray = [];
  4488.                     $cookieArray['destination'] = 'MAD';
  4489.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4490.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4491.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4492.                     } else {
  4493.                         $cookieArray['destinationLabel'] = '';
  4494.                     }
  4495.                     $cookieArray['adults'] = '';
  4496.                     $cookieArray['children'] = '';
  4497.                     $cookieArray['childAge'] = '';
  4498.                     $cookieArray['date1'] = '';
  4499.                     $cookieArray['date2'] = '';
  4500.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $europa'page' => $page'active' => $active'totalRegi' => $totalDestinosE'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4501.                 }
  4502.                 if ('africa' == $type) {
  4503.                     $cantDestinosAF count($africa);
  4504.                     $totalDestinosAF ceil($cantDestinosAF $cantRegis);
  4505.                     $paginator $knpPaginator;
  4506.                     $pagination $paginator->paginate($africa$fullRequest->query->get('page'$page), $cantRegis);
  4507.                     $cookieArray = [];
  4508.                     $cookieArray['destination'] = 'CAI';
  4509.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4510.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4511.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4512.                     } else {
  4513.                         $cookieArray['destinationLabel'] = '';
  4514.                     }
  4515.                     $cookieArray['adults'] = '';
  4516.                     $cookieArray['children'] = '';
  4517.                     $cookieArray['childAge'] = '';
  4518.                     $cookieArray['date1'] = '';
  4519.                     $cookieArray['date2'] = '';
  4520.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $africa'page' => $page'active' => $active'totalRegi' => $totalDestinosAF'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4521.                 }
  4522.                 if ('asia' == $type) {
  4523.                     $cantDestinosAS count($asia);
  4524.                     $totalDestinosAS ceil($cantDestinosAS $cantRegis);
  4525.                     $paginator $knpPaginator;
  4526.                     $pagination $paginator->paginate($asia$fullRequest->query->get('page'$page), $cantRegis);
  4527.                     $cookieArray = [];
  4528.                     $cookieArray['destination'] = 'TYO';
  4529.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4530.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4531.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4532.                     } else {
  4533.                         $cookieArray['destinationLabel'] = '';
  4534.                     }
  4535.                     $cookieArray['adults'] = '';
  4536.                     $cookieArray['children'] = '';
  4537.                     $cookieArray['childAge'] = '';
  4538.                     $cookieArray['date1'] = '';
  4539.                     $cookieArray['date2'] = '';
  4540.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $asia'page' => $page'active' => $active'totalRegi' => $totalDestinosAS'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4541.                 }
  4542.                 if ('destino' == $type) {
  4543.                     $cantDestinosD count($destino);
  4544.                     $totalDestinosD ceil($cantDestinosD $cantRegis);
  4545.                     $paginator $knpPaginator;
  4546.                     $pagination $paginator->paginate($destino$fullRequest->query->get('page'$page), $cantRegis);
  4547.                     $cookieArray = [];
  4548.                     $cookieArray['destination'] = 'SMR';
  4549.                     if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4550.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4551.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4552.                     } else {
  4553.                         $cookieArray['destinationLabel'] = '';
  4554.                     }
  4555.                     $cookieArray['adults'] = '';
  4556.                     $cookieArray['children'] = '';
  4557.                     $cookieArray['childAge'] = '';
  4558.                     $cookieArray['date1'] = '';
  4559.                     $cookieArray['date2'] = '';
  4560.                     return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $destino'page' => $page'active' => $active'totalRegi' => $totalDestinosD'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4561.                 }
  4562.             } else {
  4563.                 return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'));
  4564.             }
  4565.         }
  4566.         foreach ($articulos as $articulo) {
  4567.             $description json_decode($articulo->getDescription(), true);
  4568.             if ($description && is_array($description)) {
  4569.                 if (isset($description['type']) && 'hoteles' == $description['type']) {
  4570.                     if (isset($description['type2'])) {
  4571.                         if ('colombia' == $description['type2']) {
  4572.                             $colombia[] = $articulo;
  4573.                         }
  4574.                         if ('america' == $description['type2']) {
  4575.                             $america[] = $articulo;
  4576.                         }
  4577.                         if ('oceania' == $description['type2']) {
  4578.                             $oceania[] = $articulo;
  4579.                         }
  4580.                         if ('europa' == $description['type2']) {
  4581.                             $europa[] = $articulo;
  4582.                         }
  4583.                         if ('africa' == $description['type2']) {
  4584.                             $africa[] = $articulo;
  4585.                         }
  4586.                         if ('asia' == $description['type2']) {
  4587.                             $asia[] = $articulo;
  4588.                         }
  4589.                         if ('destino' == $description['type2']) {
  4590.                             $destino[] = $articulo;
  4591.                         }
  4592.                     }
  4593.                 }
  4594.             }
  4595.         }
  4596.         if (empty($colombia) && empty($america) && empty($oceania) && empty($europa) && empty($africa) && empty($asia)) {
  4597.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/''''No existen contenidos para esta agencia.'));
  4598.         }
  4599.         /* Redireccion hoteles según división */
  4600.         if ('colombia' == $type) {
  4601.             $cantDestinosC count($colombia);
  4602.             $totalDestinosC ceil($cantDestinosC $cantRegis);
  4603.             $paginator $knpPaginator;
  4604.             $pagination $paginator->paginate($colombia$fullRequest->query->get('page'$page), $cantRegis);
  4605.             $cookieArray = [];
  4606.             $cookieArray['destination'] = 'SMR';
  4607.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4608.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4609.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4610.             } else {
  4611.                 $cookieArray['destinationLabel'] = '';
  4612.             }
  4613.             $cookieArray['adults'] = '';
  4614.             $cookieArray['children'] = '';
  4615.             $cookieArray['childAge'] = '';
  4616.             $cookieArray['date1'] = '';
  4617.             $cookieArray['date2'] = '';
  4618.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $colombia'page' => $page'active' => $active'totalRegi' => $totalDestinosC'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4619.         }
  4620.         if ('america' == $type) {
  4621.             $cantDestinosA count($america);
  4622.             $totalDestinosA ceil($cantDestinosA $cantRegis);
  4623.             $paginator $knpPaginator;
  4624.             $pagination $paginator->paginate($america$fullRequest->query->get('page'$page), $cantRegis);
  4625.             $cookieArray = [];
  4626.             $cookieArray['destination'] = 'MIA';
  4627.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4628.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4629.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4630.             } else {
  4631.                 $cookieArray['destinationLabel'] = '';
  4632.             }
  4633.             $cookieArray['adults'] = '';
  4634.             $cookieArray['children'] = '';
  4635.             $cookieArray['childAge'] = '';
  4636.             $cookieArray['date1'] = '';
  4637.             $cookieArray['date2'] = '';
  4638.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $america'page' => $page'active' => $active'totalRegi' => $totalDestinosA'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4639.         }
  4640.         if ('oceania' == $type) {
  4641.             $cantDestinosO count($oceania);
  4642.             $totalDestinosO ceil($cantDestinosO $cantRegis);
  4643.             $paginator $knpPaginator;
  4644.             $pagination $paginator->paginate($oceania$fullRequest->query->get('page'$page), $cantRegis);
  4645.             $cookieArray = [];
  4646.             $cookieArray['destination'] = 'SYD';
  4647.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4648.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4649.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4650.             } else {
  4651.                 $cookieArray['destinationLabel'] = '';
  4652.             }
  4653.             $cookieArray['adults'] = '';
  4654.             $cookieArray['children'] = '';
  4655.             $cookieArray['childAge'] = '';
  4656.             $cookieArray['date1'] = '';
  4657.             $cookieArray['date2'] = '';
  4658.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $oceania'page' => $page'active' => $active'totalRegi' => $totalDestinosO'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4659.         }
  4660.         if ('europa' == $type) {
  4661.             $cantDestinosE count($europa);
  4662.             $totalDestinosE ceil($cantDestinosE $cantRegis);
  4663.             $paginator $knpPaginator;
  4664.             $pagination $paginator->paginate($europa$fullRequest->query->get('page'$page), $cantRegis);
  4665.             $cookieArray = [];
  4666.             $cookieArray['destination'] = 'MAD';
  4667.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4668.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4669.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4670.             } else {
  4671.                 $cookieArray['destinationLabel'] = '';
  4672.             }
  4673.             $cookieArray['adults'] = '';
  4674.             $cookieArray['children'] = '';
  4675.             $cookieArray['childAge'] = '';
  4676.             $cookieArray['date1'] = '';
  4677.             $cookieArray['date2'] = '';
  4678.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $europa'page' => $page'active' => $active'totalRegi' => $totalDestinosE'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4679.         }
  4680.         if ('africa' == $type) {
  4681.             $cantDestinosAF count($africa);
  4682.             $totalDestinosAF ceil($cantDestinosAF $cantRegis);
  4683.             $paginator $knpPaginator;
  4684.             $pagination $paginator->paginate($africa$fullRequest->query->get('page'$page), $cantRegis);
  4685.             $cookieArray = [];
  4686.             $cookieArray['destination'] = 'CAI';
  4687.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4688.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4689.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4690.             } else {
  4691.                 $cookieArray['destinationLabel'] = '';
  4692.             }
  4693.             $cookieArray['adults'] = '';
  4694.             $cookieArray['children'] = '';
  4695.             $cookieArray['childAge'] = '';
  4696.             $cookieArray['date1'] = '';
  4697.             $cookieArray['date2'] = '';
  4698.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $africa'page' => $page'active' => $active'totalRegi' => $totalDestinosAF'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4699.         }
  4700.         if ('asia' == $type) {
  4701.             $cantDestinosAS count($asia);
  4702.             $totalDestinosAS ceil($cantDestinosAS $cantRegis);
  4703.             $paginator $knpPaginator;
  4704.             $pagination $paginator->paginate($asia$fullRequest->query->get('page'$page), $cantRegis);
  4705.             $cookieArray = [];
  4706.             $cookieArray['destination'] = 'TYO';
  4707.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4708.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4709.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4710.             } else {
  4711.                 $cookieArray['destinationLabel'] = '';
  4712.             }
  4713.             $cookieArray['adults'] = '';
  4714.             $cookieArray['children'] = '';
  4715.             $cookieArray['childAge'] = '';
  4716.             $cookieArray['date1'] = '';
  4717.             $cookieArray['date2'] = '';
  4718.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $asia'page' => $page'active' => $active'totalRegi' => $totalDestinosAS'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4719.         }
  4720.         if ('destino' == $type) {
  4721.             $cantDestinosD count($destino);
  4722.             $totalDestinosD ceil($cantDestinosD $cantRegis);
  4723.             $paginator $knpPaginator;
  4724.             $pagination $paginator->paginate($asia$fullRequest->query->get('page'$page), $cantRegis);
  4725.             $cookieArray = [];
  4726.             $cookieArray['destination'] = 'SMR';
  4727.             if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination'])) {
  4728.                 $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
  4729.                 $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4730.             } else {
  4731.                 $cookieArray['destinationLabel'] = '';
  4732.             }
  4733.             $cookieArray['adults'] = '';
  4734.             $cookieArray['children'] = '';
  4735.             $cookieArray['childAge'] = '';
  4736.             $cookieArray['date1'] = '';
  4737.             $cookieArray['date2'] = '';
  4738.             return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $destino'page' => $page'active' => $active'totalRegi' => $totalDestinosD'ajaxUrl' => $requestUrl'typeArticle' => $type'params' => $routeParams'cookieLastSearch' => $cookieArray'booking' => $booking'domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4739.         }
  4740.     }
  4741.     public function viewAction(TwigFolder $twigFolder$id)
  4742.     {
  4743.         $em $this->managerRegistry;
  4744.         $session $this->session;
  4745.         $agency $this->agency;
  4746.         $agencyId $session->get('agencyId');
  4747.         $articulo $em->getRepository(\Aviatur\ContentBundle\Entity\Content::class)->findByAgencyTypeNull($session->get('agencyId'), $id'%\"hoteles\"%');
  4748.         $promoType '';
  4749.         if (isset($articulo[0]) && (null != $articulo[0])) {
  4750.             $agencyFolder $twigFolder->twigFlux();
  4751.             $description json_decode($articulo[0]->getDescription(), true);
  4752.             // determine content type based on eventual json encoded description
  4753.             $HotelesPromoList $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => 'hoteles-destino'.$promoType'agency' => $agency]);
  4754.             if (null != $HotelesPromoList) {
  4755.                 $HotelPromoList $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($HotelesPromoList, ['date' => 'DESC']);
  4756.             } else {
  4757.                 $HotelPromoList = [];
  4758.             }
  4759.             $booking false;
  4760.             $configHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['agency' => $agencyId]);
  4761.             foreach ($configHotelAgency as $agency) {
  4762.                 if ('B' == $agency->getType()) {
  4763.                     $booking true;
  4764.                     $domain $agency->getWsUrl();
  4765.                 }
  4766.             }
  4767.             if ($session->has('operatorId')) {
  4768.                 $operatorId $session->get('operatorId');
  4769.             }
  4770.             // determine content type based on eventual json encoded description
  4771.             if ($description && is_array($description)) {
  4772.                 if (isset($description['type']) && 'hoteles' == $description['type']) {
  4773.                     // eg: {"type":"hoteles","type2":"nuevo|colombia|america|oceania|europa|africa|asia" , "description":"texto", "origin1":"BOG", "destination1":"MDE", "date1":"2016-11-18", "date2":"2016-11-25", "adults":"2", "children":"", "infants":""}
  4774.                     $cookieArrayH = [];
  4775.                     $cookieArray = [];
  4776.                     foreach ($description as $key => $value) {
  4777.                         $cookieArrayH[$key] = $value;
  4778.                     }
  4779.                     if (isset($cookieArrayH['origin1']) && (preg_match('/^[A-Z]{3}$/'$cookieArrayH['origin1']) || 'A28' == $cookieArrayH['origin1'] || 'A01' == $cookieArrayH['origin1'])) {
  4780.                         $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArrayH['origin1']]);
  4781.                         $cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  4782.                     } else {
  4783.                         $cookieArray['destinationLabel'] = '';
  4784.                     }
  4785.                     $cookieArray['destination'] = $cookieArrayH['origin1'];
  4786.                     $cookieArray['adults'] = '';
  4787.                     $cookieArray['children'] = '';
  4788.                     $cookieArray['childAge'] = '';
  4789.                     $cookieArray['date1'] = '';
  4790.                     $cookieArray['date2'] = '';
  4791.                     $cookieArray['description'] = $cookieArrayH['description'];
  4792.                     return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/view_content.html.twig'), ['articulo' => $articulo[0], 'cookieLastSearch' => $cookieArray'booking' => $booking'hotelPromos' => $HotelPromoList'promoType' => 'hoteles-destino''domain' => $domain ?? null'agencyId' => $agencyId ?? null'operatorId' => $operatorId ?? null]);
  4793.                 }
  4794.             } else {
  4795.                 throw $this->createNotFoundException('Contenido no encontrado');
  4796.             }
  4797.         } else {
  4798.             throw $this->createNotFoundException('Contenido no encontrado');
  4799.         }
  4800.     }
  4801.     public function searchHotelsAction(Request $request)
  4802.     {
  4803.         $em $this->managerRegistry;
  4804.         $session $this->session;
  4805.         $agency $this->agency;
  4806.         if ($request->isXmlHttpRequest()) {
  4807.             $term $request->query->get('term');
  4808.             $url $request->query->get('url');
  4809.             $queryIn $em->createQuery('SELECT a.id, a.title, a.url, a.description, a.isactive FROM AviaturContentBundle:Content a WHERE a.title LIKE :title AND a.description LIKE :description AND (a.agency = :agency OR a.agency IS NULL)');
  4810.             $queryIn $queryIn->setParameter('title''%'.$term.'%');
  4811.             $queryIn $queryIn->setParameter('description''%\"hoteles\"%');
  4812.             $queryIn $queryIn->setParameter('agency'$agency);
  4813.             $articulos $queryIn->getResult();
  4814.             $type '';
  4815.             $json_template '<value>:<label>*';
  4816.             $json '';
  4817.             if ($articulos) {
  4818.                 foreach ($articulos as $contenidos) {
  4819.                     $description json_decode($contenidos['description'], true);
  4820.                     if (null == $description || is_array($description)) {
  4821.                         if (isset($description['type'])) {
  4822.                             $type $description['type'];
  4823.                         }
  4824.                     }
  4825.                     $json .= str_replace(['<value>''<label>'], [$contenidos['id'].'|'.$type.'|'.$contenidos['url'], $contenidos['title']], $json_template);
  4826.                 }
  4827.                 $json = \rtrim($json'-');
  4828.             } else {
  4829.                 $json 'NN:No hay Resultados';
  4830.             }
  4831.             $response = \rtrim($json'*');
  4832.             return new Response($response);
  4833.         } else {
  4834.             return new Response('Acceso Restringido');
  4835.         }
  4836.     }
  4837.     public function quotationAction(Request $fullRequestAviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandler, \Swift_Mailer $mailerExceptionLog $exceptionLogPdf $pdfRouterInterface $routerTwigFolder $twigFolderManagerRegistry $registryParameterBagInterface $parameterBag)
  4838.     {
  4839.         $projectDir $parameterBag->get('kernel.project_dir');
  4840.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  4841.         $codImg null;
  4842.         $session $this->session;
  4843.         $agency $this->agency;
  4844.         $transactionId $session->get($transactionIdSessionName);
  4845.         $prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
  4846.         $agencyFolder $twigFolder->twigFlux();
  4847.         $response simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
  4848.         $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  4849.         $detailHotelRaw $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay;
  4850.         $locationHotel $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo->Position;
  4851.         $dateIn strtotime((string) $response->Message->OTA_HotelRoomListRS['StartDate']);
  4852.         $dateOut strtotime((string) $response->Message->OTA_HotelRoomListRS['EndDate']);
  4853.         $postDataJson $session->get($transactionId.'[hotel][detail_data_hotel]');
  4854.         if ($session->has($transactionId.'[crossed]'.'[url-hotel]')) {
  4855.             $urlAvailability $session->get($transactionId.'[crossed]'.'[url-hotel]');
  4856.         } elseif ($session->has($transactionId.'[hotel][availability_url]')) {
  4857.             $urlAvailability $session->get($transactionId.'[hotel][availability_url]');
  4858.         } else {
  4859.             $urlAvailability $session->get($transactionId.'[availability_url]');
  4860.         }
  4861.         $routeParsed parse_url($urlAvailability);
  4862.         $availabilityUrl $router->match($routeParsed['path']);
  4863.         $rooms = [];
  4864.         $adults 0;
  4865.         $childs 0;
  4866.         if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
  4867.             for ($i 1$i <= $availabilityUrl['rooms']; ++$i) {
  4868.                 $adults += $availabilityUrl['adult'.$i];
  4869.                 $childrens = [];
  4870.                 if ('n' != $availabilityUrl['child'.$i]) {
  4871.                     $childAgesTemp explode('-'$availabilityUrl['child'.$i]);
  4872.                     $childs += count($childAgesTemp);
  4873.                 }
  4874.             }
  4875.         }
  4876.         else {
  4877.             $data json_decode($session->get($transactionId '[hotel][availability_data_hotel]'));
  4878.             if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
  4879.                 $availabilityData json_decode(base64_decode($data->attributes), true);
  4880.             } else {
  4881.                 $availabilityData json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
  4882.             }
  4883.             if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
  4884.                 for ($i 0$i $availabilityData['Rooms']; ++$i) {
  4885.                     $adults += $availabilityData['Adults'.$i] ?? 0;
  4886.                     if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
  4887.                         $childs += $availabilityData['Children'.$i];
  4888.                     }
  4889.                 }
  4890.             }
  4891.         }
  4892.         $detailHotel = [
  4893.             'dateIn' => $dateIn,
  4894.             'dateOut' => $dateOut,
  4895.             'roomInformation' => $rooms,
  4896.             'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
  4897.             'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
  4898.             'nights' => floor(($dateOut $dateIn) / (24 60 60)),
  4899.             'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
  4900.             'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
  4901.             'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'] ?? $availabilityData['Rooms'] ?? $availabilityUrl['rooms'],
  4902.             'timeSpan' => $detailHotelRaw->TimeSpan,
  4903.             'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
  4904.             'total' => $detailHotelRaw->Total,
  4905.             'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
  4906.             'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
  4907.             'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
  4908.             'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
  4909.             'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
  4910.             'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  4911.             'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
  4912.             'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
  4913.             'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
  4914.             'prepaymentsInfo' => $prepaymentInfo,
  4915.             'namesClient' => $fullRequest->request->get('quotationName'),
  4916.             'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
  4917.             'emailClient' => $fullRequest->request->get('quotationEmail'),
  4918.             'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
  4919.             'priceCurrency' => $fullRequest->request->get('quotationCurrency'),
  4920.             'typeRoom' => $fullRequest->request->get('typeRoom'),
  4921.             'infoTerms' => $fullRequest->request->get('quotationTerms'),
  4922.             'infoComments' => $fullRequest->request->get('quotationComments'),
  4923.             'longitude' => $locationHotel['Longitude'],
  4924.             'latitude' => $locationHotel['Latitude'],
  4925.         ];
  4926.         //'src/Aviatur/TwigBundle/Resources/views/aviatur/Flux/Hotel/Hotel/quotation.html.twig'
  4927.         $html $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/quotation.html.twig');
  4928.         $namefilepdf 'Aviatur_cotizacion_hotel_'.$transactionId.'.pdf';
  4929.         $voucherCruiseFile $projectDir.'/app/quotationLogs/hotelQuotation/'.$namefilepdf.'.pdf';
  4930.         if ('N' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
  4931.             $codImg $additionalUserFront->EMPRESA;
  4932.         } elseif ('S' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
  4933.             $codImg $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
  4934.         }
  4935.         $imgAgency 'assets/common_assets/img/offices/'.$codImg.'.png';
  4936.         if (!file_exists($imgAgency)) {
  4937.             $codImg 10;
  4938.         }
  4939.         $subject 'Cotización de Hotel';
  4940.         try {
  4941.             if (!file_exists($voucherCruiseFile)) {
  4942.                 $pdf->setOption('page-size''Legal');
  4943.                 $pdf->setOption('margin-top'0);
  4944.                 $pdf->setOption('margin-right'0);
  4945.                 $pdf->setOption('margin-bottom'0);
  4946.                 $pdf->setOption('margin-left'0);
  4947.                 $pdf->setOption('orientation''portrait');
  4948.                 $pdf->setOption('enable-javascript'true);
  4949.                 $pdf->setOption('no-stop-slow-scripts'true);
  4950.                 $pdf->setOption('no-background'false);
  4951.                 $pdf->setOption('lowquality'false);
  4952.                 $pdf->setOption('encoding''utf-8');
  4953.                 $pdf->setOption('images'true);
  4954.                 $pdf->setOption('dpi'300);
  4955.                 $pdf->setOption('enable-external-links'true);
  4956.                 $pdf->setOption('enable-internal-links'true);
  4957.                 $pdf->generateFromHtml($this->renderView($html, [
  4958.                             'dateIn' => $dateIn,
  4959.                             'dateOut' => $dateOut,
  4960.                             'roomInformation' => $rooms,
  4961.                             'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
  4962.                             'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
  4963.                             'nights' => floor(($dateOut $dateIn) / (24 60 60)),
  4964.                             'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
  4965.                             'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
  4966.                             'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'],
  4967.                             'timeSpan' => $detailHotelRaw->TimeSpan,
  4968.                             'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
  4969.                             'total' => $detailHotelRaw->Total,
  4970.                             'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
  4971.                             'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
  4972.                             'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
  4973.                             'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
  4974.                             'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
  4975.                             'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  4976.                             'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
  4977.                             'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
  4978.                             'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
  4979.                             'prepaymentsInfo' => $prepaymentInfo,
  4980.                             'namesClient' => $fullRequest->request->get('quotationName'),
  4981.                             'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
  4982.                             'emailClient' => $fullRequest->request->get('quotationEmail'),
  4983.                             'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
  4984.                             'priceCurrency' => $fullRequest->request->get('quotationCurrency'),
  4985.                             'typeRoom' => $fullRequest->request->get('typeRoom'),
  4986.                             'infoTerms' => $fullRequest->request->get('quotationTerms'),
  4987.                             'infoComments' => $fullRequest->request->get('quotationComments'),
  4988.                             'longitude' => $locationHotel['Longitude'],
  4989.                             'latitude' => $locationHotel['Latitude'],
  4990.                             'codImg' => $codImg,
  4991.                         ]), $voucherCruiseFile);
  4992.             }
  4993.             $messageEmail = (new \Swift_Message())
  4994.                 ->setContentType('text/html')
  4995.                 ->setFrom($session->get('emailNoReply'))
  4996.                 ->setTo($additionalUserFront->CORREO_ELECTRONICO)
  4997.                 ->setSubject($session->get('agencyShortName').' - '.$subject)
  4998.                 ->attach(\Swift_Attachment::fromPath($voucherCruiseFile))
  4999.                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
  5000.                     'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  5001.                     'codImg' => $codImg,
  5002.                 ]), 'text/html');
  5003.         } catch (\Exception $ex) {
  5004.             if (file_exists($voucherCruiseFile)) {
  5005.                 $messageEmail = (new \Swift_Message())
  5006.                     ->setContentType('text/html')
  5007.                     ->setFrom($session->get('emailNoReply'))
  5008.                     ->setTo($additionalUserFront->CORREO_ELECTRONICO)
  5009.                     ->setSubject($session->get('agencyShortName').' - '.$subject)
  5010.                     ->attach(\Swift_Attachment::fromPath($voucherCruiseFile))
  5011.                     ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
  5012.                         'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  5013.                         'codImg' => $codImg,
  5014.                     ]), 'text/html');
  5015.             } else {
  5016.                 $messageEmail = (new \Swift_Message())
  5017.                     ->setContentType('text/html')
  5018.                     ->setFrom($session->get('emailNoReply'))
  5019.                     ->setTo($additionalUserFront->CORREO_ELECTRONICO)
  5020.                     ->setBcc(['sebastian.huertas@aviatur.com'])
  5021.                     ->setSubject($session->get('agencyShortName').' - '.$subject)
  5022.                     ->setBody('No se generó la cotización del hotel.');
  5023.             }
  5024.         }
  5025.         try {
  5026.             $mailer->send($messageEmail);
  5027.         } catch (Exception $ex) {
  5028.             $exceptionLog->log(var_dump('aviatur_cotizacion_hotel_'.$transactionId), $ex);
  5029.         }
  5030.         unlink($voucherCruiseFile);
  5031.         $this->saveInformationCGS($aviaturLogSave$aviaturWebService$aviaturErrorHandler$registry$detailHotel$additionalUserFront$agency);
  5032.         //($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Agent/Default/menu_agent.html.twig'), ['agent' => $nombreagente, 'email' => $emailuser, 'adminAgent' => $adminAgent])
  5033.         $factor = [
  5034.             'dateIn' => $dateIn,
  5035.             'dateOut' => $dateOut,
  5036.             'roomInformation' => $rooms,
  5037.             'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
  5038.             'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
  5039.             'nights' => floor(($dateOut $dateIn) / (24 60 60)),
  5040.             'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
  5041.             'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
  5042.             'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'],
  5043.             'timeSpan' => $detailHotelRaw->TimeSpan,
  5044.             'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
  5045.             'total' => $detailHotelRaw->Total,
  5046.             'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
  5047.             'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
  5048.             'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
  5049.             'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
  5050.             'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
  5051.             'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  5052.             'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
  5053.             'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
  5054.             'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
  5055.             'prepaymentsInfo' => $prepaymentInfo,
  5056.             'namesClient' => $fullRequest->request->get('quotationName'),
  5057.             'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
  5058.             'emailClient' => $fullRequest->request->get('quotationEmail'),
  5059.             'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
  5060.             'priceCurrency' => $fullRequest->request->get('quotationCurrency'),
  5061.             'typeRoom' => $fullRequest->request->get('typeRoom'),
  5062.             'infoTerms' => $fullRequest->request->get('quotationTerms'),
  5063.             'infoComments' => $fullRequest->request->get('quotationComments'),
  5064.             'longitude' => $locationHotel['Longitude'],
  5065.             'latitude' => $locationHotel['Latitude'],
  5066.             'codImg' => $codImg,
  5067.         ];
  5068.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/quotation.html.twig'),$factor);
  5069.     }
  5070.     public function saveInformationCGS(AviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registry$data$customer$agency)
  5071.     {
  5072.         $parametersLogin $this->managerRegistry->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency'aviatur_service_login_cgs');
  5073.         $urlLoginCGS $parametersLogin[0]['value'];
  5074.         $parametersProduct $this->managerRegistry->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency'aviatur_service_hotel_cgs');
  5075.         $urlAddProductHotel $parametersProduct[0]['value'];
  5076.         /*
  5077.          * get token api autentication
  5078.          */
  5079.         $userLoginCGS $aviaturWebService->encryptUser(trim(strtolower($customer->CODIGO_USUARIO)), 'AviaturCGSMTK');
  5080.         $jsonReq json_encode(['username' => $userLoginCGS]);
  5081.         //print_r(json_encode($data)); die;
  5082.         $curl curl_init();
  5083.         curl_setopt_array($curl, [
  5084.             CURLOPT_URL => $urlLoginCGS,
  5085.             CURLOPT_RETURNTRANSFER => true,
  5086.             CURLOPT_SSL_VERIFYPEER => false,
  5087.             CURLOPT_ENCODING => '',
  5088.             CURLOPT_MAXREDIRS => 10,
  5089.             CURLOPT_TIMEOUT => 0,
  5090.             CURLOPT_FOLLOWLOCATION => true,
  5091.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5092.             CURLOPT_CUSTOMREQUEST => 'POST',
  5093.             CURLOPT_POSTFIELDS => $jsonReq,
  5094.             CURLOPT_HTTPHEADER => [
  5095.                 'Content-Type: application/json',
  5096.             ],
  5097.         ]);
  5098.         $response curl_exec($curl);
  5099.         $httpcode curl_getinfo($curlCURLINFO_HTTP_CODE);
  5100.         curl_close($curl);
  5101.         if (200 != $httpcode) {
  5102.             $aviaturLogSave->logSave('HTTPCODE: '.$httpcode.' Error usuario: '.strtolower($customer->CODIGO_USUARIO), 'CGS''CGSHOTEL_ERRORLOGIN');
  5103.             $aviaturLogSave->logSave(print_r($responsetrue), 'CGS''responseHotelCGS');
  5104.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/hoteles''Error Login''Error Login'));
  5105.         } else {
  5106.             $tokenInfoApiQuotation json_decode($response);
  5107.             $tokenApiQuotation $tokenInfoApiQuotation->TOKEN;
  5108.         }
  5109.         ini_set('xdebug.var_display_max_depth''-1');
  5110.         ini_set('xdebug.var_display_max_children''-1');
  5111.         ini_set('xdebug.var_display_max_data''-1');
  5112.         //var_dump($data['priceTotalQuotation']); die;
  5113.         /**
  5114.          * Begin API data send.
  5115.          */
  5116.         $ages '';
  5117.         $roms '';
  5118.         $roms_collection '';
  5119.         $separate '';
  5120.         for ($i 1$i <= (is_countable($data['roomInformation']) ? count($data['roomInformation']) : 0); ++$i) {
  5121.             $ages '';
  5122.             for ($a 0$a < (is_countable($data['roomInformation'][$i]['child']) ? count($data['roomInformation'][$i]['child']) : 0); ++$a) {
  5123.                 if (!== $a) {
  5124.                     $ages .= ','.'"'.$data['roomInformation'][$i]['child'][$a].'"';
  5125.                 } else {
  5126.                     $ages .= '"'.$data['roomInformation'][$i]['child'][$a].'"';
  5127.                 }
  5128.             }
  5129.             if (!== $i) {
  5130.                 $separate ',';
  5131.             } else {
  5132.                 $separate '';
  5133.             }
  5134.             $roms .= $separate.'{
  5135.                     "adultOcupancy": '.$data['roomInformation'][$i]['adult'].',
  5136.                     "availCount": null,
  5137.                     "boardCode": null,
  5138.                     "boardName": null,
  5139.                     "boardShortName": null,
  5140.                     "boardType": null,
  5141.                     "cancellationPolicies": [
  5142.                         {
  5143.                             "amount": null,
  5144.                             "dateFrom": "'.$data['prepaymentsInfo']['Message']['OTA_HotelResRS']['HotelReservations']['RoomStays']['TPA_Extensions']['CancellationPolicy']['FechaEntradaGasto'].'",
  5145.                             "respaldoFechaSalida": "'.$data['dateOutStr'].'",
  5146.                             "time": "'.$data['prepaymentsInfo']['Message']['OTA_HotelResRS']['HotelReservations']['RoomStays']['TPA_Extensions']['CancellationPolicy']['HoraFechaEntradaGasto'].'"
  5147.                         }
  5148.                     ],
  5149.                     "childAges": [
  5150.                         '.$ages.'
  5151.                     ],
  5152.                     "childOcupancy": '.(is_countable($data['roomInformation'][$i]['child']) ? count($data['roomInformation'][$i]['child']) : 0).',
  5153.                     "onRequest": null,
  5154.                     "price": null,
  5155.                     "roomCharacteristic": null,
  5156.                     "roomCharacteristicCode": null,
  5157.                     "roomCode": null,
  5158.                     "roomCount": null,
  5159.                     "roomType": null,
  5160.                     "shrui": null
  5161.                 }';
  5162.         }
  5163.         $data_send '{
  5164.             "customer":{
  5165.                "billingInformations":[
  5166.                 {
  5167.                   "active": true,
  5168.                   "agencyContact": "string",
  5169.                   "city": "'.$data['basicInfos']->Address->CityName.'",
  5170.                   "colony": "string",
  5171.                   "country": "string",
  5172.                   "dateCreated": "2020-05-21T23:20:30.441Z",
  5173.                   "email": "string",
  5174.                   "extNumber": "string",
  5175.                   "id": 0,
  5176.                   "intNumber": "string",
  5177.                   "lastUpdated": "2020-05-21T23:20:30.441Z",
  5178.                   "official": "string",
  5179.                   "phone": {
  5180.                     "active": true,
  5181.                     "dateCreated": "2020-05-21T23:20:30.441Z",
  5182.                     "id": 0,
  5183.                     "lastUpdated": "2020-05-21T23:20:30.441Z",
  5184.                     "number": "string",
  5185.                     "type": "string",
  5186.                     "version": 0
  5187.                   },
  5188.                   "postalCode": "string",
  5189.                   "representation": "string",
  5190.                   "rfc": "string",
  5191.                   "state": "string",
  5192.                   "status": "string",
  5193.                   "street": "string",
  5194.                   "taxRegime": "string",
  5195.                   "version": 0
  5196.                 }
  5197.               ],
  5198.                "birthDate":"true",
  5199.                "city": "'.$data['basicInfos']->Address->CityName.'",
  5200.                "dateCreated":"0001-01-01T00:00:00",
  5201.                "dateOfBirth":"0001-01-01T00:00:00",
  5202.                "document":null,
  5203.                "emails":[
  5204.                     {
  5205.                         "active": true,
  5206.                         "dateCreated": "'.date('Y-m-d').'",
  5207.                         "emailAddress": "'.$data['emailClient'].'",
  5208.                         "id": 0,
  5209.                         "lastUpdated": "'.date('Y-m-d').'",
  5210.                         "version": 0
  5211.                   }
  5212.                ],
  5213.                "exchangeRateInformations":null,
  5214.                "firstName":"'.$data['namesClient'].'",
  5215.                "fullName":"'.$data['namesClient'].' '.$data['lastnamesClient'].'",
  5216.                "gender":null,
  5217.                "id":null,
  5218.                "idAccount":null,
  5219.                "idIntelisis":null,
  5220.                "idUserOwner":null,
  5221.                "identify":null,
  5222.                "interestsForExpo":null,
  5223.                "lastName":"'.$data['lastnamesClient'].'",
  5224.                "lastUpdated":"0001-01-01T00:00:00",
  5225.                "mothersName":null,
  5226.                "phones":[
  5227.                   {
  5228.                      "active":false,
  5229.                      "dateCreated":"0001-01-01T00:00:00",
  5230.                      "id":0,
  5231.                      "lastUpdated":"0001-01-01T00:00:00",
  5232.                      "number":null,
  5233.                      "type":null,
  5234.                      "version":0
  5235.                   }
  5236.                ],
  5237.                "typeContact":null
  5238.             },
  5239.             "quote":null,
  5240.             "selectedProduct":{
  5241.                "associatedProductIndex":null,
  5242.                "category": "'.$data['category']['Code'].'",
  5243.                 "complementProductList": null,
  5244.                "deleteInfo":null,
  5245.                "description":"'.$data['description'].'",
  5246.                "packageName":"'.$data['basicInfos']['HotelName'].'",
  5247.                "discount":null,
  5248.                "emit":false,
  5249.                "fareData":{
  5250.                   "aditionalFee":0.0,
  5251.                   "airpotService":null,
  5252.                   "baseFare":'.str_replace('.'''$data['priceTotalQuotation']).',
  5253.                   "cO":0.0,
  5254.                   "commission":0.0,
  5255.                   "commissionPercentage":0.0,
  5256.                   "complements":null,
  5257.                   "currency":{
  5258.                      "type":"'.$data['priceCurrency'].'"
  5259.                   },
  5260.                   "equivFare":0.0,
  5261.                   "iva":0.0,
  5262.                   "otherDebit":null,
  5263.                   "otherTax":null,
  5264.                   "price":'.str_replace('.'''$data['priceTotalQuotation']).',
  5265.                   "providerPrice":0.0,
  5266.                   "qSe":0.0,
  5267.                   "qSeIva":0.0,
  5268.                   "qse":null,
  5269.                   "revenue":0.0,
  5270.                   "serviceCharge":0.0,
  5271.                   "sureCancel":null,
  5272.                   "tA":0.0,
  5273.                   "taIva":0.0,
  5274.                   "tax":0.0,
  5275.                   "total":'.str_replace('.'''$data['priceTotalQuotation']).',
  5276.                   "yQ":0.0,
  5277.                   "yQiva":0.0
  5278.                },
  5279.                "foodPlan":null,
  5280.                "hotelDetail":{
  5281.                    "nightCount": '.$data['nights'].',
  5282.                    "roomCount": '.$data['rooms'].'
  5283.                },
  5284.                "index":null,
  5285.                "itinerary": {
  5286.                    "availToken": null,
  5287.                    "category": null,
  5288.                    "cdChain": null,
  5289.                    "code": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['BasicPropertyInfo']['HotelCode'].'",
  5290.                    "codeCurrency": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['Total']['CurrencyCode'].'",
  5291.                    "contractIncommingOffice": null,
  5292.                    "contractName": null,
  5293.                    "dateFrom": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['TimeSpan']['End'].'",
  5294.                    "dateTo": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['TimeSpan']['Start'].'",
  5295.                    "echoToken": null,
  5296.                    "issueFrom": null,
  5297.                    "issueTo": null,
  5298.                    "location": [
  5299.                    ],
  5300.                    "nbChain": null,
  5301.                    "nuStars": "'.$data['category']['Code'].'",
  5302.                    "pointOfInterest": null,
  5303.                    "promo": null,
  5304.                    "rooms": [
  5305.                         '.$roms.'
  5306.                    ],
  5307.                    "topSale": null,
  5308.                    "txDescription": "'.$data['description'].'",
  5309.                    "txDestination": "'.$data['basicInfos']->Address->CityName.'",
  5310.                    "txImage": "'.$data['photos']['ImageFormat']['URL'].'",
  5311.                    "txIssues": null,
  5312.                    "txName": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['BasicPropertyInfo']['HotelName'].'",
  5313.                    "txPrice": "'.$data['priceTotalQuotation'].'",
  5314.                    "txZone": null
  5315.                },
  5316.                "locatorList":[
  5317.                ],
  5318.                "passengerDataList":[
  5319.                   {
  5320.                      "age":"0",
  5321.                      "birthday":"1899-12-31T19:00:00-05:00",
  5322.                      "fareData":{
  5323.                         "aditionalFee":0.0,
  5324.                         "airpotService":null,
  5325.                         "baseFare":0.0,
  5326.                         "cO":0.0,
  5327.                         "commission":0.0,
  5328.                         "commissionPercentage":0.0,
  5329.                         "complements":null,
  5330.                         "currency":null,
  5331.                         "equivFare":0.0,
  5332.                         "iva":0.0,
  5333.                         "otherDebit":null,
  5334.                         "otherTax":null,
  5335.                         "price":0.0,
  5336.                         "providerPrice":0.0,
  5337.                         "qSe":0.0,
  5338.                         "qSeIva":0.0,
  5339.                         "qse":null,
  5340.                         "revenue":0.0,
  5341.                         "serviceCharge":0.0,
  5342.                         "sureCancel":null,
  5343.                         "tA":0.0,
  5344.                         "taIva":0.0,
  5345.                         "tax":0.0,
  5346.                         "total": '.str_replace('.'''$data['priceTotalQuotation']).',
  5347.                         "yQ":0.0,
  5348.                         "yQiva":0.0
  5349.                      },
  5350.                      "gender":"",
  5351.                      "id":"",
  5352.                      "lastName":"",
  5353.                      "mail":"",
  5354.                      "mothersName":"",
  5355.                      "name":"",
  5356.                      "passengerCode":{
  5357.                         "accountCode":"",
  5358.                         "promo":false,
  5359.                         "realType":"ADT",
  5360.                         "type":"ADT"
  5361.                      },
  5362.                      "passengerContact":null,
  5363.                      "passengerInsuranceInfo":null,
  5364.                      "phone":null
  5365.                   }
  5366.                ],
  5367.                "priority":"",
  5368.                "productType":{
  5369.                   "description":"Hotel",
  5370.                   "typeProduct":"Hotel"
  5371.                },
  5372.                "quoteHost":null,
  5373.                "reservationInfo":null,
  5374.                "reserveProductLogList":null,
  5375.                "roomType": null,
  5376.                "route":{
  5377.                    "arrivalDate": "'.$data['dateOutStr'].'",
  5378.                    "arrivalDateString": "'.$data['dateOutStr'].'",
  5379.                    "arrivalDescription": "'.$data['basicInfos']->Address->CityName.'",
  5380.                    "arrivalIATA": null,
  5381.                    "departureDate": "'.$data['dateInStr'].'",
  5382.                    "departureDateString": "'.$data['dateInStr'].'",
  5383.                    "departureDescription": null,
  5384.                    "departureIATA": null,
  5385.                    "destination": "'.$data['basicInfos']->Address->CityName.'",
  5386.                    "flightTime": null,
  5387.                    "origin": null,
  5388.                    "providerCode": null,
  5389.                    "subRoutes": null
  5390.                },
  5391.                "savedPassenger":false,
  5392.                "searchHost":null,
  5393.                "selected":false,
  5394.                "serviceProvider": {
  5395.                  "code": "'.$data['prepaymentsInfo']['ProviderResults']['ProviderResult']['Provider'].'"
  5396.                 },
  5397.                "stayTime":null
  5398.             },
  5399.             "quote": {"channel":"B2C WEB"}
  5400.          }';
  5401.         $authorization 'Authorization: Bearer '.$tokenApiQuotation;
  5402.         //API URL
  5403.         $url $urlAddProductHotel;
  5404.         //create a new cURL resource
  5405.         $ch curl_init($url);
  5406.         //setup request to send json via POST
  5407.         $payload $data_send;
  5408.         //attach encoded JSON string to the POST fields
  5409.         curl_setopt($chCURLOPT_POSTFIELDS$payload);
  5410.         //set the content type to application/json
  5411.         curl_setopt($chCURLOPT_HTTPHEADER, [
  5412.             'accept: application/json',
  5413.             'authorization: Bearer '.$tokenApiQuotation,
  5414.             'content-type: application/json',
  5415.         ]);
  5416.         curl_setopt($chCURLOPT_CUSTOMREQUEST'POST');
  5417.         curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  5418.         curl_setopt($chCURLOPT_MAXREDIRS10);
  5419.         curl_setopt($chCURLOPT_TIMEOUT0);
  5420.         curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  5421.         curl_setopt($chCURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_1);
  5422.         //return response instead of outputting
  5423.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  5424.         //execute the POST request
  5425.         $result curl_exec($ch);
  5426.         //close CURL resource
  5427.         curl_close($ch);
  5428.         /*
  5429.          * End API data send
  5430.          */
  5431.     }
  5432.     public function consultRoommlistAction(Request $fullRequestAviaturWebService $aviaturWebServiceRouterInterface $router)
  5433.     {
  5434.         $provider null;
  5435.         $fullPricing null;
  5436.         $request $fullRequest->request;
  5437.         $em $this->managerRegistry;
  5438.         $session $this->session;
  5439.         $agency $this->agency;
  5440.         $domain $fullRequest->getHost();
  5441.         $route $router->match(str_replace($fullRequest->getSchemeAndHttpHost(), ''$fullRequest->getUri()));
  5442.         $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  5443.         $isFront $session->has('operatorId');
  5444.         $configsHotelAgency $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
  5445.         $validate true;
  5446.         $inputsRequest = ['correlationId''startDate''endDate''providerID''hotelCode''country'];
  5447.         foreach ($inputsRequest as $input) {
  5448.             if (!$request->get($input)) {
  5449.                 $validate false;
  5450.             }
  5451.         }
  5452.         if (!$validate) {
  5453.             return $this->redirect($this->generateUrl('aviatur_search_hotels'));
  5454.         }
  5455.         foreach ($configsHotelAgency as $configHotelAgency) {
  5456.             if ($request->get('providerID') == $configHotelAgency->getProvider()->getProvideridentifier()) {
  5457.                 $provider $configHotelAgency->getProvider();
  5458.             }
  5459.         }
  5460.         $correlationID $request->get('correlationId');
  5461.         $startDate $request->get('startDate');
  5462.         $endDate $request->get('endDate');
  5463.         $dateIn strtotime($startDate);
  5464.         $dateOut strtotime($endDate);
  5465.         $nights floor(($dateOut $dateIn) / (24 60 60));
  5466.         $searchHotelCodes = ['---''--'];
  5467.         $replaceHotelCodes = ['/''|'];
  5468.         $hotelCode explode('-'str_replace($searchHotelCodes$replaceHotelCodes$request->get('hotelCode')));
  5469.         $country $request->get('country');
  5470.         $variable = [
  5471.             'correlationId' => $correlationID,
  5472.             'start_date' => $startDate,
  5473.             'end_date' => $endDate,
  5474.             'hotel_code' => $hotelCode[0],
  5475.             'country' => $country,
  5476.             'ProviderId' => $provider->getProvideridentifier(),
  5477.         ];
  5478.         $hotelModel = new HotelModel();
  5479.         $xmlRequest $hotelModel->getXmlDetail();
  5480.         $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''HotelRoomList''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse);
  5481.         if (!isset($response['error'])) {
  5482.             $markup $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->find($hotelCode[1]);
  5483.             $markupValue $markup->getValue();
  5484.             $markupId $markup->getId();
  5485.             $parametersJson $session->get($domain.'[parameters]');
  5486.             $parameters json_decode($parametersJson);
  5487.             $tax = (float) $parameters->aviatur_payment_iva;
  5488.             $currency 'COP';
  5489.             if (strpos($provider->getName(), '-USD')) {
  5490.                 $currency 'USD';
  5491.             }
  5492.             $currencyCode = (string) $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
  5493.             if ('COP' != $currencyCode && 'COP' == $currency) {
  5494.                 $trm $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
  5495.                 $trm $trm[0]['value'];
  5496.             } else {
  5497.                 $trm 1;
  5498.             }
  5499.             $count 0;
  5500.             foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay as $key => $roomStay) {
  5501.                 $roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markupId;
  5502.                 foreach ($roomStay->RoomRates->RoomRate as $roomRate) {
  5503.                     if (== $count) {
  5504.                         if ('N' == $markup->getConfigHotelAgency()->getType()) {
  5505.                             $aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markupValue / (100 $markupValue);
  5506.                         } else {
  5507.                             $aviaturMarkup 0;
  5508.                         }
  5509.                         $roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
  5510.                         if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
  5511.                             $roomRate->Total['AmountAviaturMarkupTax'] = 0;
  5512.                         } else {
  5513.                             $roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup $tax;
  5514.                         }
  5515.                         $roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
  5516.                         $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round((float) ($aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
  5517.                         if ('COP' == $currencyCode) {
  5518.                             $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
  5519.                         }
  5520.                         if (isset($roomRate->Total['RateOverrideIndicator']) || (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces']))) {
  5521.                             $roomRate->TotalAviatur['AmountTax'] = 0;
  5522.                         } else {
  5523.                             $roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
  5524.                         }
  5525.                         $roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
  5526.                         $fullPricing = [
  5527.                             'total' => (float) $roomRate->TotalAviatur['AmountTotal'] * $nights,
  5528.                             'totalPerNight' => (float) $roomRate->TotalAviatur['AmountTotal'],
  5529.                         ];
  5530.                         $roomRate->TotalAviatur['FullPricing'] = base64_encode(json_encode($fullPricing));
  5531.                     }
  5532.                     ++$count;
  5533.                 }
  5534.             }
  5535.         } else {
  5536.             $fullPricing = [
  5537.                 'total' => (float) 0,
  5538.                 'totalPerNight' => 0,
  5539.             ];
  5540.         }
  5541.         return $this->json($fullPricing);
  5542.     }
  5543.     protected function authenticateUser(UserInterface $userLoginManager $loginManager)
  5544.     {
  5545.         try {
  5546.             $loginManager->loginUser(
  5547.                 'main',
  5548.                 $user
  5549.             );
  5550.         } catch (AccountStatusException $ex) {
  5551.             // We simply do not authenticate users which do not pass the user
  5552.             // checker (not enabled, expired, etc.).
  5553.         }
  5554.     }
  5555.     /**
  5556.      * Sobrescribe el método 'json' de la clase 'AbstractController'.
  5557.      *
  5558.      * @param mixed $data Los datos a serializar en json.
  5559.      * @param int $status El código de estado de la respuesta HTTP.
  5560.      * @param array $headers Un array de encabezados de respuesta HTTP.
  5561.      * @param array $context Opciones para el contexto del serializador.
  5562.      *
  5563.      * @return JsonResponse
  5564.     */
  5565.     public function json($dataint $status 200, array $headers = [], array $context = []): JsonResponse
  5566.     {
  5567.         if (! isset($context['responseHotelDetail'])) {
  5568.             $jsonResponse=parent::json($data$status$headers$context);
  5569.         } else {
  5570.             $isSerializableValidResponse=TRUE;
  5571.             if ($this->multiCustomUtils->isObjectInArray($data)) {
  5572.                 $isSerializableValidResponse=FALSE;
  5573.             }
  5574.             if ($isSerializableValidResponse) {
  5575.                 $jsonResponse=parent::json($data$status$headers$context);
  5576.             } else {
  5577.                 $jsonResponse= new JsonResponse($data);
  5578.             }
  5579.         }
  5580.         return $jsonResponse;
  5581.     }
  5582.     /**
  5583.      * Obtiene las coordenadas (latitud y longitud) para un código IATA.
  5584.      *
  5585.      * @param string $iata Código IATA de la ciudad.
  5586.      * @return array|null Array con 'latitude' y 'longitude', o null si no se encuentra.
  5587.      * @throws \InvalidArgumentException Si el código IATA es inválido.
  5588.      */
  5589.     public function getCoordinatesByIata(string $iata): ?array
  5590.     {
  5591.         // Validar que el código IATA no sea vacío ni inválido.
  5592.         if (empty($iata) || !preg_match('/^[A-Z]{3}$/'$iata)) {
  5593.             throw new \InvalidArgumentException('El código IATA proporcionado no es válido.');
  5594.         }
  5595.         $em $this->managerRegistry;
  5596.         // Obtener el repositorio basado en la entidad SearchCities.
  5597.         $repositorySearchCities $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class);
  5598.         // Buscar la ciudad por su código IATA.
  5599.         $city $repositorySearchCities->findOneBy(['iata' => $iata]);
  5600.         // Si no se encuentra la ciudad, retornar null.
  5601.         if (!$city) {
  5602.             return null;
  5603.         }
  5604.         // Decodificar el JSON almacenado en el campo 'coordinates'.
  5605.         try {
  5606.             $coordinates json_decode($city->getCoordinates(), true512JSON_THROW_ON_ERROR);
  5607.             $city $city->getCity();
  5608.             // $country = $city->getCountryCode();
  5609.         } catch (\JsonException $e) {
  5610.             // Si el JSON está mal formado, arrojar una excepción o manejar el error.
  5611.             throw new \RuntimeException('Error al decodificar el campo coordinates: ' $e->getMessage());
  5612.         }
  5613.         // Verificar que latitud y longitud estén presentes en el JSON decodificado.
  5614.         if (!isset($coordinates['latitude'], $coordinates['longitude'])) {
  5615.             throw new \RuntimeException('El JSON no contiene los campos requeridos: latitude y longitude.');
  5616.         }
  5617.         // Retornar la latitud y longitud.
  5618.         return [
  5619.             'latitude' => $coordinates['latitude'],
  5620.             'longitude' => $coordinates['longitude'],
  5621.             'city' => $city,
  5622.             'country' => 'co',
  5623.         ];
  5624.     }
  5625.    /**
  5626.      * @Route("/build-url/{iata}/{checkIn}+{checkOut}/{adults}+{children}", name="redirect_to_coordinates")
  5627.      *
  5628.      * @param string $iata Código IATA de la ciudad.
  5629.      * @param string $checkIn Fecha de entrada en formato YYYY-MM-DD.
  5630.      * @param string $checkOut Fecha de salida en formato YYYY-MM-DD.
  5631.      * @param string $adults Número de adultos.
  5632.      * @param string $children Número de niños o "n" si no hay niños.
  5633.      *
  5634.      * @return RedirectResponse
  5635.      */
  5636.     public function redirectToCoordinates(
  5637.         string $iata,
  5638.         string $checkIn,
  5639.         string $checkOut,
  5640.         string $adults,
  5641.         string $children
  5642.     ): RedirectResponse {
  5643.         try {
  5644.             $coordinates $this->getCoordinatesByIata($iata);
  5645.             $latitude 0;
  5646.             $longitude 0;
  5647.             $url 'https://api.opencagedata.com/geocode/v1/json';
  5648.             $params = [
  5649.                 //'key' => 'd4ea2db24f6448dcbb1551c3546851d6', // dev
  5650.                 'key' => 'd7c38ad65c694ffc82d29a4987e3f056'// prod
  5651.                 'q' => $coordinates['city'],
  5652.                 'no_annotations' => 1
  5653.             ];
  5654.             $queryString http_build_query($params);
  5655.             $requestUrl $url '?' $queryString;
  5656.             $ch curl_init();
  5657.             curl_setopt($chCURLOPT_URL$requestUrl);
  5658.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  5659.             curl_setopt($chCURLOPT_CUSTOMREQUEST'GET'); 
  5660.             curl_setopt($chCURLOPT_HTTPHEADER, [
  5661.                 'Content-Type: application/json'
  5662.             ]);
  5663.             $response curl_exec($ch);
  5664.             if (curl_errno($ch)) {
  5665.                 echo 'Error:' curl_error($ch);
  5666.             } else {
  5667.                 $data json_decode($responsetrue);
  5668.                 if (!empty($data['results']) && isset($data['results'][0]['geometry'])) {
  5669.                     $firstResult $data['results'][0]['geometry'];
  5670.                     $latitude $firstResult['lat'];
  5671.                     $longitude $firstResult['lng'];
  5672.                     $city $data['results'][0]['components']['_normalized_city'];
  5673.                     $country $data['results'][0]['components']['country_code'];
  5674.                 } else {
  5675.                     echo "No se encontraron resultados.\n";
  5676.                 }
  5677.             }
  5678.             curl_close($ch);
  5679.             $coordinateString "{$latitude},{$longitude}";
  5680.             
  5681.             $destination sprintf('%s(%s)'$city$country);
  5682.             $destinationUrl sprintf(
  5683.                 '/hoteles/avail/%s/%s/%s+%s/room=1&adults=%s&children=%s',
  5684.                 rawurlencode($destination), // Codificar el destino.
  5685.                 $coordinateString,
  5686.                 $checkIn,
  5687.                 $checkOut,
  5688.                 $adults,
  5689.                 $children
  5690.             );
  5691.             // Redirigir a la nueva URL.
  5692.             return $this->redirect($destinationUrl);
  5693.         } catch (\InvalidArgumentException $e) {
  5694.             // Manejar errores de validación del código IATA.
  5695.             return $this->json(['error' => $e->getMessage()], 400);
  5696.         } catch (\RuntimeException $e) {
  5697.             // Manejar otros errores como coordenadas no encontradas o JSON inválido.
  5698.             return $this->json(['error' => $e->getMessage()], 500);
  5699.         }
  5700.     }
  5701. }