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

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