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

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