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

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