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

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