src/Aviatur/ExperienceBundle/Controller/ExperienceController.php line 59

Open in your IDE?
  1. <?php
  2. namespace Aviatur\ExperienceBundle\Controller;
  3. use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
  4. use Aviatur\ExperienceBundle\Services\SearchExperienceCookie;
  5. use Aviatur\GeneralBundle\Controller\OrderController;
  6. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  7. use Aviatur\GeneralBundle\Models\GeneralModel;
  8. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  9. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  10. use Aviatur\GeneralBundle\Services\AviaturExperienceService;
  11. use Aviatur\GeneralBundle\Services\AviaturMailer;
  12. use Aviatur\GeneralBundle\Services\AviaturWebService;
  13. use Aviatur\GeneralBundle\Services\ExceptionLog;
  14. use Aviatur\PackageBundle\Models\PackageModel;
  15. use Aviatur\PaymentBundle\Controller\CashController;
  16. use Aviatur\PaymentBundle\Controller\P2PController;
  17. use Aviatur\PaymentBundle\Controller\PSEController;
  18. use Aviatur\PaymentBundle\Controller\SafetypayController;
  19. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  20. use Aviatur\PaymentBundle\Services\TokenizerService;
  21. use Aviatur\TwigBundle\Services\TwigFolder;
  22. use FOS\UserBundle\Model\UserInterface;
  23. use FOS\UserBundle\Security\LoginManagerInterface;
  24. use Knp\Snappy\Pdf;
  25. use Doctrine\Persistence\ManagerRegistry;
  26. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  27. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  28. use Symfony\Component\HttpFoundation\Cookie;
  29. use Symfony\Component\HttpFoundation\Request;
  30. use Symfony\Component\HttpFoundation\Response;
  31. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  32. use Symfony\Component\Routing\RouterInterface;
  33. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  34. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  35. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  36. use Aviatur\CustomerBundle\Services\PhoneNumberService;
  37. class ExperienceController extends AbstractController
  38. {
  39.     /**
  40.      * @var \Doctrine\Persistence\ObjectManager
  41.      */
  42.     protected $managerRegistry;
  43.     /**
  44.      * @var SessionInterface
  45.      */
  46.     protected $session;
  47.     protected $agency;
  48.     public function __construct(ManagerRegistry $registrySessionInterface $session)
  49.     {
  50.         $this->managerRegistry $registry->getManager();
  51.         $this->session $session;
  52.         $this->agency $this->managerRegistry->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  53.     }
  54.     public function searchAction()
  55.     {
  56.         return $this->redirect($this->generateUrl('aviatur_search_experiences', []));
  57.     }
  58.     public function availabilityAction(Request $requestTwigFolder $twigFolderAviaturErrorHandler $errorHandlerAviaturWebService $webServiceExceptionLog $exceptionLogSearchExperienceCookie $experienceCookie$destination1$date1 null$date2 null$trips)
  59.     {
  60.         $channel = [];
  61.         $providers = [];
  62.         $urlDescription = [];
  63.         $em $this->managerRegistry;
  64.         $session $this->session;
  65.         $server $request->server;
  66.         $referer $server->get('REQUEST_URI');
  67.         $fullRequest $request;
  68.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
  69.         $agency $this->agency;
  70.         $configExperienceAgency $em->getRepository(\Aviatur\ExperienceBundle\Entity\ConfigExperienceAgency::class)->findProviderForExperiencesWithAgency($agency);
  71.         $agencyFolder $twigFolder->twigFlux();
  72.         if (!$configExperienceAgency || !isset($configExperienceAgency[0])) {
  73.             return $this->redirect($errorHandler->errorRedirectNoEmail('/buscar/experiencias''Busqueda de resultados''No podemos realizar la consulta ya que no existe un proveedor configurado para este servicio'));
  74.         } else {
  75.             $provider $configExperienceAgency[0]->getProvider()->getProvideridentifier();
  76.         }
  77.         $info = [];
  78.         $channel['channel'] = $configExperienceAgency[0]->getChannel();
  79.         $OfficeId explode('-'$configExperienceAgency[0]->getOfficeid());
  80.         $channel['officeId'] = $OfficeId[1];
  81.         $keyword='';
  82.         if (strlen($destination1) > 3) {
  83.             $keyword $destination1;
  84.         } else {
  85.             $destinationObject $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination1);
  86.             if ('' == $destinationObject) {
  87.                 $destinationLabel=NULL;
  88.                 $destinationObject $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findOneByIata($destination1);
  89.                 if ($destinationObject) {
  90.                     $destination1 $destinationObject->getSearchCities()->getIata();
  91.                     $destinationLabel $destinationObject->getCity().', '.$destinationObject->getCountry().' ('.$destinationObject->getIata().')';
  92.                 }
  93.             } else {
  94.                 $destinationLabel $destinationObject->getCity().', '.$destinationObject->getCountry().' ('.$destinationObject->getIata().')';
  95.             }
  96.         }
  97.         if ($fullRequest->isXmlHttpRequest()) {
  98.             $tempDate1 = (null == $date1) ? date('Y-m-d') : $date1;
  99.             $info = [
  100.                 'Start' => $tempDate1,
  101.                 'End' => (null == $date2) ? $tempDate1 $date2,
  102.                 'Code' => $destination1,
  103.                 'IdChannel' => $channel['channel'],
  104.                 'OfficeId' => '',
  105.                 'keywords' => (isset($keyword) && null != $keyword) ? str_replace('-'' '$keyword) : null,
  106.                 'ProviderId' => $provider,
  107.                 'referer' => $referer,
  108.                 'destinationLabel' => $destinationLabel ?? null,
  109.             ];
  110.             // var_dump($session->get('whitemark'));
  111.             // die;
  112.             if ('aviaseguros' == $session->get('whitemark')) {
  113.                 if ('seguros' == $keyword) {
  114.                     $info['IdChannel'] = 4;
  115.                     $info['TypesOfService'] = 48;
  116.                 }
  117.             }
  118.             $generalModel = new GeneralModel();
  119.             $xmlTemplateExperiences $generalModel->getXmlExperiencesAvail($info);
  120.             $variableExperiences = [
  121.                 'ProviderId' => $provider,
  122.             ];
  123.             $responseExperiences $webService->callWebServiceAmadeus('SERVICIO_MPT''SvcAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplateExperiences$variableExperiencestrue);
  124.             //$responseExperiences = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\serviciosQ\experience\SvcAvailRS.xml')));
  125.             if (empty($responseExperiences) || isset($responseExperiences['error'])) {
  126.                 $responseExperiences['error'] ??= 'No se encontro información para la búsqueda seleccionada.';
  127.                 if (false === strpos($responseExperiences['error'], 'No se encontro información para la busqueda seleccionada')) {
  128.                     return $this->redirect($errorHandler->errorRedirectNoEmail($requestUrl'Error disponibilidad buscador'$responseExperiences['error']));
  129.                 }
  130.                 return new Response($responseExperiences['error']);
  131.             }
  132.             $info['transactionId'] = (string) $responseExperiences->Message->OTAServiceAvailRS['TransactionIdentifier'];
  133.             $ExperiencesInfo null;
  134.             foreach ($responseExperiences->Message->OTAServiceAvailRS->Service as $experience) {
  135.                 $experience->TPA_Extensions->ProductInfo->Description htmlspecialchars_decode($experience->TPA_Extensions->ProductInfo->Description);
  136.                 $selectDate strtotime($info['Start']);
  137.                 $endDate = isset($experience) ? strtotime($experience->TPA_Extensions->ProductInfo->VigenciaFinal) : null;
  138.                 $startDate = isset($experience) ? strtotime($experience->TPA_Extensions->ProductInfo->VigenciaInicial) : null;
  139.                 if (($selectDate $endDate /* && $selectDate > $startDate */)) {
  140.                     $ExperiencesInfo[] = $experience;
  141.                 }
  142.             }
  143.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/AjaxAvailability.html.twig');
  144.             return $this->render($urlAvailability, [
  145.                         'ExperiencesInfo' => $ExperiencesInfo,
  146.                         'info' => $info,
  147.             ]);
  148.         } else {
  149.             if ($configExperienceAgency) {
  150.                 $providers[] = $configExperienceAgency[0]->getProvider()->getProvideridentifier();
  151.             } else {
  152.                 $domain $request->getHost();
  153.                 $exceptionLog->log('Error Fatal''No se encontró la agencia segun el dominio: '.$domainnullfalse);
  154.                 return new Response('No se encontró agencias para consultar disponibilidad.');
  155.             }
  156.             $provider implode(';'$providers);
  157.             $availabilityArray = [
  158.                 'ProviderId' => $provider,
  159.                 'destination' => (strlen($destination1) > 3) ? null $destination1,
  160.                 'searchInfoExperience' => (strlen($destination1) > 3) ? $destination1 null,
  161.                 'destinationLabel' => $destinationLabel ?? null,
  162.             ];
  163.             if (null != $date1) {
  164.                 $availabilityArray['date1'] = $date1;
  165.             }
  166.             if (null != $date2) {
  167.                 $availabilityArray['date2'] = $date2;
  168.             }
  169.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/availability.html.twig');
  170.             $safeUrl 'https://'.$agency->getDomainsecure();
  171.             $cookieLastSearch $experienceCookie->searchExperienceCookie(['experience' => base64_encode(json_encode($availabilityArray))]);
  172.             $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  173.             if (null != $pointRedemption) {
  174.                 $points 0;
  175.                 if ($fullRequest->request->has('pointRedemptionValue')) {
  176.                     $points $fullRequest->request->get('pointRedemptionValue');
  177.                     $session->set('point_redemption_value'$points);
  178.                 } elseif ($fullRequest->query->has('pointRedeem')) {
  179.                     $points $fullRequest->query->get('pointRedeem');
  180.                     $session->set('point_redemption_value'$points);
  181.                 } elseif ($session->has('point_redemption_value')) {
  182.                     $points $session->get('point_redemption_value');
  183.                 }
  184.                 $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  185.             }
  186.             $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
  187.             $urlDescription['url'] = null != $seoUrl '/'.$seoUrl[0]->getUrl() : $requestUrl;
  188.             $response $this->render($urlAvailability, [
  189.                 'ajaxUrl' => $requestUrl,
  190.                 'inlineEngine' => true,
  191.                 'safeUrl' => $safeUrl,
  192.                 'availabilityArray' => $availabilityArray,
  193.                 'cookieLastSearch' => $cookieLastSearch,
  194.                 'pointRedemption' => $pointRedemption,
  195.                 'urlDescription' => $urlDescription,
  196.             ]);
  197.             $response->headers->setCookie(new Cookie('_availability_array[experience]'base64_encode(json_encode($availabilityArray)), (time() + 3600 24 7), '/'));
  198.             return $response;
  199.         }
  200.     }
  201.     public function ajaxDetailAction(AviaturWebService $webService$id$startDate null$transactionId false)
  202.     {
  203.         $em $this->managerRegistry;
  204.         $session $this->session;
  205.         $agency $this->agency;
  206.         $ProviderId $em->getRepository(\Aviatur\ExperienceBundle\Entity\ConfigExperienceAgency::class)->findProviderForExperiencesWithAgency($agency)[0]->getProvider()->getProviderIdentifier();
  207.         $variableExperiences = ['ProviderId' => $ProviderId];
  208.         if (!$transactionId) {
  209.             $transactionId $webService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  210.         }
  211.         $generalModel = new GeneralModel();
  212.         if (!$startDate) {
  213.             $startDate date('Y-m-d');
  214.         }
  215.         $info = ['ID' => $id'Start' => $startDate'End' => ''];
  216.         $xmlTemplateExperiences $generalModel->getXmlExperiencesDetail($info);
  217.         $responseExperiences $webService->callWebServiceAmadeus('SERVICIO_MPT''SvcDetail''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplateExperiences$variableExperiencesfalse$transactionIdfalse);
  218.         if (empty($responseExperiences) || isset($responseExperiences['error'])) {
  219.             $responseExperiences['error'] ??= 'Ha sido redirigido a la disponibilidad para que pueda seguir explorando opciones.';
  220.             return $this->json(['error' => true'message' => $responseExperiences['error']]);
  221.         }
  222.         // $this->get("aviatur_log_save")->logSave(var_dump($responseExperiences), 'decksterr', 'xperience');
  223.         // die;
  224.         $infodetail = [
  225.             'UnitCostName' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->UnitCostName,
  226.             'CurrencyCode' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->CurrencyCode,
  227.             'CurrencyName' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->CurrencyName,
  228.             'ValorTotal' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Valor,
  229.             'Description' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Description,
  230.             'Email' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Email,
  231.         ];
  232.         $images = [];
  233.         foreach ($responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Multimedia->ImageItems->ImageItem as $image) {
  234.             $images[] = ['URL' => (string) $image->Url'Name' => (string) $image->Name];
  235.         }
  236.         $dates = [];
  237.         $datesArray = [];
  238.         $daysBeforeReservation = (int) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->DiasAntesReserva 1;
  239.         if ($startDate date('Y-m-d'strtotime('+ '.$daysBeforeReservation.' days'))) {
  240.             $startDate date('Y-m-d'strtotime('+ '.$daysBeforeReservation.' days'));
  241.         }
  242.         foreach ($responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Salidas->Salida as $date) {
  243.             if ('' != (string) $date['DepartureArrivalDate']) {
  244.                 if ((string) $date['DepartureArrivalDate'] >= $startDate) {
  245.                     $datesArray[] = (string) $date['DepartureArrivalDate'];
  246.                 }
  247.             } else {
  248.                 if ((string) $date['BeginDate'] > $startDate) {
  249.                     $begin = new \DateTime((string) $date['BeginDate']);
  250.                 } else {
  251.                     $begin = new \DateTime($startDate);
  252.                 }
  253.                 $end = new \DateTime((string) $date['EndDate']);
  254.                 $interval = \DateInterval::createFromDateString('1 day');
  255.                 $period = new \DatePeriod($begin$interval$end);
  256.                 foreach ($period as $dt) {
  257.                     $datesArray[] = $dt->format('Y-m-d');
  258.                 }
  259.                 if (empty($dates)) {
  260.                     $datesArray[0] = $period->start->format('Y-m-d');
  261.                 }
  262.             }
  263.         }
  264.         asort($datesArray);
  265.         foreach ($datesArray as $key => $val) {
  266.             $dates[] = $val;
  267.         }
  268.         $cautions = [];
  269.         foreach ($responseExperiences->Message->OTAServiceAvailRS->Service->Cautions->Caution as $caution) {
  270.             $cautions[] = ['Type' => (string) $caution['ID'], 'Info' => (string) $caution];
  271.         }
  272.         $infoFares = ['ID' => $id'Start' => $dates[0], 'End' => $dates[4] ?? $dates[sizeof($dates) - 1] ?? $dates[0]];
  273.         $xmlTemplateExperiencesFares $generalModel->getXmlExperiencesFares($infoFares);
  274.         $responseExperiencesFares $webService->callWebServiceAmadeus('SERVICIO_MPT''SvcFares''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplateExperiencesFares$variableExperiencesfalse$transactionIdfalse);
  275.         $fares = [];
  276.         foreach ($responseExperiencesFares->Message->OTAServiceAvailRS->Service->Items->Item->Provider->PropertyProfiles->PropertyProfile as $fare) {
  277.             if ($startDate >= (string) $fare['EffectiveDate'] && $startDate <= (string) $fare['ExpireDate']) {
  278.                 $fare['PropertyCategory'] ??= 'General';
  279.                 $fares[(string) $fare['PropertyCategory']][(string) $fare['PropertyType']] = [
  280.                     'Count' => (string) $fare->Prices->Price['Count'],
  281.                     'CurrencyCode' => (string) $fare->Prices->Price['CurrencyCode'],
  282.                     'PriceBasis' => (string) $fare->Prices->Price['PriceBasis'],
  283.                     'DecimalPlaces' => (string) $fare->Prices->Price['DecimalPlaces'],
  284.                     'PriceQualifier' => (string) $fare->Prices->Price['PriceQualifier'],
  285.                     'Amount' => (string) $fare->Prices->Price['Amount'],
  286.                     'AmountSpecified' => (string) $fare->Prices->Price['AmountSpecified'],
  287.                     'RangeMaximum' => (string) $fare->Prices->Price['RangeMaximum'],
  288.                     'RangeMinimum' => (string) $fare->Prices->Price['RangeMinimum'],
  289.                     'Description' => (string) $fare['Description'],
  290.                 ];
  291.                 $fares[(string) $fare['PropertyCategory']]['StartDate'] = (string) $fare['EffectiveDate'];
  292.                 $fares[(string) $fare['PropertyCategory']]['EndDate'] = (string) $fare['ExpireDate'];
  293.             }
  294.         }
  295.         $dateFares = [];
  296.         for ($i 0$i <= (isset($dates[4]) ? sizeof($dates) - 1); ++$i) {
  297.             foreach ($fares as $fareKey => $fare) {
  298.                 if (/* $fare["StartDate"] <= $dates[$i] && */$fare['EndDate'] >= $dates[$i]) {
  299.                     $dateFares[$dates[$i]][$fareKey] = $fare;
  300.                     unset($dateFares[$dates[$i]][$fareKey]['StartDate']);
  301.                     unset($dateFares[$dates[$i]][$fareKey]['EndDate']);
  302.                 }
  303.             }
  304.         }
  305.         $attributes = [];
  306.         $sessionAttributes = ['operatorId''whitemark''special_campaing''typeCoin''typeCountry''CoinValue''financialValue''trmValue''RateChange''RateDiff'];
  307.         foreach ($sessionAttributes as $attribute) {
  308.             if ($session->has($attribute)) {
  309.                 $attributes['session'][$attribute] = $session->get($attribute);
  310.             }
  311.         }
  312.         //agrupar por propertyCategory como inicial
  313.         return $this->json(['infodetail' => base64_encode(json_encode($infodetail)), 'images' => base64_encode(json_encode($images)), 'dates' => $dates'cautions' => base64_encode(json_encode($cautions)), 'fares' => $fares'dateFares' => $dateFares'attributes' => $attributes]);
  314.     }
  315.     public function detailAction(Request $requestTwigFolder $twigFolderLoginManagerInterface $loginManagerParameterBagInterface $parameterBagAviaturErrorHandler $errorHandlerAviaturWebService $webServiceTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentService$id null$date null$adults null$children null)
  316.     {
  317.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  318.         $exchangeValues null;
  319.         $postData null;
  320.         $responseExperiences = [];
  321.         $fullRequest $request;
  322.         $request $fullRequest->request;
  323.         $em $this->managerRegistry;
  324.         $session $this->session;
  325.         $agency $this->agency;
  326.         $agencyFolder $twigFolder->twigFlux();
  327.         $passengerTypes = [];
  328.         $productInfo = new PackageModel();
  329.         $generalModel = new GeneralModel();
  330.         $phoneService = new PhoneNumberService($em);
  331.         $phonePrefixes $phoneService->getActivePrefixes();
  332.         if (true === $request->has('whitemarkDataInfo')) {
  333.             $session->set('whitemarkDataInfo'json_decode($request->get('whitemarkDataInfo'), true));
  334.         }
  335.         if (true === $request->has('userLogin') && '' != $request->get('userLogin') && null != $request->get('userLogin')) {
  336.             $user $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($request->get('userLogin'));
  337.             $this->authenticateUser($user$loginManager);
  338.         }
  339.         if ($request->has('transactionID')) {
  340.             $transactionId $request->get('transactionID');
  341.             $session->set($transactionIdSessionName$transactionId);
  342.             $session->set($transactionId.'[experience][availability_url]'$fullRequest->server->get('HTTP_REFERER'));
  343.         } elseif ($session->has($transactionIdSessionName)) {
  344.             $transactionId $session->get($transactionIdSessionName);
  345.             if ('POST' == $fullRequest->getMethod()) {
  346.                 $session->set('redirectedRetry'false);
  347.             } else {
  348.                 $loadInfo json_decode($this->ajaxDetailAction($webService$id$date$transactionId)->getContent(), true);
  349.                 if(isset($loadInfo["error"])){
  350.                     return $this->redirect($errorHandler->errorRedirectNoEmail($fullRequest->server->get('HTTP_REFERER'), 'No encontramos información del detalle de tu búsqueda.'$responseExperiences['error']));
  351.                 }
  352.                 $images json_decode(base64_decode($loadInfo['images']));
  353.                 $cautions json_decode(base64_decode($loadInfo['cautions']));
  354.                 $infodetail json_decode(base64_decode($loadInfo['infodetail']));
  355.             }
  356.         } else {
  357.             if (empty($id) || empty($date)) {
  358.                 return new Response('error');
  359.             } else {
  360.                 $transactionId $webService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  361.                 $session->set($transactionIdSessionName$transactionId);
  362.                 $loadInfo json_decode($this->ajaxDetailAction($webService$id$date$transactionId)->getContent(), true);
  363.                 if(isset($loadInfo["error"])){
  364.                     return $this->redirect($errorHandler->errorRedirectNoEmail($fullRequest->server->get('HTTP_REFERER'), 'No encontramos información del detalle de tu búsqueda.'$responseExperiences['error']));
  365.                 }
  366.                 $images json_decode(base64_decode($loadInfo['images']));
  367.                 $cautions json_decode(base64_decode($loadInfo['cautions']));
  368.                 $infodetail json_decode(base64_decode($loadInfo['infodetail']));
  369.             }
  370.         }
  371.         if ('' != $request->get('ProviderId')) {
  372.             $session->set($transactionId.'[experience][ProviderId]'$request->get('ProviderId'));
  373.             $ProviderId $request->get('ProviderId');
  374.         } else {
  375.             if (isset($transactionId) && $session->has($transactionId.'[experience][ProviderId]')) {
  376.                 $ProviderId $session->get($transactionId.'[experience][ProviderId]');
  377.             } else {
  378.                 $ProviderId $em->getRepository(\Aviatur\ExperienceBundle\Entity\ConfigExperienceAgency::class)->findProviderForExperiencesWithAgency($agency)[0]->getProvider()->getProviderIdentifier();
  379.             }
  380.         }
  381.         $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($ProviderId);
  382.         $paymentType $provider->getPaymentType()->getTwig();
  383.         $repositoryDocumentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  384.         $queryDocumentType $repositoryDocumentType
  385.                 ->createQueryBuilder('p')
  386.                 ->where('p.paymentcode != :paymentcode')
  387.                 ->setParameter('paymentcode''')
  388.                 ->getQuery();
  389.         $documentPaymentType $queryDocumentType->getResult();
  390.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  391.         $paymentOptions = [];
  392.         foreach ($paymentMethodAgency as $payMethod) {
  393.             $paymentCode $payMethod->getPaymentMethod()->getCode();
  394.             if (!in_array($paymentCode$paymentOptions) && 'davivienda' != $paymentCode) {
  395.                 $paymentOptions[] = $paymentCode;
  396.             }
  397.         }
  398.         $banks = [];
  399.         if (in_array('pse'$paymentOptions)) {
  400.             $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  401.         }
  402.         $cybersource = [];
  403.         if (in_array('cybersource'$paymentOptions)) {
  404.             $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  405.             $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  406.         }
  407.         foreach ($paymentOptions as $key => $paymentOption) {
  408.             if ('cybersource' == $paymentOption) {
  409.                 unset($paymentOptions[$key]); // strip from other renderizable payment methods
  410.             }
  411.         }
  412.         if ($session->has($transactionId.'[experience][retry]')) {
  413.             $twigVariables json_decode($session->get($transactionId.'[experience][detailVariables]'), true);
  414.             $postData json_decode($session->get($transactionId.'[experience][detail_data]'));
  415.             $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_hotels');
  416.             $twig_readonly true;
  417.             $twigVariables['twig_readonly'] = $twig_readonly;
  418.             $twigVariables['passengers'] = $postData->PI;
  419.             $twigVariables['billingData'] = $postData->BD;
  420.             $twigVariables['contactData'] = $postData->CD;
  421.             if (isset($postData->OD)) {
  422.                 $twigVariables['observations'] = $postData->OD->notes;
  423.             }
  424.             $twigVariables['cards'] = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]);
  425.             $twigVariables['inactiveCards'] = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]);
  426.             $twigVariables['banks'] = $banks;
  427.             $twigVariables['cybersource'] = $cybersource;
  428.             $twigVariables['paymentOptions'] = $paymentOptions;
  429.             $twigVariables['payment_doc_type'] = $documentPaymentType;
  430.             $twigVariables['cybersource'] = $cybersource;
  431.             $twigVariables['doc_type'] = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  432.             $twigVariables['gender'] = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  433.             $twigVariables['gconditionsender'] = $conditions;
  434.             $twigVariables['payment_type_form_name'] = $paymentType;
  435.         } else {
  436.             $twig_readonly false;
  437.             $passengerTypes = [
  438.                 => [
  439.                     'ADT' => ('' != $request->get('adults')) ? (int) $request->get('adults') : ($adults ?? 1),
  440.                     'CHD' => ('' != $request->get('children')) ? (int) $request->get('children') : ($children ?? 0),
  441.                     'INF' => 0,
  442.                 ],
  443.             ];
  444.             $info = [
  445.                 'ID' => ('' == $request->get('packageCode')) ? $id $request->get('packageCode'),
  446.                 'Start' => ('' == $request->get('date1')) ? $date $request->get('date1'),
  447.                 'End' => ('' == $request->get('date2')) ? (('' == $request->get('date1')) ? $date $request->get('date1')) : $request->get('date2'),
  448.                 'date1' => ('' == $request->get('date1')) ? $date $request->get('date1'),
  449.                 'date2' => ('' == $request->get('date2')) ? (('' == $request->get('date1')) ? $date $request->get('date1')) : $request->get('date2'),
  450.                 'Code' => $request->get('destination'),
  451.                 'passangerTypes' => $passengerTypes,
  452.             ];
  453.             $variableExperiences = ['ProviderId' => $ProviderId];
  454.             $session->set($transactionId.'[experiences][args]'json_encode($info));
  455.             $validateChild 0;
  456.             $count 0;
  457.             $validateRph 0;
  458.             $dias = (strtotime($info['Start']) - strtotime(date('Y-m-d'))) / 86400;
  459.             $xmlTemplateExperiencesFares $generalModel->getXmlExperiencesFares($info);
  460.             $itemcount = ('' != $request->get('itemcount')) ? explode(','$request->get('itemcount')) : '';
  461.             $parameters json_decode($session->get($session->get('domain').'[parameters]'));
  462.             $webService->setUrls($parameters);
  463.             $responseExperiencesFares $webService->callWebServiceAmadeus('SERVICIO_MPT''SvcFares''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplateExperiencesFares$variableExperiencesfalse$transactionIdfalse);
  464.             /* Se debe definir la variable de la información sobre experiencias, por que se parte del supuesto que existe, y se está enviando algo que puede fallar por inexistente */
  465.             $infoExperience = [];
  466.             //$responseExperiencesFares = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\serviciosQ\experience\SvcFaresRS.xml')));
  467.             if (!isset($responseExperiencesFares['error'])) {
  468.                 $infodetail = !isset($infodetail) ? json_decode(base64_decode($request->get('infodetail'))) : $infodetail;
  469.                 $cautions = !isset($cautions) ? json_decode(base64_decode($request->get('cautions'))) : $cautions;
  470.                 $images = !isset($images) ? json_decode(base64_decode($request->get('images'))) : $images;
  471.                 $session->set($transactionId.'[experience][detailInfo]'$cautions);
  472.                 $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  473.                 $typeGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  474.                 $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_hotels');
  475.                 $totalPassengers $passengerTypes[1]['ADT'] + $passengerTypes[1]['CHD'];
  476.                 $profilesServices = [];
  477.                 if ($responseExperiencesFares) {
  478.                     foreach ($responseExperiencesFares->Message->OTAServiceAvailRS->Service as $serviceFare) {
  479.                         //$DiasAntesReserva = (int) $serviceDetail->TPA_Extensions->ProductInfo->DiasAntesReserva;
  480.                         //    if ($DiasAntesReserva >= $dias) {
  481.                         //        return $this->redirect($this->get("aviatur_error_handler")->errorRedirect(($fullRequest->server->get('HTTP_REFERER') != '') ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'Este producto debe reservarse con minimo ' . $DiasAntesReserva . ' días antes de la entrada.'));
  482.                         //    }
  483.                         $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Description $infodetail->Description;
  484.                         $totalAmount[0] = (int) $infodetail->ValorTotal;
  485.                         $baseAmount[0] = (int) 0;
  486.                         $tax[0] = (int) 0;
  487.                         $percentage[0] = (int) 0;
  488.                         $legend[0] = (string) $serviceFare->TPA_Extensions->ProductInfo->Description;
  489.                         $PassengerExperienceDetail[0]['ImageItem'] = $images;
  490.                         $PassengerExperienceDetail[0]['ID'] = (int) $serviceFare['ID'];
  491.                         $PassengerExperienceDetail[0]['ProductName'] = (string) $serviceFare->TPA_Extensions->ProductInfo->ProductName;
  492.                         $PassengerExperienceDetail[0]['UnitCostName'] = (string) $infodetail->UnitCostName;
  493.                         $PassengerExperienceDetail[0]['CurrencyCode'] = (string) $infodetail->CurrencyCode;
  494.                         $PassengerExperienceDetail[0]['CurrencyName'] = (string) $infodetail->CurrencyName;
  495.                         $PassengerExperienceDetail[0]['FormaVenta'] = (string) $serviceFare->TPA_Extensions->ProductInfo->FormaVenta;
  496.                         $PassengerExperienceDetail[0]['Description'] = (string) $serviceFare->TPA_Extensions->ProductInfo->Description;
  497.                         $PassengerExperienceDetail[0]['ClaseServicio'] = (string) $serviceFare->TPA_Extensions->ProductInfo->ClaseServicio;
  498.                         $PassengerExperienceDetail[0]['ValorTotal'] = (int) $infodetail->ValorTotal;
  499.                         $PassengerExperienceDetail[0]['Email'] = (string) $infodetail->Email;
  500.                         $PassengerExperienceDetail[0]['cautions'] = $cautions;
  501.                         if (isset($serviceFare->Items->Item->Provider->PropertyProfiles)) {
  502.                             $PassengerExperienceDetail[0]['BrandCode'] = (string) $serviceFare->Items->Item->Provider->Identity['BrandCode'];
  503.                             $PassengerExperienceDetail[0]['HotelCode'] = (string) $serviceFare->Items->Item->Provider->Identity['HotelCode'];
  504.                             $PassengerExperienceDetail[0]['HotelName'] = (string) $serviceFare->Items->Item->Provider->Identity['HotelName'];
  505.                             $PassengerExperienceDetail[0]['ResortCode'] = (string) $serviceFare->Items->Item->Provider['ResortCode'];
  506.                             $PassengerExperienceDetail[0]['ResortName'] = (string) $serviceFare->Items->Item->Provider['ResortName'];
  507.                             $PassengerExperienceDetail[0]['DestinationCode'] = (string) $serviceFare->Items->Item->Provider['DestinationCode'];
  508.                             $PassengerExperienceDetail[0]['DestinationName'] = (string) $serviceFare->Items->Item->Provider['DestinationName'];
  509.                             foreach ($serviceFare->Items->Item->Provider->PropertyProfiles->PropertyProfile as $PropertyProfiles) {
  510.                                 $rph = (int) $PropertyProfiles['RPH'];
  511.                                 $rphInfo[] = $rph;
  512.                                 $PropertyTypeCode = (int) $PropertyProfiles['PropertyTypeCode'];
  513.                                 $Quantity = (string) $PropertyProfiles['CotQuantity'];
  514.                                 $PropertyViewCode = (string) $PropertyProfiles['PropertyViewCode'];
  515.                                 $PassengerExperienceDetail[0]['PropertyViewCode'] = $PropertyViewCode;
  516.                                 if ('True' == (string) $PropertyProfiles['FreeChildFlag']) {
  517.                                     ++$validateChild;
  518.                                 }
  519.                                 if ('' != $request->get('itemcount')) {
  520.                                     if (in_array($PropertyProfiles['PropertyTypeCode'], $itemcount)) {
  521.                                         foreach ($PropertyProfiles->Prices as $prices) {
  522.                                             if ((string) $PropertyProfiles['EffectiveDate'] <= $date && (string) $PropertyProfiles['ExpireDate'] >= $date) {
  523.                                                 if (isset($passengerTypes[1][(string) $prices->Price['PriceQualifier']])) {
  524.                                                     $quantity $passengerTypes[1][(string) $prices->Price['PriceQualifier']];
  525.                                                 } else {
  526.                                                     $quantity $totalPassengers;
  527.                                                 }
  528.                                                 if ((int) $prices->Price['RangeMaximum'] >= $quantity && (int) $prices->Price['RangeMinimum'] <= $quantity) {
  529.                                                     if ($totalPassengers $rph && 'true' == (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta) {
  530.                                                         ++$validateRph;
  531.                                                         continue;
  532.                                                     }
  533.                                                     if (false === strpos((string) $prices->Price['WeekDay'], date('N'strtotime($info['date1'])))) {
  534.                                                         $dias_ES = ['Lunes''Martes''Miércoles''Jueves''Viernes''Sábado''Domingo'];
  535.                                                         $dias_EN = ['Monday''Tuesday''Wednesday''Thursday''Friday''Saturday''Sunday'];
  536.                                                         $nombredia str_replace($dias_EN$dias_ESdate('l'strtotime($info['date1'])));
  537.                                                         return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar''Los dias '.$nombredia.' no hay servicio'));
  538.                                                     }
  539.                                                     $profilesServices[] = $PropertyProfiles;
  540.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Count'.$PropertyTypeCode] = (int) $prices->Price['Count'];
  541.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Amount'.$PropertyTypeCode] = (int) $prices->Price['Amount'];
  542.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Quantity'.$PropertyTypeCode] = $Quantity;
  543.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['CurrencyCode'.$PropertyTypeCode] = (string) $prices->Price['CurrencyCode'];
  544.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['RPH'.$PropertyTypeCode] = $rph;
  545.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Age'.$PropertyTypeCode] = (int) $prices->Price['RangeMinimum'];
  546.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['AgeEnd'.$PropertyTypeCode] = (int) $prices->Price['RangeMaximum'];
  547.                                                     if (isset($info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']]) && $info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']] > 0) {
  548.                                                         $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceQualifier'];
  549.                                                     } elseif (!isset($prices->Price['PriceQualifier']) && isset($prices->Price['PriceBasis'])) {
  550.                                                         $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceBasis'];
  551.                                                     } else {
  552.                                                         continue;
  553.                                                     }
  554.                                                 }
  555.                                             }
  556.                                         }
  557.                                     }
  558.                                 } else {
  559.                                     foreach ($PropertyProfiles->Prices as $prices) {
  560.                                         if ((string) $PropertyProfiles['EffectiveDate'] <= $date && (string) $PropertyProfiles['ExpireDate'] >= $date) {
  561.                                             if (isset($passengerTypes[1][(string) $prices->Price['PriceQualifier']])) {
  562.                                                 $quantity $passengerTypes[1][(string) $prices->Price['PriceQualifier']];
  563.                                             } else {
  564.                                                 $quantity $totalPassengers;
  565.                                             }
  566.                                             if ((int) $prices->Price['RangeMaximum'] >= $quantity && (int) $prices->Price['RangeMinimum'] <= $quantity) {
  567.                                                 if ($totalPassengers $rph && 'true' == (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta) {
  568.                                                     ++$validateRph;
  569.                                                     continue;
  570.                                                 }
  571.                                                 if (false === strpos((string) $prices->Price['WeekDay'], date('N'strtotime($info['date1'])))) {
  572.                                                     $dias_ES = ['Lunes''Martes''Miércoles''Jueves''Viernes''Sábado''Domingo'];
  573.                                                     $dias_EN = ['Monday''Tuesday''Wednesday''Thursday''Friday''Saturday''Sunday'];
  574.                                                     $nombredia str_replace($dias_EN$dias_ESdate('l'strtotime($info['date1'])));
  575.                                                     return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar''Los dias '.$nombredia.' no hay servicio'));
  576.                                                 }
  577.                                                 $profilesServices[] = $PropertyProfiles;
  578.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Count'.$PropertyTypeCode] = (int) $prices->Price['Count'];
  579.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Amount'.$PropertyTypeCode] = (int) $prices->Price['Amount'];
  580.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Quantity'.$PropertyTypeCode] = $Quantity;
  581.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['CurrencyCode'.$PropertyTypeCode] = (string) $prices->Price['CurrencyCode'];
  582.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['RPH'.$PropertyTypeCode] = $rph;
  583.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Age'.$PropertyTypeCode] = (int) $prices->Price['RangeMinimum'];
  584.                                                 $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['AgeEnd'.$PropertyTypeCode] = (int) $prices->Price['RangeMaximum'];
  585.                                                 if (isset($info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']]) && $info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']] > 0) {
  586.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceQualifier'];
  587.                                                 } elseif (!isset($prices->Price['PriceQualifier']) && isset($prices->Price['PriceBasis'])) {
  588.                                                     $PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceBasis'];
  589.                                                 } else {
  590.                                                     continue;
  591.                                                 }
  592.                                             }
  593.                                         }
  594.                                     }
  595.                                 }
  596.                                 ++$count;
  597.                             }
  598.                             if ($validateRph >= $count) {
  599.                                 return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar''Este producto posee '.max($rphInfo).' cupo(s) disponibles'));
  600.                             }
  601.                             $infoExperience[0] = $this->generateReturn([$totalAmount[0], $baseAmount[0], $tax[0], $percentage[0], $totalAmount[0]], $legend[0], ['ExperienceDetail' => $PassengerExperienceDetail[0]]);
  602.                             /* Aquí se debe emplear una función que permite devolver los cautions sin estilos, sin heights, sin widths que perjudiquen la visual por móvil, especialmente */
  603.                             $this->removeStylesFromCautions($infoExperience[0]);
  604.                             $infoExperience[0]['values'] = $infoExperience[0];
  605.                         } else {
  606.                             return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar''Hubo un problema al realizar el cálculo de tu producto'));
  607.                         }
  608.                     }
  609.                 }
  610.                 if (empty($profilesServices)) {
  611.                     return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar''No hay tarifas disponibles para la fecha seleccionada o para la cantidad de pasajeros'));
  612.                 }
  613.                 //elseif($validateChild == 0 && $passengerTypes[1]['CHD'] > 0){
  614.                 //return $this->redirect($this->get("aviatur_error_handler")->errorRedirect(($fullRequest->server->get('HTTP_REFERER') != '') ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'No se permiten niños para este producto'));
  615.                 //}
  616.                 $passengerTypes[1]['countDate'] = is_countable($date) ? count($date) : 0;
  617.                 $rateExperiences $this->rateExperience($profilesServices$passengerTypes[1]);
  618.                 if (isset($rateExperiences['error'])) {
  619.                     return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar'$rateExperiences['error']));
  620.                 }
  621.                 $rpm 1;
  622.                 if (isset($rateExperiences['Amount']) && 'COP' != mb_strtoupper((string) $infodetail->CurrencyCode) && 'true' == (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta) {
  623.                     $hoy date('Y-m-d');
  624.                     $xmlTemplate $productInfo->getTasaCambio($hoy);
  625.                     $financial $webService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  626.                     $validate false;
  627.                     foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
  628.                         if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && mb_strtoupper((string) $infodetail->CurrencyCode) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
  629.                             $financialValue = (int) $tasa->VALOR;
  630.                             $exchangeValues = [
  631.                                 'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
  632.                                 'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
  633.                             ];
  634.                             $validate true;
  635.                         }
  636.                     }
  637.                     if (!$validate) {
  638.                         $hoy date('Y-m-d'strtotime('-1 day'strtotime(date('Y-m-d'))));
  639.                         $xmlTemplate $productInfo->getTasaCambio($hoy);
  640.                         $financial $webService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  641.                         foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
  642.                             if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && mb_strtoupper((string) $infodetail->CurrencyCode) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
  643.                                 $financialValue = (int) $tasa->VALOR;
  644.                                 $exchangeValues = [
  645.                                     'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
  646.                                     'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
  647.                                 ];
  648.                             }
  649.                         }
  650.                     }
  651.                     if (!isset($financialValue) || !is_numeric($financialValue)) {
  652.                         return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_experience_search'), 'Error en la conversión de moneda'''));
  653.                     } else {
  654.                         $rpm $financialValue;
  655.                         $AmountTotal min(array_filter($rateExperiences['Amount'])) * $financialValue;
  656.                         $session->set('[mpt][finantial_rate]'$financialValue);
  657.                         $session->set($transactionId.'[mpt][exchangeValues]'json_encode($exchangeValues));
  658.                     }
  659.                 } else {
  660.                     $AmountTotal min(array_filter($rateExperiences['Amount']));
  661.                 }
  662.                 $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  663.                 if (null != $pointRedemption) {
  664.                     $points 0;
  665.                     if ($fullRequest->request->has('pointRedemptionValue')) {
  666.                         $points $fullRequest->request->get('pointRedemptionValue');
  667.                         $session->set('point_redemption_value'$points);
  668.                     } elseif ($fullRequest->query->has('pointRedeem')) {
  669.                         $points $fullRequest->query->get('pointRedeem');
  670.                         $session->set('point_redemption_value'$points);
  671.                     } elseif ($session->has('point_redemption_value')) {
  672.                         $points $session->get('point_redemption_value');
  673.                     }
  674.                     $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  675.                 }
  676.                 if (isset($postData->cusPOptSelected)) {
  677.                     //$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData->id);
  678.                     //$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData->id);
  679.                     $customerLogin $tokenStorage->getToken()->getUser();
  680.                     if (is_object($customerLogin)) {
  681.                         $paymentsSaved $methodPaymentService->getMethodsByCustomer($customerLoginfalse);
  682.                     }
  683.                 }
  684.                 $twigVariables = [
  685.                    'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
  686.                     'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
  687.                     'banks' => $banks,
  688.                     'cybersource' => $cybersource,
  689.                     'paymentOptions' => $paymentOptions,
  690.                     'payment_doc_type' => $documentPaymentType,
  691.                     'twig_readonly' => $twig_readonly,
  692.                     'doc_type' => $typeDocument,
  693.                     'gender' => $typeGender,
  694.                     'services' => $passengerTypes,
  695.                     'profilesServices' => $profilesServices,
  696.                     'rateExperiences' => $rateExperiences['optionsList'],
  697.                     'transactionId' => base64_encode($transactionId),
  698.                     'CriteoTags' => null,
  699.                     'conditions' => $conditions,
  700.                     'serviceResponse' => $responseExperiencesFares->Message->OTAServiceAvailRS->Service,
  701.                     'payment_type_form_name' => $paymentType,
  702.                     'referer' => ('' != $request->get('referer')) ? $request->get('referer') : $fullRequest->server->get('REQUEST_URI'),
  703.                     'amount' => min(array_filter($rateExperiences['Amount'])),
  704.                     'AmountTotal' => $AmountTotal,
  705.                     'currency' => (string) $infodetail->CurrencyCode,
  706.                     'info' => $info,
  707.                     'rpm' => $rpm,
  708.                     'infoExperience' => $infoExperience,
  709.                     'FormaVenta' => (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta,
  710.                     'pointRedemption' => $pointRedemption,
  711.                     'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  712.                     'Email' => $infodetail->Email,
  713.                     'phone_prefixes' => $phonePrefixes,
  714.                     'default_country' => 'CO',
  715.                 ];
  716.                 $twigVariables['pse'] = true;
  717.                 $twigVariables['safety'] = true;
  718.                 $iinRecordsArray $webService->getIINRanges($em);
  719.                 $twigVariables["ccranges"] = $iinRecordsArray["ccranges"];
  720.                 $twigVariables["ccfranchises"] = $iinRecordsArray["ccfranchises"];
  721.                 $session->set($transactionId.'[experience][detailVariables]'json_encode($twigVariables));
  722.                 $agencyFolder $twigFolder->twigFlux();
  723.             } else {
  724.                 $message $responseExperiences['error'] ?? 'Ha ocurrido un error inesperado';
  725.                 return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_general_homepage'), 'Página no accesible'$message));
  726.             }
  727.         }
  728.         if (empty($twigVariables['rateExperiences'])) {
  729.             $message 'Por favor cambia los filtros de busqueda para este producto';
  730.             return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_general_homepage'), 'Error en las tarifas'$message));
  731.         }
  732.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/detail.html.twig'), $twigVariables);
  733.     }
  734.     public function prePaymentStep1Action(Request $requestParameterBagInterface $parameterBagTwigFolder $twigFolderAviaturErrorHandler $errorHandlerAviaturEncoder $aviaturEncoderTokenizerService $tokenizerServiceAviaturWebService $webServiceExceptionLog $exceptionLogSearchExperienceCookie $experienceCookieTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentService)
  735.     {
  736.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  737.         if ($request->isXmlHttpRequest()) {
  738.             $session $this->session;
  739.             $transactionId $session->get($transactionIdSessionName);
  740.             $billingData $request->get('BD');
  741.             $em $this->managerRegistry;
  742.             $postData $request->request->all();
  743.             $publicKey $aviaturEncoder->aviaturRandomKey();
  744.             /* if (isset($postData['PD']['card_num'])) {
  745.                 $postDataInfo = $postData;
  746.                 $postDataInfo['PD']['card_num'] = $this->get('aviatur_tokenizer')->getToken($postData['PD']['card_num']);
  747.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  748.             } */
  749.             if (isset($postData['PD']['card_num'])) {
  750.                 $postDataInfo $postData;
  751.                 if (isset($postDataInfo['PD']['cusPOptSelected'])) {
  752.                     $customerLogin $tokenStorage->getToken()->getUser();
  753.                     $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLogintrue);
  754.                     $cardToken $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
  755.                     $postDataInfo['PD']['card_num'] = $cardToken;
  756.                     $postData['PD']['card_num'] = $cardToken;
  757.                 } else {
  758.                     $postDataInfo['PD']['card_num'] = $tokenizerService->getToken($postData['PD']['card_num']);
  759.                 }
  760.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  761.                 $postDataInfo['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  762.             }
  763.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
  764.             $formUserInfo = new FormUserInfo();
  765.             $formUserInfo->setInfo($encodedInfo);
  766.             $formUserInfo->setPublicKey($publicKey);
  767.             $em->persist($formUserInfo);
  768.             $em->flush();
  769.             $session->set($transactionId.'[experience][user_info]'$formUserInfo->getId());
  770.             if ((true !== $session->has($transactionId.'[experience][retry]')) || (true !== $session->has($transactionId.'[experience][prepayment_check]'))) {
  771.                 if ($session->has($transactionId.'[experience][detailVariables]')) {
  772.                     //$postData = $request->all();                    |
  773.                     $passangersData $request->get('PI');
  774.                     $passangerNames = [];
  775.                     for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  776.                         $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  777.                         $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  778.                     }
  779.                     $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  780.                     if (== sizeof($nameWhitelist)) {
  781.                         $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  782.                         if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  783.                                 (sizeof($nameBlacklist)) ||
  784.                                 (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  785.                             return $this->json(['error' => 'error''message' => 'nombre inválido']);
  786.                         }
  787.                     }
  788.                     $isFront $session->has('operatorId');
  789.                     if ($isFront) {
  790.                         $customer null;
  791.                         $ordersProduct null;
  792.                     } else {
  793.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  794.                         $ordersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
  795.                     }
  796.                     if (null == $ordersProduct) {
  797.                         $documentTypes $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  798.                         $arrayDocumentTypes = [];
  799.                         foreach ($documentTypes as $documentType) {
  800.                             $arrayDocumentTypes[$documentType->getExternalCode()] = $documentType->getId();
  801.                         }
  802.                         $genders $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  803.                         $arrayGenders = [];
  804.                         foreach ($genders as $gender) {
  805.                             $arrayGenders[$gender->getCode()] = $gender->getExternalCode();
  806.                         }
  807.                         $session->set($transactionId.'[experience][retry]'$parameterBag->get('aviatur_payment_retry_times'));
  808.                         $detail $session->get($transactionId.'[experience][detailVariables]');
  809.                         $session->set($transactionId.'[experience][prepayment]'$detail);
  810.                         $cancelPenalties = (string) '';
  811.                         $ajaxUrl $this->generateUrl('aviatur_experience_prepayment_step_2_secure');
  812.                         return $this->json(['cancelPenalties' => $cancelPenalties'ajax_url' => $ajaxUrl]);
  813.                     } else {
  814.                         $booking = [];
  815.                         $cus = [];
  816.                         foreach ($ordersProduct as $orderProduct) {
  817.                             $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  818.                             $paymentResponse json_decode($productResponse);
  819.                             array_push($booking'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
  820.                             if (isset($paymentResponse->x_approval_code)) {
  821.                                 array_push($cus$paymentResponse->x_approval_code);
  822.                             } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  823.                                 array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  824.                             }
  825.                         }
  826.                         return $this->json([
  827.                                     'error' => 'pending payments',
  828.                                     'message' => 'pending_payments',
  829.                                     'booking' => $booking,
  830.                                     'cus' => $cus,
  831.                         ]);
  832.                     }
  833.                 } else {
  834.                     return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
  835.                 }
  836.             } else {
  837.                 $paymentData $request->get('PD');
  838.                 $paymentData json_decode(json_encode($paymentData));
  839.                 $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  840.                 $json json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  841.                 if (!is_null($json)) {
  842.                     $json->ajax_url $this->generateUrl('aviatur_experience_prepayment_step_2_secure');
  843.                     // reemplazar datos de pago por los nuevos.
  844.                     $oldPostData json_decode($session->get($transactionId.'[experience][detail_data]'));
  845.                     //$card_num_token = $tokenizerService->getToken($paymentData->card_num);
  846.                     if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
  847.                         if (isset($paymentData->cusPOptSelected)) {
  848.                             $customerLogin $tokenStorage->getToken()->getUser();
  849.                             $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLogintrue);
  850.                             $card_num_token $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  851.                         } else {
  852.                             $card_num_token $tokenizerService->getToken($paymentData->card_num);
  853.                         }
  854.                         $card_values = ['card_num_token' => $card_num_token'card_num' => $paymentData->card_num];
  855.                     }
  856.                     unset($oldPostData->PD);
  857.                     $oldPostData->PD $paymentData;
  858.                     if (isset($card_num_token)) {
  859.                         $oldPostData->PD->card_values $card_values;
  860.                     }
  861.                     $session->set($transactionId.'[experience][detail_data]'json_encode($oldPostData));
  862.                     $response = new Response(json_encode($json));
  863.                     $response->headers->set('Content-Type''application/json');
  864.                     return $response;
  865.                 } else {
  866.                     return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos datos de tu orden, por favor vuelve a intentarlo')]);
  867.                 }
  868.             }
  869.         } else {
  870.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  871.         }
  872.     }
  873.     public function prePaymentStep2Action(Request $requestParameterBagInterface $parameterBagTwigFolder $twigFolderAviaturErrorHandler $errorHandlerAviaturExperienceService $experienceService)
  874.     {
  875.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  876.         $order = [];
  877.         $infoDates = [];
  878.         if ($request->isXmlHttpRequest()) {
  879.             $em $this->managerRegistry;
  880.             $session $this->session;
  881.             $agency $this->agency;
  882.             $billingData $request->get('BD');
  883.             $transactionId $session->get($transactionIdSessionName);
  884.             $session->set($transactionId.'[experience][prepayment_check]'true);
  885.             $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  886.             if (true !== $session->has($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']')) {
  887.                 if ($session->has($transactionId.'[experience][detailVariables]')) {
  888.                     $isFront $session->has('operatorId');
  889.                     if ($isFront) {
  890.                         $customer $billingData;
  891.                         $customer['isFront'] = true;
  892.                         $status 'B2T';
  893.                     } else {
  894.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  895.                         $status 'waiting';
  896.                     }
  897.                     if (isset($agency)) {
  898.                         $experienceService->createExtraExperience($detailVariables->infoExperience$request$transactionId);
  899.                         $infoDates json_decode($session->get($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'), true);
  900.                         $postData json_decode($session->get($transactionId.'[experience][detail_data]'));
  901.                         $order json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'), true);
  902.                         $orderId str_replace('ON'''$order['order']);
  903.                         $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  904.                         $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[experience][user_info]'));
  905.                         $formUserInfo->setOrder($orderEntity);
  906.                         $em->persist($formUserInfo);
  907.                         $em->flush();
  908.                         if ($isFront) {
  909.                             $order['url'] = $this->makeReservation($transactionId);
  910.                         } else {
  911.                             if ('true' == (string) $detailVariables->infoExperience[0]->info->ExperienceDetail->FormaVenta) {
  912.                                 $order['url'] = $this->generateUrl('aviatur_experience_payment_secure');
  913.                             } else {
  914.                                 $orderProductCode json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  915.                                 $productId str_replace('PN'''$orderProductCode->products);
  916.                                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  917.                                 $ratePlan explode('@||'$postData->EI->ratePlan);
  918.                                 foreach ($detailVariables->rateExperiences as $rateExperiences) {
  919.                                     $code explode('@||'$rateExperiences->Code);
  920.                                     if ($code[0] === $ratePlan[0] && $code[1] === $ratePlan[1]) {
  921.                                         $x_total_amount $rateExperiences->Amount;
  922.                                     }
  923.                                 }
  924.                                 if (empty($x_total_amount)) {
  925.                                     return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '''Ocurrio un error al tarificar, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  926.                                 } else {
  927.                                     $infoDates['AmountTotal'] = $x_total_amount;
  928.                                     $session->set($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'json_encode($infoDates));
  929.                                 }
  930.                                 $experienceService->xmlExperienceExtra($transactionId$detailVariables->infoExperience[0]->id$orderProduct->getStatus(), falsefalse);
  931.                                 $EmitirSolicitud $experienceService->EmitirSolicitud($orderProduct$detailVariables->infoExperience[0]->idtrue);
  932.                                  // Obtener el valor almacenado en la sesión
  933.                                  $storedVariables $session->get($transactionId '[experience][detailVariables]');
  934.                                  // Decodificar el JSON si es necesario
  935.                                  $detailVariables json_decode($storedVariablestrue);
  936.                                  $FormaVenta $detailVariables['FormaVenta'] ?? null;
  937.                                  // dd($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct->getStatus());
  938.                                  if ('Ok' == $EmitirSolicitud) {
  939.                                      $twig 'aviatur_experience_reservation_success_secure';
  940.                                  } elseif('false' == $FormaVenta and isset($FormaVenta)){
  941.                                      $twig 'aviatur_experience_reservation_success_secure';
  942.                                  } else {
  943.                                      $twig 'aviatur_experience_payment_error_secure'//no existe?
  944.                                  }
  945.                                 $order['url'] = $this->generateUrl($twig);
  946.                             }
  947.                         }
  948.                         return $this->json($order);
  949.                     } else {
  950.                         return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró la agencia con el dominio: '.$request->getHost()));
  951.                     }
  952.                 } else {
  953.                     return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
  954.                 }
  955.             } else {
  956.                 $postData json_decode($session->get($transactionId.'[experience][detail_data]'));
  957.                 if ('true' == (string) $detailVariables->infoExperience[0]->info->ExperienceDetail->FormaVenta) {
  958.                     $order['url'] = $this->generateUrl('aviatur_experience_payment_secure');
  959.                 } else {
  960.                     $orderProductCode json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  961.                     $productId str_replace('PN'''$orderProductCode->products);
  962.                     $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  963.                     $ratePlan explode('@||'$postData->EI->ratePlan);
  964.                     foreach ($detailVariables->rateExperiences as $rateExperiences) {
  965.                         $code explode('@||'$rateExperiences->Code);
  966.                         if ($code[0] === $ratePlan[0] && $code[1] === $ratePlan[1]) {
  967.                             $x_total_amount $rateExperiences->Amount;
  968.                         }
  969.                     }
  970.                     if (empty($x_total_amount)) {
  971.                         return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '''Ocurrio un error al tarificar, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  972.                     } else {
  973.                         $infoDates['AmountTotal'] = $x_total_amount;
  974.                     }
  975.                     $EmitirSolicitud $experienceService->EmitirSolicitud($orderProduct$detailVariables->infoExperience[0]->idtrue);
  976.                     if ('Ok' == $EmitirSolicitud) {
  977.                         $twig 'aviatur_experience_reservation_success_secure';
  978.                     } else {
  979.                         $twig 'aviatur_experience_payment_error_secure'//no existe?
  980.                     }
  981.                     $order['url'] = $this->generateUrl($twig);
  982.                 }
  983.                 return $this->json($order);
  984.             }
  985.         } else {
  986.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  987.         }
  988.     }
  989.     public function paymentAction(Request $requestRouterInterface $routerParameterBagInterface $parameterBagTwigFolder $twigFolderAviaturErrorHandler $errorHandlerAviaturExperienceService $experienceServiceP2PController $p2PControllerPSEController $PSEControllerSafetypayController $safetypayControllerCashController $cashControllerTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentService, \Swift_Mailer $mailerTokenizerService $tokenizerServiceAviaturLogSave $aviaturLogSaveOrderController $orderController)
  990.     {
  991.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  992.         $emailNotification $parameterBag->get('email_notification');
  993.         $orderProduct = [];
  994.         $emissionData = [];
  995.         $response null;
  996.         $array = [];
  997.         $em $this->managerRegistry;
  998.         $session $this->session;
  999.         $transactionId $session->get($transactionIdSessionName);
  1000.         $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  1001.         $postData json_decode($session->get($transactionId.'[experience][detail_data]'));
  1002.         $orderInfo json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  1003.         $infoDates json_decode($session->get($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'), true);
  1004.         $productId str_replace('PN'''$orderInfo->products);
  1005.         $orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1006.         $paymentData $postData->PD;
  1007.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  1008.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  1009.         $ratePlan explode('@||'$postData->EI->ratePlan);
  1010.         foreach ($detailVariables->rateExperiences as $rateExperiences) {
  1011.             $code explode('@||'$rateExperiences->Code);
  1012.             if ($code[0] === $ratePlan[0] && $code[1] === $ratePlan[1]) {
  1013.                 $x_total_amount $rateExperiences->Amount;
  1014.             }
  1015.         }
  1016.         if (empty($x_total_amount)) {
  1017.             return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '''Ocurrio un error al tarificar, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  1018.         } else {
  1019.             $infoDates['AmountTotal'] = $x_total_amount;
  1020.             $trm 1;
  1021.             if ($session->has($transactionId.'[mpt][exchangeValues]')) {
  1022.                 $trm $session->get('[mpt][finantial_rate]');
  1023.                 if (!empty($x_total_amount)) {
  1024.                     $infoDates['amount'] = $x_total_amount;
  1025.                     $x_total_amount $x_total_amount $trm;
  1026.                     $infoDates['AmountTotal'] = $x_total_amount;
  1027.                 }
  1028.             }
  1029.             $session->set($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'json_encode($infoDates));
  1030.         }
  1031.         $aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
  1032.         $x_amount_base $x_total_amount / ($aviaturPaymentIva);
  1033.         $x_amount_iva $x_amount_base $aviaturPaymentIva;
  1034.         $session->set($transactionId.'[experience][payment][only]'true);
  1035.         if ('p2p' == $paymentData->type) {
  1036.             if (isset($paymentData->cusPOptSelected)) {
  1037.                 $customerLogin $tokenStorage->getToken()->getUser();
  1038.                 $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLogintrue);
  1039.                 $cardToken $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  1040.                 $paymentData->card_num $cardToken;
  1041.                 $paymentData->card_values->card_num_token $cardToken;
  1042.             }
  1043.             $array = [
  1044.                 'x_currency_code' => (string) 'COP',
  1045.                 'x_amount' => number_format(round((float) ($x_total_amount)), 0'.'''),
  1046.                 'x_tax' => number_format(round((float) ($x_amount_iva)), 2'.'''),
  1047.                 'x_amount_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  1048.                 'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  1049.                 'x_first_name' => $customer->getFirstname(),
  1050.                 'x_last_name' => $customer->getLastname(),
  1051.                 'x_description' => 'Paquete - '.$infoDates['datesTransaction']['ProductName'],
  1052.                 'x_cust_id' => $customer->getDocumentType()->getPaymentcode().' '.$customer->getDocumentnumber(),
  1053.                 'x_address' => $customer->getAddress(),
  1054.                 'x_phone' => $customer->getPhone(),
  1055.                 'x_email' => $customer->getEmail(),
  1056.                 'x_card_num' => $paymentData->card_num,
  1057.                 'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
  1058.                 'x_card_code' => $paymentData->card_code,
  1059.                 'x_differed' => $paymentData->differed,
  1060.                 'x_client_id' => $postData->BD->id,
  1061.                 'product_type' => 'experience',
  1062.             ];
  1063.             if (isset($paymentData->card_values)) {
  1064.                 $array['card_values'] = (array) $paymentData->card_values;
  1065.             }
  1066.             if (isset($paymentData->cusPOptSelected)) {
  1067.                 $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  1068.             }
  1069.             if (isset($paymentData->savePaymProc)) {
  1070.                 $array['x_provider_id'] = 1;
  1071.             } elseif (isset($paymentData->cusPOptSelected)) {
  1072.                 if (isset($paymentData->cusPOptSelectedStatus)) {
  1073.                     if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
  1074.                         $array['x_provider_id'] = 1;
  1075.                     } else {
  1076.                         $array['x_provider_id'] = 2;
  1077.                     }
  1078.                 } else {
  1079.                     $array['x_provider_id'] = 2;
  1080.                 }
  1081.             }
  1082.             // $paymentResponse = $p2PController->placetopayAction($array, true, $detailVariables->infoExperience[0]->id);
  1083.             $paymentResponse $p2PController->placetopayAction($parameterBag$tokenizerService$methodPaymentService$mailer$aviaturLogSave$arraytrue$detailVariables->infoExperience[0]->id);
  1084.             $experienceService->xmlExperienceExtra($transactionId$detailVariables->infoExperience[0]->id$orderProduct[0]->getStatus());
  1085.             unset($array['x_client_id']);
  1086.             if (null != $paymentResponse) {
  1087.                 return $this->redirect($this->generateUrl('aviatur_experience_payment_p2p_return_url_secure', [], true));
  1088.             } else {
  1089.                 $orderProduct[0]->setStatus('pending');
  1090.                 $em->persist($orderProduct[0]);
  1091.                 $em->flush();
  1092.                 return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '''No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción22'));
  1093.             }
  1094.         } elseif ('pse' == $paymentData->type) {
  1095.             $array = [
  1096.                 'x_doc_num' => $paymentData->pse_doc_num,
  1097.                 'x_doc_type' => $paymentData->pse_doc_type,
  1098.                 // 'x_doc_num' => $customer->getDocumentnumber(),
  1099.                 // 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  1100.                 'x_first_name' => $customer->getFirstname(),
  1101.                 'x_last_name' => $customer->getLastname(),
  1102.                 'x_company' => 'Aviatur',
  1103.                 'x_email' => $customer->getEmail(),
  1104.                 'x_address' => $customer->getAddress(),
  1105.                 'x_city' => $customer->getCity()->getDescription(),
  1106.                 'x_province' => $customer->getCity()->getDescription(),
  1107.                 'x_country' => $customer->getCountry()->getDescription(),
  1108.                 'x_phone' => $customer->getPhone(),
  1109.                 'x_mobile' => $customer->getCellphone(),
  1110.                 'x_bank' => $paymentData->pse_bank,
  1111.                 'x_type' => $paymentData->pse_type,
  1112.                 'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  1113.                 'x_description' => 'Paquete - '.$infoDates['datesTransaction']['ProductName'],
  1114.                 'x_currency' => (string) 'COP',
  1115.                 'x_total_amount' => number_format(round((float) ($x_total_amount)), 0'.'''),
  1116.                 'x_tax_amount' => number_format(round((float) ($x_amount_iva)), 2'.'''),
  1117.                 'x_devolution_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  1118.                 'x_tax' => number_format(round((float) (0)), 2'.'''),
  1119.                 'x_tip_amount' => number_format(round((float) (0)), 2'.'''),
  1120.                 'product_type' => 'experience',
  1121.                 'x_transactionId' => $transactionId,
  1122.             ];
  1123.             $paymentResponse $PSEController->sendPaymentAction($request$session$router$parameterBag$mailer$orderController$array$orderProduct);
  1124.             $experienceService->xmlExperienceExtra($transactionId$detailVariables->infoExperience[0]->id$orderProduct[0]->getStatus());
  1125.             if (!isset($paymentResponse->error)) {
  1126.                 switch ($paymentResponse->createTransactionResult->returnCode) {
  1127.                     case 'SUCCESS':
  1128.                         return $this->redirect($paymentResponse->createTransactionResult->bankURL);
  1129.                     case 'FAIL_EXCEEDEDLIMIT':
  1130.                         return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '');
  1131.                     case 'FAIL_BANKUNREACHEABLE':
  1132.                         return $this->redirect($this->generateUrl('aviatur_experience_retry_secure'), '');
  1133.                     default:
  1134.                         return $this->redirect($this->generateUrl('aviatur_experience_retry_secure'), '');
  1135.                 }
  1136.             } else {
  1137.                 return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), 'Error al procesar el pago''Ocurrió un problema al intentar crear tu transacción, '.$paymentResponse->error));
  1138.             }
  1139.         } elseif ('safety' == $paymentData->type) {
  1140.             $transactionUrl $this->generateUrl('aviatur_payment_safetypay', [], true);
  1141.             $array = ['x_doc_num' => $customer->getDocumentnumber(),
  1142.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  1143.                 'x_first_name' => $customer->getFirstname(),
  1144.                 'x_last_name' => $customer->getLastname(),
  1145.                 'x_company' => 'Aviatur',
  1146.                 'x_email' => $customer->getEmail(),
  1147.                 'x_address' => $customer->getAddress(),
  1148.                 'x_city' => $customer->getCity()->getDescription(),
  1149.                 'x_province' => $customer->getCity()->getDescription(),
  1150.                 'x_country' => $customer->getCountry()->getDescription(),
  1151.                 'x_phone' => $customer->getPhone(),
  1152.                 'x_mobile' => $customer->getCellphone(),
  1153.                 'x_reference' => $orderInfo->products,
  1154.                 'x_booking' => $request->get('PlanID'),
  1155.                 'x_description' => 'Paquete - '.$infoDates['datesTransaction']['ProductName'],
  1156.                 'x_currency' => 'COP',
  1157.                 'x_total_amount' => number_format(round((float) ($x_total_amount)), 2'.'''),
  1158.                 'x_tax_amount' => number_format(round((float) (0)), 2'.'''),
  1159.                 'x_devolution_base' => number_format(round((float) (0)), 2'.'''),
  1160.                 'x_tip_amount' => number_format(round(0), 2'.'''),
  1161.                 'x_payment_data' => $paymentData->type,
  1162.                 'x_type_description' => 'experience',
  1163.             ];
  1164.             $parametMerchant = [
  1165.                 'MerchantSalesID' => $array['x_reference'],
  1166.                 'Amount' => $array['x_total_amount'],
  1167.                 'transactionUrl' => $transactionUrl,
  1168.                 'dataTrans' => $array,
  1169.             ];
  1170.             $safeTyPay $safetypayController->safetyAction($router$parameterBag$mailer$parametMerchant$array);
  1171.             $experienceService->xmlExperienceExtra($transactionId$detailVariables->infoExperience[0]->id$orderProduct[0]->getStatus());
  1172.             if ('ok' == $safeTyPay['status']) {
  1173.                 if ('baloto' == $paymentData->type) {
  1174.                     $cash '&CountryId=COL&ChannelId=CASH';
  1175.                     $session->set($transactionId.'[experience][retry]'0);
  1176.                     return $this->redirect($safeTyPay['response'].$cash);
  1177.                 } else {
  1178.                     return $this->redirect($safeTyPay['response']);
  1179.                 }
  1180.             } else {
  1181.                 $emissionData->x_booking $array['x_booking'];
  1182.                 $emissionData->x_first_name $array['x_first_name'];
  1183.                 $emissionData->x_last_name $array['x_last_name'];
  1184.                 $emissionData->x_doc_num $array['x_doc_num'];
  1185.                 $emissionData->x_reference $array['x_reference'];
  1186.                 $emissionData->x_description $array['x_description'];
  1187.                 $emissionData->x_total_amount $array['x_total_amount'];
  1188.                 $emissionData->x_email $array['x_email'];
  1189.                 $emissionData->x_address $array['x_address'];
  1190.                 $emissionData->x_phone $array['x_phone'];
  1191.                 $emissionData->x_type_description $array['x_type_description'];
  1192.                 $emissionData->x_resultSafetyPay $safeTyPay;
  1193.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($responsetrue);
  1194.                 $message = (new \Swift_Message())
  1195.                         ->setContentType('text/html')
  1196.                         ->setFrom($session->get('emailNoReply'))
  1197.                         ->setTo($emailNotification)
  1198.                         ->setSubject('Error Creación Token SafetyPay AssistCard'.$emissionData->x_reference)
  1199.                         ->setBody($mailInfo);
  1200.                 $mailer->send($message);
  1201.                 return $this->redirect($this->generateUrl('aviatur_experience_payment_rejected_secure'));
  1202.             }
  1203.         } elseif ('cash' == $paymentData->type) {
  1204.             $agency $this->agency;
  1205.             $agencyName $agency->getOfficeId();
  1206.             $array['x_officeId'] = $agencyName;
  1207.             $array['x_doc_num'] = $customer->getDocumentnumber();
  1208.             $array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
  1209.             $array['x_first_name'] = $customer->getFirstname();
  1210.             $array['x_last_name'] = $customer->getLastname();
  1211.             $array['x_company'] = 'Aviatur';
  1212.             $array['x_email'] = $customer->getEmail();
  1213.             $array['x_address'] = $customer->getAddress();
  1214.             $array['x_city'] = $customer->getCity()->getDescription();
  1215.             $array['x_province'] = $customer->getCity()->getDescription();
  1216.             $array['x_country'] = $customer->getCountry()->getDescription();
  1217.             $array['x_phone'] = $customer->getPhone();
  1218.             $array['x_mobile'] = $customer->getCellphone();
  1219.             $array['x_payment_data'] = $paymentData->type;
  1220.             $array['x_reference'] = $orderInfo->products;
  1221.             $array['x_description'] = $infoDates['datesTransaction']['ProductName'];
  1222.             $array['x_booking'] = $orderProduct[0]->getBooking();
  1223.             $array['x_total_amount'] = number_format(round((float) $x_total_amount), 0'.''');
  1224.             $array['x_tax_amount'] = number_format(round((float) (0)), 2'.''');
  1225.             $array['x_devolution_base'] = number_format(round((float) (0)), 2'.''');
  1226.             $array['x_tip_amount'] = number_format(round(0), 0'.''');
  1227.             $array['x_currency'] = 'COP';
  1228.             $array['x_type_description'] = $orderProduct[0]->getDescription();
  1229.             $array['x_cantidad'] = $postData->PI->person_count_1;
  1230.             $fecha $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
  1231.             $fechalimite $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
  1232.             $nuevafecha strtotime('+2 hour'strtotime($fecha));
  1233.             $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  1234.             if (strcmp($fechavigencia$fechalimite) > 0) {
  1235.                 $fechavigencia $fechalimite;
  1236.             }
  1237.             $array['x_fechavigencia'] = $fechavigencia;
  1238.             $cashPay $cashController->cashAction($array);
  1239.             $experienceService->xmlExperienceExtra($transactionId$detailVariables->infoExperience[0]->id$orderProduct[0]->getStatus());
  1240.             if ('ok' == $cashPay->status) {
  1241.                 $session->set($transactionId.'[experience][cash_result]'json_encode($cashPay));
  1242.                 return $this->redirect($this->generateUrl('aviatur_experience_payment_success_secure'));
  1243.             } else {
  1244.                 $retryCount = (int) $session->get($transactionId.'[experience][retry]');
  1245.                 //$toEmails = array('soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', 'gustavo.hincapie@aviatur.com');
  1246.                 $toEmails = ['sergio.amaya@aviatur.com'];
  1247.                 $emissionData['x_booking'] = $array['x_booking'];
  1248.                 $emissionData['x_first_name'] = $array['x_first_name'];
  1249.                 $emissionData['x_last_name'] = $array['x_last_name'];
  1250.                 $emissionData['x_doc_num'] = $array['x_doc_num'];
  1251.                 $emissionData['x_reference'] = $array['x_reference'];
  1252.                 $emissionData['x_description'] = $array['x_description'];
  1253.                 $emissionData['x_total_amount'] = $array['x_total_amount'];
  1254.                 $emissionData['x_email'] = $array['x_email'];
  1255.                 $emissionData['x_address'] = $array['x_address'];
  1256.                 $emissionData['x_phone'] = $array['x_phone'];
  1257.                 $emissionData['x_type_description'] = $array['x_type_description'];
  1258.                 $emissionData['x_error'] = $cashPay->status;
  1259.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($cashPaytrue);
  1260.                 $message = (new \Swift_Message())
  1261.                         ->setContentType('text/html')
  1262.                         ->setFrom($session->get('emailNoReply'))
  1263.                         ->setTo($toEmails)
  1264.                         //->setBcc('arthur.picerna@aviatur.com')
  1265.                         ->setSubject('Error Creación Transacción Baloto'.$emissionData['x_reference'].' - '.$orderProduct[0]->getOrder()->getAgency()->getName())
  1266.                         ->setBody($mailInfo);
  1267.                 $mailer->send($message);
  1268.                 $session->set($transactionId.'[experience][retry]'$retryCount 1);
  1269.                 return $this->redirect($this->generateUrl('aviatur_experience_payment_rejected_secure'));
  1270.             }
  1271.         } else {
  1272.             return $errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '''El tipo de pago es invalido');
  1273.         }
  1274.     }
  1275.     public function p2pCallbackAction(Request $requestParameterBagInterface $parameterBagAviaturErrorHandler $errorHandlerOrderController $orderControllerAviaturMailer $aviaturMailerAviaturEncoder $aviaturEncoderAviaturExperienceService $experienceServiceValidateSanctionsRenewal $validateSanctionsTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentService)
  1276.     {
  1277.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1278.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  1279.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1280.         $agency null;
  1281.         $em $this->managerRegistry;
  1282.         $session $this->session;
  1283.         $fullRequest $request;
  1284.         $request $fullRequest->request;
  1285.         $transactionId $session->get($transactionIdSessionName);
  1286.         if (true === $request->has('correlationID')) {
  1287.             $correlationId $request->get('correlationID');
  1288.         } else {
  1289.             $correlationId $session->get($correlationIdSessionName);
  1290.         }
  1291.         $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  1292.         $orderProductCode json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  1293.         $productId str_replace('PN'''$orderProductCode->products);
  1294.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1295.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1296.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1297.         $jsonSendEmail $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
  1298.         if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
  1299.             $email json_decode($jsonSendEmail->getDescription())->email->CallBack;
  1300.         }
  1301.         $references $orderProductCode->order.'-'.$orderProductCode->products;
  1302.         $bookings $orderProduct->getBooking();
  1303.         if (null != $decodedResponse) {
  1304.             $twig '';
  1305.             $retryCount = (int) $session->get($transactionId.'[experience][retry]');
  1306.             switch ($decodedResponse->x_response_code) {
  1307.                 case isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber):
  1308.                     //rechazado cybersource
  1309.                     $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  1310.                     if ($parameters) {
  1311.                         if (== $parameters->getValue()) {
  1312.                             if (== $decodedResponse->x_response_code) {
  1313.                                 $postData json_decode($session->get($transactionId.'[experience][detail_data]'));
  1314.                                 $postData->PD->card_num $decodedRequest->x_card_num;
  1315.                                 $postData->PD->card_values->card_num_token $decodedRequest->x_card_num;
  1316.                                 if (isset($postData->PD->cusPOptSelected)) {
  1317.                                     if (isset($postData->PD->cusPOptSelectedStatus)) {
  1318.                                         if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  1319.                                             $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  1320.                                             $customerLogin $tokenStorage->getToken()->getUser();
  1321.                                             $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1322.                                         }
  1323.                                     }
  1324.                                 }
  1325.                                 if (isset($postData->PD->savePaymProc)) {
  1326.                                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  1327.                                     $customerLogin $tokenStorage->getToken()->getUser();
  1328.                                     $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1329.                                 }
  1330.                             }
  1331.                         }
  1332.                     }
  1333.                     $twig 'aviatur_experience_payment_rejected_secure';
  1334.                     // no break
  1335.                 case 3:// pendiente p2p
  1336.                     $twig '' != $twig $twig 'aviatur_experience_payment_pending_secure';
  1337.                     $updateOrder $orderController->updatePaymentAction($orderProduct);
  1338.                     $orderProduct->setUpdatingdate(new \DateTime());
  1339.                     $em->persist($orderProduct);
  1340.                     $em->flush();
  1341.                     $retryCount 1;
  1342.                     break;
  1343.                 case 0:// error p2p
  1344.                     $twig 'aviatur_experience_payment_error_secure'//no existe?
  1345.                     if (isset($email)) {
  1346.                         $from 'noreply@aviatur.com';
  1347.                         $error $twig;
  1348.                         $subject $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
  1349.                         $body '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  1350.                         $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  1351.                     }
  1352.                     // no break
  1353.                 case 2:// rechazada p2p
  1354.                     $twig '' != $twig $twig 'aviatur_experience_payment_rejected_secure';
  1355.                     $orderProduct->setResume('No reservation');
  1356.                     if (isset($email)) {
  1357.                         $from 'noreply@aviatur.com';
  1358.                         $error $twig;
  1359.                         $subject $orderProduct->getDescription().':Transacción rechazada';
  1360.                         $body '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  1361.                         $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  1362.                     }
  1363.                     break;
  1364.                 case 1:// aprobado p2p
  1365.                     $decodedRequest->product_type 'experience';
  1366.                     $decodedResponse->product_type 'experience';
  1367.                     $encodedRequest $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
  1368.                     $encodedResponse $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
  1369.                     $orderProduct->setPayrequest($encodedRequest);
  1370.                     $orderProduct->setPayresponse($encodedResponse);
  1371.                     $twig 'aviatur_experience_payment_success_secure';
  1372.                     $postData json_decode($session->get($transactionId.'[experience][detail_data]'));
  1373.                     $postData->PD->card_num $decodedRequest->x_card_num;
  1374.                     $postData->PD->card_values->card_num_token $decodedRequest->x_card_num;
  1375.                     if (isset($postData->PD->cusPOptSelected)) {
  1376.                         if (isset($postData->PD->cusPOptSelectedStatus)) {
  1377.                             if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  1378.                                 $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  1379.                                 $customerLogin $tokenStorage->getToken()->getUser();
  1380.                                 $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1381.                             }
  1382.                         }
  1383.                     }
  1384.                     if (isset($postData->PD->savePaymProc)) {
  1385.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  1386.                         $customerLogin $tokenStorage->getToken()->getUser();
  1387.                         $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1388.                     }
  1389.                     $experienceService->EmitirSolicitud($orderProduct$detailVariables->infoExperience[0]->idtrue);
  1390.                     $updateOrder $orderController->updatePaymentAction($orderProduct);
  1391.                     $session->set($transactionId.'[experience][retry]'$aviaturPaymentRetryTimes);
  1392.                     $em->persist($orderProduct);
  1393.                     $em->flush();
  1394.                     break;
  1395.             }
  1396.             $session->set($transactionId.'[experience][retry]'$retryCount 1);
  1397.             //////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
  1398.             // if ($session->has('Marked_name') && $session->has('Marked_document')) {
  1399.             //     $product = 'Experiencias';
  1400.             //     $validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
  1401.             // }
  1402.             /* Pero solo si hay condicionados (no bloqueados) y que paguen con Tarjeta */
  1403.             if ($session->has('Marked_users')) {
  1404.                 $product 'Experiencias';
  1405.                 $validateSanctions->sendMarkedEmail($orderProductCode$session$agency$orderProduct$transactionId$product);
  1406.             }
  1407.             ////////////////////////////////////////////////////////////////////////////////////
  1408.             return $this->redirect($this->generateUrl($twig));
  1409.         } else {
  1410.             $orderProduct->setStatus('pending');
  1411.             $em->persist($orderProduct);
  1412.             $em->flush();
  1413.             return $errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '''No hay respuesta por parte del servicio de pago');
  1414.         }
  1415.     }
  1416.     public function pseCallbackAction(ParameterBagInterface $parameterBagTwigFolder $twigFolderAviaturErrorHandler $errorHandlerOrderController $orderControllerAviaturMailer $aviaturMailerAviaturEncoder $aviaturEncoderAviaturExperienceService $experienceServicePSEController $PSEController$transaction)
  1417.     {
  1418.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1419.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1420.         $status null;
  1421.         $detailVariables null;
  1422.         $twig null;
  1423.         $em $this->managerRegistry;
  1424.         $session $this->session;
  1425.         if ($session->has('agencyId')) {
  1426.             $agency $this->agency;
  1427.         } else {
  1428.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1);
  1429.         }
  1430.         $paymentMethod $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pse');
  1431.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findOneBy(['agency' => $agency'paymentMethod' => $paymentMethod]);
  1432.         $tranKey $paymentMethodAgency->getTrankey();
  1433.         $decodedUrl json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
  1434.         $transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
  1435.         $orders $decodedUrl['x_orders'];
  1436.         if (isset($orders['experience'])) {
  1437.             $experiencesOrders explode('+'$orders['experience']);
  1438.             $orderProductCode $experiencesOrders[0];
  1439.             $productId $experiencesOrders[0];
  1440.             $retryCount 1;
  1441.         } else {
  1442.             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontro identificador de la transacción'));
  1443.         }
  1444.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1445.         if (empty($orderProduct)) {
  1446.             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1447.         } else {
  1448.             if ('approved' == $orderProduct->getStatus()) {
  1449.                 //return $this->redirect($this->get("aviatur_error_handler")->errorRedirectNoEmail($this->get("aviatur_agency_twig_folder")->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
  1450.             }
  1451.             $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1452.             if (isset($decodedResponse->createTransactionResult)) {
  1453.                 $pseTransactionId $decodedResponse->createTransactionResult->transactionID;
  1454.                 $paymentResponse $PSEController->pseCallbackAction($orderController$pseTransactionId);
  1455.                 if (!isset($paymentResponse->error)) {
  1456.                     if (!$session->has($transactionId.'[experience][detail_data]')) {
  1457.                         $message 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
  1458.                         return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra'$message));
  1459.                     }
  1460.                     $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  1461.                     $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1462.                     $orderProduct->setUpdatingdate(new \DateTime());
  1463.                     $em->persist($orderProduct);
  1464.                     $em->flush();
  1465.                     if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
  1466.                         switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
  1467.                                 case 'OK':
  1468.                                     $twig 'aviatur_experience_payment_success_secure';
  1469.                                     $status 'approved';
  1470.                                     break;
  1471.                                 case 'PENDING':
  1472.                                     $twig 'aviatur_experience_payment_pending_secure';
  1473.                                     $status 'pending';
  1474.                                     break;
  1475.                                 case 'NOT_AUTHORIZED':
  1476.                                     $twig 'aviatur_experience_payment_error_secure';
  1477.                                     $status 'rejected';
  1478.                                     break;
  1479.                                 case 'FAILED':
  1480.                                     $twig 'aviatur_experience_payment_error_secure';
  1481.                                     $status 'failed';
  1482.                                     break;
  1483.                             }
  1484.                         $orderProduct->setStatus($status);
  1485.                         $orderProduct->getOrder()->setStatus($status);
  1486.                         $orderProduct->setUpdatingdate(new \DateTime());
  1487.                         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1488.                         $em->persist($orderProduct);
  1489.                         $em->flush();
  1490.                         if ('approved' == $status) {
  1491.                             $orderController->updatePaymentAction($orderProductfalsenull);
  1492.                             $segment $detailVariables->infoExperience[0]->id ?? null;
  1493.                             $experienceService->EmitirSolicitud($orderProduct$segmenttrue);
  1494.                             $session->set($transactionId.'[experience][retry]'$aviaturPaymentRetryTimes);
  1495.                             $em->persist($orderProduct);
  1496.                             $em->flush();
  1497.                         }
  1498.                     } elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
  1499.                         echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1500.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1501.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1502.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1503.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1504.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1505.                             transacción <#CUS> .';
  1506.                         $orderProduct->setEmissiondata('error');
  1507.                         $orderProduct->setUpdatingdate(new \DateTime());
  1508.                         $em->persist($orderProduct);
  1509.                         $em->flush();
  1510.                         $twig 'aviatur_experience_payment_error_secure';
  1511.                     }
  1512.                     if ($session->has($transactionId.'[experience][retry]')) {
  1513.                         $session->set($transactionId.'[experience][retry]'$retryCount 1);
  1514.                     }
  1515.                     return $this->redirect($this->generateUrl($twig));
  1516.                 } else {
  1517.                     $decodedResponse->getTransactionInformationResult $paymentResponse;
  1518.                     $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1519.                     $orderProduct->setUpdatingdate(new \DateTime());
  1520.                     $em->persist($orderProduct);
  1521.                     $em->flush();
  1522.                     return $this->redirect($errorHandler->errorRedirectNoEmail($errorHandler->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  1523.                 }
  1524.             } else {
  1525.                 return $this->redirect($errorHandler->errorRedirectNoEmail($errorHandler->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  1526.             }
  1527.         }
  1528.     }
  1529.     public function safetyCallbackOkAction(ParameterBagInterface $parameterBagSafetypayController $safetypayControllerAviaturEncoder $aviaturEncoderOrderController $orderControllerAviaturExperienceService $experienceServiceTwigFolder $twigFolderAviaturErrorHandler $errorHandler)
  1530.     {
  1531.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1532.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1533.         $status null;
  1534.         $twig null;
  1535.         $em $this->managerRegistry;
  1536.         $session $this->session;
  1537.         $safeTyPay $safetypayController->safetyok();
  1538.         if (true === $session->has($transactionIdSessionName)) {
  1539.             $transactionId $session->get($transactionIdSessionName);
  1540.             $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  1541.             if (true === $session->has($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']')) {
  1542.                 $orderProductCode json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  1543.                 $productId str_replace('PN'''$orderProductCode->products);
  1544.                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1545.                 $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1546.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1547.                 $payError $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
  1548.                 $notifyError $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
  1549.                 if (isset($decodedResponse->payResponse->OperationResponse)) {
  1550.                     if (=== $payError) {
  1551.                         $retryCount = (int) $session->get($transactionId.'[experience][retry]');
  1552.                         if (== $notifyError) {
  1553.                             switch ($payError) {
  1554.                                 case 0:
  1555.                                     $twig 'aviatur_experience_payment_success_secure';
  1556.                                     $status 'approved';
  1557.                                     break;
  1558.                                 case 2:
  1559.                                     $twig 'aviatur_experience_payment_error_secure';
  1560.                                     $status 'failed';
  1561.                                     break;
  1562.                             }
  1563.                             $orderProduct->setStatus($status);
  1564.                             $orderProduct->getOrder()->setStatus($status);
  1565.                             $orderProduct->setUpdatingdate(new \DateTime());
  1566.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1567.                             $em->persist($orderProduct);
  1568.                             $em->flush();
  1569.                             $orderController->updatePaymentAction($orderProduct);
  1570.                             if ('approved' == $status) {
  1571.                                 $experienceService->EmitirSolicitud($orderProduct$detailVariables->infoExperience[0]->idtrue);
  1572.                                 $session->set($transactionId.'[experience][retry]'$aviaturPaymentRetryTimes);
  1573.                                 $em->persist($orderProduct);
  1574.                                 $em->flush();
  1575.                             }
  1576.                         } else {
  1577.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1578.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1579.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1580.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1581.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1582.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1583.                             transacción <#CUS> .';
  1584.                             $orderProduct->setUpdatingdate(new \DateTime());
  1585.                             $em->persist($orderProduct);
  1586.                             $em->flush();
  1587.                             $twig 'aviatur_experience_payment_error_secure';
  1588.                         }
  1589.                         $session->set($transactionId.'[experience][retry]'$retryCount 1);
  1590.                         return $this->redirect($this->generateUrl($twig));
  1591.                     } else {
  1592.                         $orderProduct->setUpdatingdate(new \DateTime());
  1593.                         $em->persist($orderProduct);
  1594.                         $em->flush();
  1595.                         return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  1596.                     }
  1597.                 } else {
  1598.                     return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción, por favor comuniquese con nosotros'));
  1599.                 }
  1600.             } else {
  1601.                 return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1602.             }
  1603.         } else {
  1604.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró identificador de la transacción'));
  1605.         }
  1606.     }
  1607.     public function safetyCallbackErrorAction(ParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoderTwigFolder $twigFolderAviaturErrorHandler $errorHandler)
  1608.     {
  1609.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1610.         $status null;
  1611.         $em $this->managerRegistry;
  1612.         $session $this->session;
  1613.         $transactionId $session->get($transactionIdSessionName);
  1614.         $retryCount = (int) $session->get($transactionId.'[experience][retry]');
  1615.         $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  1616.         $orderInfo json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  1617.         $productId str_replace('PN'''$orderInfo->products);
  1618.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1619.         $payResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  1620.         $payRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
  1621.         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
  1622.         if ('baloto' == $payRequest->dataTransf->x_payment_data) {
  1623.             $status 'pending';
  1624.             $payResponse->dataTransf->x_response_code 100;
  1625.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
  1626.         } elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
  1627.             $status 'rejected';
  1628.             $payResponse->dataTransf->x_response_code 100;
  1629.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
  1630.         }
  1631.         $orderProduct->setStatus($status);
  1632.         $orderProduct->setUpdatingdate(new \DateTime());
  1633.         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1634.         $order $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
  1635.         $order->setStatus($status);
  1636.         $em->persist($order);
  1637.         $em->persist($orderProduct);
  1638.         $em->flush();
  1639.         if (true !== $session->has($transactionId.'[experience][order]')) {
  1640.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1641.         }
  1642.         $session->set($transactionId.'[experience][retry]'$retryCount 1);
  1643.         return $this->redirect($this->generateUrl('aviatur_experience_payment_rejected_secure'));
  1644.     }
  1645.     public function paymentOutputAction(ParameterBagInterface $parameterBagTwigFolder $twigFolderAviaturEncoder $aviaturEncoderExceptionLog $exceptionLog, \Swift_Mailer $mailerPdf $pdf)
  1646.     {
  1647.         $projectDir $parameterBag->get('kernel.project_dir');
  1648.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1649.         $clientFranquice = [];
  1650.         $orderProductCode null;
  1651.         $paymentResume = [];
  1652.         $customer null;
  1653.         $em $this->managerRegistry;
  1654.         $session $this->session;
  1655.         $transactionId $session->get($transactionIdSessionName);
  1656.         $detailVariables json_decode($session->get($transactionId.'[experience][detailVariables]'));
  1657.         $detail_data json_decode($session->get($transactionId.'[experience][detail_data]'));
  1658.         $infoDates json_decode($session->get($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'), true);
  1659.         $orderInfo json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
  1660.         $detailInfo $session->get($transactionId.'[experience][detailInfo]');
  1661.         $productId str_replace('PN'''$orderInfo->products);
  1662.         $paymentData $detail_data->BD;
  1663.         $isFront $session->has('officeId');
  1664.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1665.         $agency $orderProduct->getOrder()->getAgency();
  1666.         if (!$isFront) {
  1667.             $opRequestInitial json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1668.             $opRequest $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
  1669.             $opResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  1670.             if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
  1671.                 $franquiceCode str_replace(['CR_''RM_''CDNSA'], ['''''CS'], $opResponse->x_franchise);
  1672.                 $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
  1673.                 $franquiceDescription $clientFranquice->getDescription();
  1674.             } else {
  1675.                 $clientFranquice['description'] = 'error';
  1676.                 $franquiceDescription $clientFranquice['description'];
  1677.             }
  1678.             if ((null != $opRequest) && (null != $opResponse)) {
  1679.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
  1680.                 if (isset($opResponse->x_description)) {
  1681.                     $paymentResume = [
  1682.                         'transaction_state' => $opResponse->x_response_code,
  1683.                         'ta_transaction_state' => $opResponse->x_ta_response_code,
  1684.                         'id' => $orderProduct->getBooking(),
  1685.                         'id_context' => $opRequest->x_invoice_num,
  1686.                         'total_amount' => $opResponse->x_amount,
  1687.                         'currency' => $opResponse->x_bank_currency,
  1688.                         'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  1689.                         'iva' => $opRequest->x_tax,
  1690.                         'ip_address' => $opRequest->x_customer_ip,
  1691.                         'bank_name' => $opResponse->x_bank_name,
  1692.                         'client_franquice' => ['description' => $franquiceDescription],
  1693.                         'cuotas' => $opRequest->x_differed,
  1694.                         'card_num' => '************'.substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  1695.                         'reference' => $opResponse->x_transaction_id,
  1696.                         'auth' => $opResponse->x_approval_code,
  1697.                         'transaction_date' => $opResponse->x_transaction_date,
  1698.                         'description' => $opResponse->x_description,
  1699.                         'reason_code' => $opResponse->x_response_reason_code,
  1700.                         'reason_description' => $opResponse->x_response_reason_text,
  1701.                         'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
  1702.                         'client_email' => $opResponse->x_email,
  1703.                         'serviceResponse' => $detailInfo,
  1704.                         'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
  1705.                     ];
  1706.                     if (isset($opRequest->administrative_base)) {
  1707.                         $paymentResume['fee_base'] = $opRequest->administrative_base;
  1708.                         $paymentResume['ta_reference'] = $paymentResume['reference'];
  1709.                         $paymentResume['ta_auth'] = $paymentResume['auth'];
  1710.                         $paymentResume['ta_reason_code'] = $paymentResume['reason_code'];
  1711.                     }
  1712.                     if (isset($opRequest->administrative_amount_tax)) {
  1713.                         $paymentResume['fee_tax'] = $opRequest->administrative_amount_tax;
  1714.                     }
  1715.                     if (isset($opRequest->admin_amount)) {
  1716.                         $paymentResume['x_service_fee'] = $opRequest->admin_amount;
  1717.                         $paymentResume['total_amount'] = $paymentResume['total_amount'] + $opRequest->admin_amount;
  1718.                     }
  1719.                 } elseif (isset($opRequest->dataTransf)) {
  1720.                     if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
  1721.                         $state $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
  1722.                     if (102 == $state):
  1723.                             $state 1;
  1724.                     $reason_description 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
  1725.                             $state 2;
  1726.                     $reason_description 'Transacción creada';
  1727.                     endif;
  1728.                     $paymentResume = [
  1729.                             'transaction_state' => $state,
  1730.                             'id' => $orderProduct->getBooking(),
  1731.                             'currency' => $opRequest->dataTransf->x_currency,
  1732.                             'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
  1733.                             'amount' => null,
  1734.                             'iva' => null,
  1735.                             'ip_address' => $opRequest->dataTransf->dirIp,
  1736.                             'airport_tax' => null,
  1737.                             'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
  1738.                             'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
  1739.                             'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
  1740.                             'description' => $opRequest->dataTransf->x_description,
  1741.                             'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
  1742.                             'reason_description' => $reason_description,
  1743.                             'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  1744.                             'client_email' => $opRequest->dataTransf->x_email,
  1745.                             'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  1746.                             'client_franquice' => ['description' => 'SafetyPay'],
  1747.                             'id_context' => $orderProductCode->order.'-'.$orderProductCode->products,
  1748.                             'serviceResponse' => $detailInfo,
  1749.                             'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
  1750.                         ]; else:
  1751.                         $paymentResume = [
  1752.                             'transaction_state' => 2,
  1753.                             'id' => $orderProduct->getBooking(),
  1754.                             'currency' => $opRequest->dataTransf->x_currency,
  1755.                             'total_amount' => $opRequest->dataTransf->x_total_amount,
  1756.                             'amount' => null,
  1757.                             'iva' => null,
  1758.                             'ip_address' => $opRequest->dataTransf->dirIp,
  1759.                             'airport_tax' => null,
  1760.                             'reference' => $opRequest->dataTransf->x_reference,
  1761.                             'auth' => null,
  1762.                             'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
  1763.                             'description' => $opRequest->dataTransf->x_description,
  1764.                             'reason_code' => 101,
  1765.                             'reason_description' => 'Transacción creada',
  1766.                             'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  1767.                             'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  1768.                             'client_email' => $opRequest->dataTransf->x_email,
  1769.                             'serviceResponse' => $detailInfo,
  1770.                             'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
  1771.                         ];
  1772.                     endif;
  1773.                     if ('baloto' == $opRequest->dataTransf->x_payment_data) {
  1774.                         $paymentResume['transaction_state'] = 3;
  1775.                     }
  1776.                 } elseif (isset($opRequest->infoCash)) {
  1777.                     $paymentResume = [
  1778.                         'transaction_state' => 2,
  1779.                         'id' => $orderProduct->getBooking(),
  1780.                         'id_booking' => $opRequest->infoCash->x_booking,
  1781.                         'id_context' => $opRequest->infoCash->x_reference,
  1782.                         'currency' => $opRequest->infoCash->x_currency,
  1783.                         'total_amount' => $opRequest->infoCash->x_total_amount,
  1784.                         'client_franquice' => ['description' => 'Efectivo'],
  1785.                         'amount' => null,
  1786.                         'iva' => null,
  1787.                         'ip_address' => $opRequest->infoCash->dirIp,
  1788.                         'airport_tax' => null,
  1789.                         'reference' => $opRequest->infoCash->x_reference,
  1790.                         'auth' => null,
  1791.                         'transaction_date' => $opRequest->infoCash->x_fechavigencia,
  1792.                         'description' => $opRequest->infoCash->x_description,
  1793.                         'reason_code' => 101,
  1794.                         'reason_description' => 'Transacción creada',
  1795.                         'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
  1796.                         'client_email' => $opRequest->infoCash->x_email,
  1797.                         'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
  1798.                         'serviceResponse' => $detailInfo,
  1799.                         'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
  1800.                     ];
  1801.                     $cash_result json_decode($session->get($transactionId.'[experience][cash_result]'));
  1802.                     $paymentResume['transaction_state'] = 3;
  1803.                     if ('' == $cash_result) {
  1804.                         $paymentResume['transaction_state'] = 2;
  1805.                     }
  1806.                 } else {
  1807.                     $bank_info $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
  1808.                     $bank_name $bank_info->getName();
  1809.                     $clientFranquice['description'] = 'PSE';
  1810.                     $paymentResume = [
  1811.                         'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
  1812.                         'id' => $orderProduct->getBooking(),
  1813.                         'id_context' => $opRequest->reference,
  1814.                         'currency' => $opRequest->currency,
  1815.                         'total_amount' => $opRequest->totalAmount,
  1816.                         'amount' => $opRequest->devolutionBase,
  1817.                         'iva' => $opRequest->taxAmount,
  1818.                         'ip_address' => $opRequest->ipAddress,
  1819.                         'bank_name' => $bank_name,
  1820.                         'client_franquice' => $clientFranquice,
  1821.                         'reference' => $opResponse->createTransactionResult->transactionID,
  1822.                         'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
  1823.                         'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
  1824.                         'description' => $opRequest->description,
  1825.                         'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
  1826.                         'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
  1827.                         'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
  1828.                         'client_email' => $opRequest->payer->emailAddress,
  1829.                         'serviceResponse' => $detailInfo,
  1830.                         'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
  1831.                     ];
  1832.                 }
  1833.             } else {
  1834.                 $customer null;
  1835.                 if ('false' == $infoDates['datesTransaction']['FormaVenta']) {
  1836.                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
  1837.                     $EmisionInfo json_decode($session->get($transactionId.'[experience][EmisionInfo'.$detailVariables->infoExperience[0]->id.']'), true);
  1838.                     $emissionData json_decode($orderProduct->getEmissionData(), true);
  1839.                     $emissionXml simplexml_load_string($emissionData['xml'])->Request;
  1840.                     $paymentResume = [
  1841.                         'transaction_state' => isset($emissionData['emission']) ? 0,
  1842.                         'transaction_state_reservation' => isset($emissionData['emission']) ? 0,
  1843.                         'id' => $orderProduct->getBooking(),
  1844.                         'id_context' => $emissionData['emission'] ?? $EmisionInfo['message'] ?? '',
  1845.                         'currency' => $detailVariables->currency,
  1846.                         'total_amount' => $detailVariables->AmountTotal,
  1847.                         'amount' => null,
  1848.                         'iva' => null,
  1849.                         'ip_address' => null,
  1850.                         'bank_name' => 'Reserva Off Line',
  1851.                         //'client_franquice' => 'Off Line',
  1852.                         'reference' => $emissionData['emission'] ?? $EmisionInfo['message'] ?? '',
  1853.                         'auth' => null,
  1854.                         'transaction_date' => $orderProduct->getCreationDate(),
  1855.                         'description' => (string) $emissionXml->Producto->ProductName,
  1856.                         'reason_code' => 101,
  1857.                         'reason_description' => $EmisionInfo['Description'] ?? '',
  1858.                         'client_names' => $emissionXml->Cliente->Name.' '.$emissionXml->Cliente->Last_name,
  1859.                         'client_email' => (string) $emissionXml->Cliente->email,
  1860.                         'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
  1861.                         'serviceResponse' => $detailInfo,
  1862.                     ];
  1863.                 }
  1864.             }
  1865.             $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  1866.         } else {
  1867.             $paymentResume = [
  1868.                 'id' => $orderProduct->getBooking(),
  1869.             ];
  1870.         }
  1871.         if (false !== strpos($paymentData->first_name'***')) {
  1872.             $facturationResume = [
  1873.                 'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  1874.                 'customer_address' => $customer->getAddress(),
  1875.                 'customer_doc_num' => $customer->getDocumentnumber(),
  1876.                 'customer_phone' => $customer->getPhone(),
  1877.                 'customer_email' => $customer->getEmail(),
  1878.             ];
  1879.         } else {
  1880.             $facturationResume = [
  1881.                 'customer_names' => $paymentData->first_name.' '.$paymentData->last_name,
  1882.                 'customer_address' => $paymentData->address ?? null,
  1883.                 'customer_doc_num' => $paymentData->doc_num,
  1884.                 'customer_phone' => $paymentData->phone,
  1885.                 'customer_email' => $paymentData->email ?? null,
  1886.             ];
  1887.         }
  1888.         if (false !== strpos($detail_data->PI->first_name_1_1'***')) {
  1889.             $detail_data->PI->first_name_1_1 $customer->getFirstname();
  1890.             $detail_data->PI->last_name_1_1 $customer->getLastname();
  1891.             $detail_data->PI->email_1_1 $customer->getEmail();
  1892.             $detail_data->PI->address_1_1 $customer->getAddress();
  1893.             $detail_data->CD->phone $customer->getPhone();
  1894.         }
  1895.         $clientFranquice '';
  1896.         $retryCount = (int) $session->get($transactionId.'[experience][retry]');
  1897.         $agencyFolder $twigFolder->twigFlux();
  1898.         $number 1;
  1899.         $detailVariables->infoExperience[0]->info->ExperienceDetail->FechaInicio $detailVariables->info->date1;
  1900.         if (isset($detailVariables->info->date1) && '' != $detailVariables->info->date2) {
  1901.             $detailVariables->infoExperience[0]->info->ExperienceDetail->FechaFin $detailVariables->info->date2;
  1902.         }
  1903.         $emailData = [
  1904.             'retry_count' => $retryCount,
  1905.             'order' => $orderInfo->order,
  1906.             'products' => $orderInfo->products,
  1907.             'description' => $infoDates['datesTransaction']['ProductName'],
  1908.             'info_travelers' => (array) $detail_data->PI,
  1909.             'contact_phone' => $detail_data->CD->phone,
  1910.             'transactionID' => $transactionId,
  1911.             'facturationResume' => $facturationResume,
  1912.             'passenger_data' => ($detailVariables->info->passangerTypes->$number->ADT $detailVariables->info->passangerTypes->$number->CHD),
  1913.             'detailInfo' => $detailVariables->infoExperience[0]->info->ExperienceDetail,
  1914.         ];
  1915.         $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/resume.html.twig');
  1916.         $renderResumeView $emailData;
  1917.         if (isset($paymentResume)) {
  1918.             $renderResumeView['infos'][0] = ['paymentResume' => $paymentResume];
  1919.         }
  1920.         $renderResumeView['infos'][0]['agencyData']['agency_nit'] = $agency->getNit();
  1921.         $renderResumeView['infos'][0]['agencyData']['agency_name'] = $agency->getName();
  1922.         $renderResumeView['infos'][0]['agencyData']['agency_phone'] = $agency->getPhone();
  1923.         $renderResumeView['infos'][0]['agencyData']['agency_email'] = $agency->getMailContact();
  1924.         $renderResumeView['infos'][0]['retry_count'] = $retryCount;
  1925.         $renderResumeView['infos'][0]['transactionID'] = $transactionId;
  1926.          // $mailAgency = $session->get('agencyDataInfo');
  1927.         // dd($session->get('agencyDataInfo'));
  1928.         $session->set($transactionId.'[experience][quote_result]'$renderResumeView);
  1929.         if ($session->has($transactionId.'[experience][quote_result]')) {
  1930.             
  1931.             $ruta $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/resume_content.html.twig');
  1932.             $namefilepdf 'Aviatur_cotizacion_experiencias_'.$transactionId.'.pdf';
  1933.             $quoteFile $projectDir.'/app/quotationLogs/experienceQuotation/'.$namefilepdf;
  1934.             if (!file_exists($quoteFile)) {
  1935.                 $pdf->setOption('page-size''Legal');
  1936.                 $pdf->setOption('margin-top'0);
  1937.                 $pdf->setOption('margin-right'0);
  1938.                 $pdf->setOption('margin-bottom'0);
  1939.                 $pdf->setOption('margin-left'0);
  1940.                 $pdf->setOption('orientation''portrait');
  1941.                 $pdf->setOption('enable-javascript'true);
  1942.                 $pdf->setOption('no-stop-slow-scripts'true);
  1943.                 $pdf->setOption('no-background'false);
  1944.                 $pdf->setOption('lowquality'false);
  1945.                 $pdf->setOption('encoding''utf-8');
  1946.                 $pdf->setOption('images'true);
  1947.                 $pdf->setOption('dpi'300);
  1948.                 $pdf->setOption('enable-external-links'true);
  1949.                 $pdf->setOption('enable-internal-links'true);
  1950.                 $pdf->generateFromHtml($this->renderView($ruta$renderResumeView), $quoteFile);
  1951.                 $renderResumeView['NameArchive'] = 'QN'.$paymentResume['id'].'_'.$transactionId.'.pdf';
  1952.             }
  1953.             $paymentResume['exportPDF'] = false;
  1954.             if (!$session->has($transactionId.'[emission_quote_email]')) {
  1955.                 $setTo = [$paymentResume['client_email']];
  1956.                 $message = (new \Swift_Message())
  1957.                         ->setContentType('text/html')
  1958.                         ->setFrom($session->get('emailNoReply'))
  1959.                         ->setTo($setTo)
  1960.                         ->setBcc(array('soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co'$agency->getMailContact()))
  1961.                         ->setSubject($session->get('agencyShortName').' - Cotización Experiencias '.$paymentResume['id'])
  1962.                         ->attach(\Swift_Attachment::fromPath($quoteFile))
  1963.                         ->setBody(
  1964.                             $this->renderView($twigFolder->twigExists($ruta), $renderResumeView)
  1965.                         );
  1966.                 try {
  1967.                     $mailer->send($message);
  1968.                     $session->set($transactionId.'[emission_quote_email]''emailed');
  1969.                 } catch (Exception $ex) {
  1970.                     $exceptionLog->log(var_dump($message), $ex);
  1971.                 }
  1972.             }
  1973.         }
  1974.         $orderProductResume $this->render($urlResume$renderResumeView);
  1975.         if (empty($orderProduct->getResume())) {
  1976.             try {
  1977.                 $orderProduct->setResume($orderProductResume);
  1978.                 $em->persist($orderProduct);
  1979.                 $em->flush();
  1980.             } catch(\Exception $e) {
  1981.                 // Implement try/catch to control exception when persist entity.
  1982.                 // the alternatyve flow is not defined yet.
  1983.             }
  1984.         }
  1985.         chmod($projectDir.'/app/quotationLogs/experienceQuotation/'777);
  1986.         $carpeta $parameterBag->get('kernel.project_dir') .'/app/quotationLogs/experienceQuotation/';        
  1987.         if (!chmod($carpeta0755)) {   
  1988.             // Manejo de errores si chmod falla
  1989.            var_dump('No se pudieron establecer los permisos correctamente.'500);
  1990.         }
  1991.         return $orderProductResume;
  1992.     }
  1993.     public function rateExperience($profilesServices$passengerTypes)
  1994.     {
  1995.         $totalPassengers $passengerTypes['ADT'] + $passengerTypes['CHD'];
  1996.         $pricesResult = [];
  1997.         $pricesCombinedResult = [];
  1998.         $PricesQualifier = [];
  1999.         $count 0;
  2000.         $rateCHD false;
  2001.         foreach ($profilesServices as $prices) {
  2002.             foreach ($prices->Prices as $price) {
  2003.                 if (isset($price->Price['PriceQualifier']) && isset($price->Price['PriceBasis']) && isset($passengerTypes[(string) $price->Price['PriceQualifier']]) && in_array((string) $price->Price['PriceQualifier'], $passengerTypes)) {
  2004.                     if ('CHD' == (string) $price->Price['PriceQualifier']) {
  2005.                         $rateCHD true;
  2006.                     }
  2007.                     $pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Count'] = (string) $price->Price['Count'];
  2008.                     $pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Description'] = (string) $prices['Description'];
  2009.                     $pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Amount'] = (int) $price->Price['Amount'] * $passengerTypes[(string) $price->Price['PriceQualifier']];
  2010.                     $pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Code'] = (string) $price->Price['Count'];
  2011.                 } elseif (isset($price->Price['PriceQualifier'])) {
  2012.                     if ('CHD' == (string) $price->Price['PriceQualifier']) {
  2013.                         $rateCHD true;
  2014.                     }
  2015.                     if ('ADT' == (string) $price->Price['PriceQualifier'] && $passengerTypes['ADT'] > || 'CHD' == (string) $price->Price['PriceQualifier'] && $passengerTypes['CHD'] > 0) {
  2016.                         $PricesQualifier[$count][(string) $price->Price['PriceQualifier']]['Count'] = (string) $price->Price['Count'];
  2017.                         $PricesQualifier[$count][(string) $price->Price['PriceQualifier']]['Description'] = (string) $prices['Description'];
  2018.                         $PricesQualifier[$count][(string) $price->Price['PriceQualifier']]['Amount'] = (int) $price->Price['Amount'] * $passengerTypes[(string) $price->Price['PriceQualifier']];
  2019.                     }
  2020.                 } else {
  2021.                     $rateCHD true;
  2022.                     $pricesResult['optionsList'][$count]['Count'] = (string) $price->Price['Count'];
  2023.                     $pricesResult['optionsList'][$count]['Description'] = (string) $prices['Description'];
  2024.                     $pricesResult['optionsList'][$count]['Amount'] = (int) $price->Price['Amount'] * $totalPassengers;
  2025.                     $pricesResult['optionsList'][$count]['Code'] = (string) $price->Price['Count'].'@||'.(int) $price->Price['Amount'] * $totalPassengers;
  2026.                 }
  2027.             }
  2028.             ++$count;
  2029.         }
  2030.         if (!empty($PricesQualifier)) {
  2031.             $pricesResult = [];
  2032.             $Count null;
  2033.             $Description null;
  2034.             $Amount null;
  2035.             foreach ($PricesQualifier as $key => $PriceQualifier) {
  2036.                 foreach ($PriceQualifier as $keyQualifier => $Qualifier) {
  2037.                     foreach ($Qualifier as $index => $valueQualifier) {
  2038.                         if ('Count' == $index) {
  2039.                             $Count $Count.'+'.$valueQualifier;
  2040.                         }
  2041.                         if ('Description' == $index) {
  2042.                             $Description $Description.'+'.$valueQualifier;
  2043.                         }
  2044.                         if ('Amount' == $index) {
  2045.                             $Amount $valueQualifier $Amount;
  2046.                         }
  2047.                     }
  2048.                 }
  2049.             }
  2050.             $pricesResult['optionsList'][0]['Count'] = substr($Count1);
  2051.             $pricesResult['optionsList'][0]['Description'] = substr($Description1);
  2052.             $pricesResult['optionsList'][0]['Amount'] = $Amount;
  2053.             $pricesResult['optionsList'][0]['Code'] = substr($Count1).'@||'.$Amount;
  2054.         }
  2055.         if (!empty($pricesCombinedResult)) {
  2056.             $count 0;
  2057.             foreach ($pricesCombinedResult as $key => $priceCombined) {
  2058.                 $Count null;
  2059.                 $Description null;
  2060.                 $Amount 0;
  2061.                 foreach ($priceCombined as $keyPrice => $price) {
  2062.                     $Count $Count.'+'.$price['Count'];
  2063.                     $Description $Description.'+'.$price['Description'];
  2064.                     $Amount += $price['Amount'];
  2065.                 }
  2066.                 $pricesResult['optionsList'][$count]['Count'] = substr($Count1);
  2067.                 $pricesResult['optionsList'][$count]['Description'] = substr($Description1);
  2068.                 $pricesResult['optionsList'][$count]['Amount'] = $Amount;
  2069.                 $pricesResult['optionsList'][$count]['Code'] = substr($Count1).'@||'.$Amount;
  2070.                 ++$count;
  2071.             }
  2072.         }
  2073.         if (!isset($pricesResult['optionsList'])) {
  2074.             $pricesResult['error'] = 'Ocurrio un problema al tarificar, por favor intente de nuevo.';
  2075.         } else {
  2076.             foreach ($pricesResult['optionsList'] as $key => $list) {
  2077.                 $pricesResult['Amount'][] = $list['Amount'];
  2078.             }
  2079.             if ($passengerTypes['CHD'] > && false === $rateCHD) {
  2080.                 $pricesResult['error'] = 'El Producto no permite niños o la cantidad es inferior a la permitida';
  2081.             }
  2082.         }
  2083.         return $pricesResult;
  2084.     }
  2085.     public function generateReturn($fare$legend null$info null)
  2086.     {
  2087.         return [
  2088.             'fare' => [
  2089.                 'total' => $fare[0], //total amount of Extra
  2090.                 'base' => $fare[1], //base amount less tax
  2091.                 'tax' => $fare[2], // tax amount applied to total
  2092.                 'percentage' => $fare[3], //percentage rate for tax calculation
  2093.                 'amount_insurance' => $fare[4] ?? null,
  2094.             ],
  2095.             'info' => $info// mixed object returned to twig to be used at will
  2096.             'legend' => $legend// Is the text rendered under price tag in each Extra row
  2097.             'name' => 'EXPERIENCE',
  2098.             'id' => $info['ExperienceDetail']['ID'],
  2099.         ];
  2100.     }
  2101.     public function normaliza($text)
  2102.     {
  2103.         $text htmlentities($textENT_QUOTES'UTF-8');
  2104.         $text mb_strtolower($text);
  2105.         $patron = [
  2106.             // Espacios, puntos y comas por guion
  2107.             //'/[\., ]+/' => ' ',
  2108.             // Vocales
  2109.             '/\+/' => '',
  2110.             '/&agrave;/' => 'a',
  2111.             '/&egrave;/' => 'e',
  2112.             '/&igrave;/' => 'i',
  2113.             '/&ograve;/' => 'o',
  2114.             '/&ugrave;/' => 'u',
  2115.             '/&aacute;/' => 'a',
  2116.             '/&eacute;/' => 'e',
  2117.             '/&iacute;/' => 'i',
  2118.             '/&oacute;/' => 'o',
  2119.             '/&uacute;/' => 'u',
  2120.             '/&acirc;/' => 'a',
  2121.             '/&ecirc;/' => 'e',
  2122.             '/&icirc;/' => 'i',
  2123.             '/&ocirc;/' => 'o',
  2124.             '/&ucirc;/' => 'u',
  2125.             '/&atilde;/' => 'a',
  2126.             '/&etilde;/' => 'e',
  2127.             '/&itilde;/' => 'i',
  2128.             '/&otilde;/' => 'o',
  2129.             '/&utilde;/' => 'u',
  2130.             '/&auml;/' => 'a',
  2131.             '/&euml;/' => 'e',
  2132.             '/&iuml;/' => 'i',
  2133.             '/&ouml;/' => 'o',
  2134.             '/&uuml;/' => 'u',
  2135.             '/&auml;/' => 'a',
  2136.             '/&euml;/' => 'e',
  2137.             '/&iuml;/' => 'i',
  2138.             '/&ouml;/' => 'o',
  2139.             '/&uuml;/' => 'u',
  2140.             // Otras letras y caracteres especiales
  2141.             '/&aring;/' => 'a',
  2142.             '/&ntilde;/' => 'n',
  2143.                 // Agregar aqui mas caracteres si es necesario
  2144.         ];
  2145.         $text preg_replace(array_keys($patron), array_values($patron), $text);
  2146.         return $text;
  2147.     }
  2148.     protected function authenticateUser(UserInterface $userLoginManagerInterface $loginManager)
  2149.     {
  2150.         try {
  2151.             $loginManager->loginUser(
  2152.                 'main',
  2153.                 $user
  2154.             );
  2155.         } catch (AccountStatusException $ex) {
  2156.             // We simply do not authenticate users which do not pass the user
  2157.             // checker (not enabled, expired, etc.).
  2158.         }
  2159.     }
  2160.     /**
  2161.      * removeStylesFromCautions()
  2162.      * Removes the styles from the caution information.
  2163.      * Author: Ing. David Rincon
  2164.      * Email: david.rincon@aviatur.com
  2165.      * Date: 2025/05/13
  2166.      * @param &$infoExperience (By reference).
  2167.      * @return The same $infoExperience with the styles removed.
  2168.      */
  2169.     function removeStylesFromCautions(&$infoExperience){
  2170.         $infoCautions $infoExperience['info']['ExperienceDetail']['cautions'];
  2171.         foreach ($infoCautions as $indexCaution => $caution) {
  2172.             /* Se debe validar desde la primera coincidencia a la última, para identificar si hallamos las coincidencias completas de style="", width="", y height="" */
  2173.             while(false !== strpos($caution->Info'style="')) {
  2174.                 $caution->Info preg_replace('/style="[^"]*"/'''$caution->Info);
  2175.             }
  2176.             while(false !== strpos($caution->Info'width="')) {
  2177.                 $caution->Info preg_replace('/width="[^"]*"/'''$caution->Info);
  2178.             }
  2179.             while(false !== strpos($caution->Info'height="')) {
  2180.                 $caution->Info preg_replace('/height="[^"]*"/'''$caution->Info);
  2181.             }
  2182.             $infoCautions[$indexCaution] = $caution;
  2183.         }
  2184.         /* Se asigna al final los cautions corregidos sin estilos */
  2185.         $infoExperience['info']['ExperienceDetail']['cautions'] = $infoCautions;
  2186.     }
  2187. }