src/Aviatur/PackageBundle/Controller/DefaultController.php line 113

Open in your IDE?
  1. <?php
  2. namespace Aviatur\PackageBundle\Controller;
  3. use Aviatur\AgentBundle\Entity\AgentTransaction;
  4. use Aviatur\CustomerBundle\Models\CustomerModel;
  5. use Aviatur\DocumentationBundle\Models;
  6. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  7. use Aviatur\PackageBundle\Models\PackageModel;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  10. use Symfony\Component\HttpFoundation\Cookie;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Doctrine\Persistence\ManagerRegistry;
  15. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  16. use Symfony\Component\Routing\RouterInterface;
  17. use Aviatur\TwigBundle\Services\TwigFolder;
  18. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  19. use Aviatur\GeneralBundle\Services\ExceptionLog;
  20. use Aviatur\GeneralBundle\Services\AviaturWebService;
  21. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  22. use Aviatur\PackageBundle\Services\SearchPackageCookie;
  23. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  24. use Aviatur\GeneralBundle\Services\AviaturLoginService;
  25. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  26. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  27. use Aviatur\GeneralBundle\Controller\OrderController;
  28. use Aviatur\PaymentBundle\Controller\SafetypayController;
  29. use Aviatur\PaymentBundle\Controller\P2PController;
  30. use Aviatur\PaymentBundle\Controller\PSEController;
  31. use Aviatur\PaymentBundle\Services\TokenizerService;
  32. use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
  33. use Aviatur\GeneralBundle\Services\AviaturMailer;
  34. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  35. use Knp\Snappy\Pdf;
  36. use Aviatur\CustomerBundle\Services\PhoneNumberService;
  37. use Aviatur\GeneralBundle\Service\MaintenanceTimeValidator;
  38. class DefaultController extends AbstractController
  39. {
  40.     /**
  41.      * @var \Doctrine\Persistence\ObjectManager
  42.      */
  43.     protected $managerRegistry;
  44.     /**
  45.      * @var SessionInterface
  46.      */
  47.     protected $session;
  48.     protected $agency;
  49.     private MaintenanceTimeValidator $maintenanceTimeValidator;
  50.     public function __construct(ManagerRegistry $registrySessionInterface $sessionMaintenanceTimeValidator $maintenanceTimeValidator)
  51.     {
  52.         $this->managerRegistry $registry->getManager();
  53.         $this->session $session;
  54.         $this->maintenanceTimeValidator $maintenanceTimeValidator;
  55.         $this->agency $this->managerRegistry->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  56.     }
  57.     public function searchAction()
  58.     {
  59.         return $this->redirect(
  60.             $this->generateUrl(
  61.                 'aviatur_search_package',
  62.                 []
  63.             )
  64.         );
  65.     }
  66.     public function availabilitySeoAction(Request $requestRouterInterface $router$url)
  67.     {
  68.         $em $this->managerRegistry;
  69.         $session $this->session;
  70.         $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findOneByUrl('paquetes/' $url);
  71.         if (null != $seoUrl) {
  72.             $maskedUrl $seoUrl->getMaskedurl();
  73.             $session->set('maxResults'$request->query->get('maxResults'));
  74.             if (false !== strpos($maskedUrl'?')) {
  75.                 $parameters explode('&'substr($maskedUrlstrpos($maskedUrl'?') + 1));
  76.                 foreach ($parameters as $parameter) {
  77.                     $sessionInfo explode('='$parameter);
  78.                     if (== sizeof($sessionInfo)) {
  79.                         $session->set($sessionInfo[0], $sessionInfo[1]);
  80.                     }
  81.                 }
  82.                 $maskedUrl substr($maskedUrl0strpos($maskedUrl'?'));
  83.             }
  84.             if (null != $seoUrl) {
  85.                 $route $router->match($maskedUrl);
  86.                 $route['_route_params'] = [];
  87.                 foreach ($route as $param => $val) {
  88.                     // set route params without defaults
  89.                     if ('_' !== \substr($param01)) {
  90.                         $route['_route_params'][$param] = $val;
  91.                     }
  92.                 }
  93.                 return $this->forward($route['_controller'], $route);
  94.             } else {
  95.                 throw $this->createNotFoundException('La página que solicito no existe o se ha movido permanentemente');
  96.             }
  97.         } else {
  98.             throw $this->createNotFoundException('La página que solicito no existe o se ha movido permanentemente');
  99.         }
  100.     }
  101.     public function availabilityAction(Request $requestSearchPackageCookie $searchPackageCookieAuthorizationCheckerInterface $authorizationCheckerAviaturWebService $aviaturWebServiceExceptionLog $exceptionLogAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBagTwigFolder $twigFolder$package$description)
  102.     {
  103.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  104.         $channel = [];
  105.         $Chanels null;
  106.         $xmlTemplate = [];
  107.         $providers = [];
  108.         $domain null;
  109.         $urlDescription = [];
  110.         $em $this->managerRegistry;
  111.         $fullRequest $request;
  112.         $session $this->session;
  113.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
  114.         $agency $this->agency;
  115.         
  116.         $isFront $session->has('operatorId');
  117.         $redirectResponse $this->maintenanceTimeValidator->validateMaintenanceTime('avail');
  118.         if ($redirectResponse !== null && !$isFront) {
  119.             return $redirectResponse;
  120.         }
  121.         $configPackageAgency $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
  122.         $valueReservation $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_package');
  123.         $agencyFolder $twigFolder->twigFlux();
  124.         $packageModel = new PackageModel();
  125.         if (!$configPackageAgency || !isset($configPackageAgency[0])) {
  126.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes''Resultados de búsqueda''No podemos realizar la consulta ya que, no existe un proveedor configurado para este servicio'));
  127.         }
  128.         $channel['channel'] = $configPackageAgency[0]->getChannel();
  129.         $OfficeId explode('-'$configPackageAgency[0]->getOfficeid());
  130.         $channel['officeId'] = $OfficeId[1];
  131.         $date date('Y-m-d');
  132.         if ('especializado' === $package && 'Turismo-vacaciones' === $description) {
  133.             $package 'personalizada';
  134.             $description 'vacaciones';
  135.         }
  136.         $newDescription explode('/'$description);
  137.         $descriptions = [$newDescription];
  138.         $count count($newDescription);
  139.         switch ($channel['channel']) {
  140.             case 1:
  141.                 // canal de venta Aviatur.com (público)
  142.                 $Chanels '<Channels>
  143.                         <Channel>
  144.                             <Id>'.$channel['channel'].'</Id>
  145.                             <OfficeId/>
  146.                         </Channel>
  147.                     </Channels>';
  148.                 break;
  149.             case 2:
  150.                 // canal de venta página web agencia de la organización (privado)
  151.                 $Chanels '<Channels>
  152.                     <Channel>
  153.                         <Id>3</Id>
  154.                         <OfficeId>'.$channel['officeId'].'</OfficeId>
  155.                     </Channel>
  156.                 </Channels>';
  157.                 break;
  158.             case 3:
  159.                 // canal de venta página web agencia de la organización (privado mas público)
  160.                 $Chanels '<Channels>
  161.                     <Channel>
  162.                         <Id>1</Id>
  163.                         <OfficeId/>
  164.                     </Channel>
  165.                     <Channel>
  166.                         <Id>3</Id>
  167.                         <OfficeId>'.$channel['officeId'].'</OfficeId>
  168.                     </Channel>
  169.                 </Channels>';
  170.                 break;
  171.             case 4:
  172.                 // canal de venta Marcas Blancas (público)
  173.                 $Chanels '<Channels>
  174.                         <Channel>
  175.                             <Id>4</Id>
  176.                             <OfficeId/>
  177.                         </Channel>
  178.                     </Channels>';
  179.                 break;
  180.             case 6:
  181.                 // canal de venta Marcas Blancas (público)
  182.                 $Chanels '<Channels>
  183.                         <Channel>
  184.                             <Id>6</Id>
  185.                             <OfficeId/>
  186.                         </Channel>
  187.                     </Channels>';
  188.                 break;
  189.         }
  190.         if ('especializado' == $package) {
  191.             $xmlTemplate $packageModel->getAvailabilityFavorite($Chanels);
  192.         } elseif ('personalizada' == $package) {
  193.             $descriptions[0] = str_replace('-'' '$descriptions[0]);
  194.             $xmlTemplate $packageModel->getXmlAvailability($count$descriptions[0], $Chanels);
  195.         }
  196.         $xmlRequest $xmlTemplate[0];
  197.         if ($fullRequest->isXmlHttpRequest()) {
  198.             if ($configPackageAgency) {
  199.                 $providers[] = $configPackageAgency[0]->getProvider()->getProvideridentifier();
  200.             } else {
  201.                 $exceptionLog->log('Error Fatal''No se encontró la agencia segun el dominio: '.$domainnullfalse);
  202.                 return new Response('No se encontraron agencias para consultar disponibilidad.');
  203.             }
  204.             $provider implode(';'$providers);
  205.             $description str_replace('-'' '$description);
  206.             $variable = [
  207.                 'ProviderId' => $provider,
  208.                 'package' => $package,
  209.                 'description' => $description,
  210.                 'date' => $date,
  211.             ];
  212.             $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  213.             if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  214.                 $aviaturErrorHandler->errorRedirect('''Error MPA''No se creo Login!');
  215.                 return new Response('Estamos experimentando dificultades técnicas en este momento.');
  216.             }
  217.             $transactionId = (string) $transactionIdResponse;
  218.             $variable['transactionId'] = $transactionId;
  219.             $session->set($transactionIdSessionName$transactionId);
  220.             $session->set($transactionId.'[availability_url]'$requestUrl);
  221.             $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse$variable['transactionId']);
  222.             if (isset($response['error'])) {
  223.                 $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgAvail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variabletrue);
  224.                 //$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgAvail__RS.xml')));
  225.                 if (isset($response['error'])) {
  226.                     if ('No se encontró información para la búsqueda seleccionada.' != $response['error']) {
  227.                         $this->redirect($aviaturErrorHandler->errorRedirect($requestUrl'Error disponibilidad buscador'$response['error']));
  228.                     }
  229.                     return new Response($response['error']);
  230.                 }
  231.             } elseif (!isset($response->Message->OTA_PkgAvailRS)) {
  232.                 echo 'No hay información';
  233.                 die;
  234.                 $aviaturErrorHandler->errorRedirect($requestUrl'Error disponibilidad hoteles'$response->Message);
  235.                 return new Response('No hemos encontrado información para el destino solicitado.');
  236.             }
  237.             $searchImages = ['http://static.aviatur.com/images'];
  238.             $replaceImages = ['https://static.aviatur.com/images'];
  239.             $response simplexml_load_string(str_replace($searchImages$replaceImages$response->asXML()));
  240.             $packages null;
  241.             $ProductInfo null;
  242.             //$isAgent = false;
  243.             $nameProduct 'package';
  244.             $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  245.             $productCommission2 = (array) $productCommission;
  246.             if (($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) && (is_countable($productCommission2) ? count($productCommission2) : 0) > 0) {
  247.                 $user $this->getUser();
  248.                 $agent $user->getAgent();
  249.                 $agency $this->agency;
  250.                 if (!empty($agent)) {
  251.                     $nameProduct 'package';
  252.                     $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  253.                     $tarifaCommissionPercentage $productCommission->getTacommissionpercentage();
  254.                     $isAgent true;
  255.                 }
  256.             }
  257.             foreach ($response->Message->OTA_PkgAvailRS->Package as $packages) {
  258.                 $packages->TPA_Extensions->ProductInfo->Description htmlspecialchars_decode($packages->TPA_Extensions->ProductInfo->Description);
  259.                 $hoy date('Y-m-d');
  260.                 $fecha_actual strtotime($hoy);
  261.                 $fecha_final = isset($packages) ? strtotime($packages->TPA_Extensions->ProductInfo->VigenciaFinal) : null;
  262.                 if (isset($isAgent) && $isAgent) {
  263.                     $packages->TPA_Extensions->ProductInfo->ActiveAgent $isAgent;
  264.                     $packages->TPA_Extensions->ProductInfo->ComisionPay round((float) $packages->TPA_Extensions->ProductInfo->Comision $tarifaCommissionPercentage);
  265.                 }
  266.                 if ($fecha_actual $fecha_final) {
  267.                     switch ($valueReservation->getValue()) {
  268.                         case 0:
  269.                             if ('false' === (string) $packages->TPA_Extensions->ProductInfo->FormaVenta) {
  270.                                 //Only Products OFF LINE
  271.                                 $ProductInfo[] = $packages;
  272.                             }
  273.                             break;
  274.                         case 1:
  275.                             if ('false' === (string) $packages->TPA_Extensions->ProductInfo->FormaVenta || 'true' === (string) $packages->TPA_Extensions->ProductInfo->FormaVenta) {
  276.                                 //Products OFF LINE and Products ON LINE
  277.                                 $ProductInfo[] = $packages;
  278.                             }
  279.                             break;
  280.                     }
  281.                 }
  282.             }
  283.             $variable['TransactionIdentifier'] = (string) $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
  284.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/AjaxAvailability.html.twig');
  285.             return $this->render($urlAvailability, [
  286.                 'ProductsInfo' => $ProductInfo,
  287.                 'variable' => $variable,
  288.                 'packages'=> $packages->TPA_Extensions->ProductInfo->ComisionPay,
  289.             ]);
  290.         } else {
  291.             if ($configPackageAgency) {
  292.                 $providers[] = $configPackageAgency[0]->getProvider()->getProvideridentifier();
  293.             } else {
  294.                 $exceptionLog->log('Error Fatal''No se encontró la agencia segun el dominio: '.$domainnullfalse);
  295.                 return new Response('No se encontraron agencias para consultar disponibilidad.');
  296.             }
  297.             $provider implode(';'$providers);
  298.             $cookieArray = [
  299.                 'ProviderId' => $provider,
  300.                 'package' => $package,
  301.                 'description' => $description,
  302.                 //                'date' => $date,
  303.             ];
  304.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/availability.html.twig');
  305.             if ($agency->getDomainsecure() == $agency->getDomain()) {
  306.                 $safeUrl 'https://'.$agency->getDomain();
  307.             } else {
  308.                 $safeUrl 'https://'.$agency->getDomainsecure();
  309.             }
  310.             $cookieLastSearch $searchPackageCookie->searchPackageCookie(['package' => base64_encode(json_encode($cookieArray))]);
  311.             $availableArrayPackage $cookieArray;
  312.             if ('personalizada' == $availableArrayPackage['package']) {
  313.                 $availableArrayPackage['label'] = 'Búsqueda personalizada';
  314.             } else {
  315.                 $descriptionE trim($availableArrayPackage['description'], '-');
  316.                 $availableArrayPackage['description'] = str_replace('-'' '$descriptionE);
  317.                 $availableArrayPackage['label'] = 'Plan especializado';
  318.             }
  319.             $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  320.             $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
  321.             $urlDescription['url'] = null != $seoUrl '/'.$seoUrl[0]->getUrl() : $requestUrl;
  322.             $response $this->render($urlAvailability, [
  323.                 'ajaxUrl' => $requestUrl,
  324.                 'availableArrayPackage' => $availableArrayPackage,
  325.                 'inlineEngine' => true,
  326.                 'safeUrl' => $safeUrl,
  327.                 'cookieLastSearch' => $cookieLastSearch,
  328.                 'pointRedemption' => $pointRedemption,
  329.                 'urlDescription' => $urlDescription,
  330.                 'ispackage' => true,
  331.             ]);
  332.             $response->headers->setCookie(new Cookie('_availability_array[package]'base64_encode(json_encode($cookieArray)), (time() + 3600 24 7), '/'));
  333.             return $response;
  334.         }
  335.     }
  336.     public function detailAction(Request $requestRouterInterface $routerAuthorizationCheckerInterface $authorizationChecker,AviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBagTwigFolder $twigFolder$name$id)
  337.     {
  338.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  339.         $urlDescription = [];
  340.         $em $this->managerRegistry;
  341.         $isAgent false;
  342.         $fullRequest $request;
  343.         $domain $fullRequest->getHost();
  344.         $request $fullRequest->request;
  345.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
  346.         $session $this->session;
  347.         $agency $this->agency;
  348.         $agencyFolder $twigFolder->twigFlux();
  349.         $values explode('-'$id);
  350.         $packageCode $values[0];
  351.         $TipoProducto $values[2];
  352.         $valueReservation $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_package');
  353.         $UrlHomologation $em->getRepository(\Aviatur\GeneralBundle\Entity\urlHomologation::class)->findOneByOldUrl(trim('paquetes/detalle/'.$id.'/'.$name));
  354.         if (!empty($UrlHomologation)) {
  355.             return $this->redirect('/'.$UrlHomologation->getNewUrl());
  356.         }
  357.         if (true === $request->has('whitemarkDataInfo')) {
  358.             $session->set('whitemarkDataInfo'json_decode($request->get('whitemarkDataInfo'), true));
  359.         }
  360.         if ($request->has('correlationID')) {
  361.             $correlationId $request->get('correlationID');
  362.             $session->set($correlationIdSessionName$correlationId);
  363.         } else {
  364.             $correlationId '';
  365.         }
  366.         $configPackageAgency $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
  367.         $provider $configPackageAgency[0]->getProvider();
  368.         $variable = [
  369.             'date' => date('Y-m-d'),
  370.             'packageCode' => $packageCode,
  371.             'nights' => $values[1],
  372.             'TipoProducto' => $values[2],
  373.             'correlationId' => $correlationId,
  374.             'ProviderId' => $provider->getProviderIdentifier(),
  375.         ];
  376.         $packageModel = new PackageModel();
  377.         $xmlTemplate $packageModel->getXmlDetail();
  378.         $xmlRequest $xmlTemplate;
  379.         $transactionId $request->get('transactionID');
  380.         $aviaturWebService->setUrls(json_decode($session->get($domain'[parameters]')), $domain);
  381.         if ($request->has('transactionID')) {
  382.             $variable['transactionId'] = $request->get('transactionID');
  383.             $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgDetail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse$variable['transactionId']);
  384.             //$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
  385.         } else {
  386.             $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgDetail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variabletrue);
  387.             //$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
  388.         }
  389.         
  390.         if (empty($response) || isset($response['error'])) {
  391.             $requestUrl $this->generateUrl('aviatur_search_package', []);
  392.             $messageError $response['error'] ?? 'Ha sido redirigido al home para que pueda seguir explorando opciones.';
  393.             if ($request->has('package')) {
  394.                 $package $request->get('package') ?? 'personalizada';
  395.                 $description $request->get('description') ?? 'cartagena';
  396.                 $requestUrl $this->generateUrl('aviatur_package_availability', ['package' => $package'description' => str_replace(' ''-'$description)]);
  397.                 $messageError "Ha sido redirigido a la disponibilidad para que pueda seguir explorando opciones. Por favor, intente nuevamente o contáctenos para obtener más información.";
  398.             }
  399.             $titleError "No hemos encontrado información para el paquete solicitado.";
  400.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($requestUrl$titleError$messageError));
  401.         }
  402.         $transactionId $transactionId ?? (string) $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
  403.         $nameProduct 'package';
  404.         $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  405.         $productCommission2 = (array)$productCommission;
  406.         $session->set($transactionId '_isActiveQse', ((is_countable($productCommission2) ? count($productCommission2) : 0) > 0) ? true false);
  407.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId '_isActiveQse')) {
  408.             $user $this->getUser();
  409.             $agent $user->getAgent();
  410.             $agency $this->agency;
  411.             if (!empty($agent)) {
  412.                 $emailuser $user->getemail();
  413.                 $idagent $agent[0]->getid();
  414.                 $nombreagente $user->getFirstname().' '.$user->getLastname();
  415.                 $agencyFolder $twigFolder->twigFlux();
  416.                 $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
  417.                 $infoQse json_decode($agentCommission->getQseproduct());
  418.                 $infoQseNameProduct = empty($infoQse->$nameProduct) ? false $infoQse->$nameProduct;
  419.                 $infoQse = empty($infoQse) ? false $infoQseNameProduct;
  420.                 $productCommissionPercentage $productCommission->getQsecommissionpercentage();
  421.                 $packageCommission = ($infoQse) ? (int) $infoQse->commission_money 0;
  422.                 $packageCommissionPercentage = ($infoQse) ? (float) $infoQse->commission_percentage 0;
  423.                 $commissionActive = ($infoQse) ? (int) $infoQse->active 0;
  424.                 $isAgent true;
  425.             } else {
  426.                 $session->set($transactionId.'_isActiveQse'false);
  427.             }
  428.         }
  429.         $searchImages = ['http://static.aviatur.com/images'];
  430.         $replaceImages = ['https://static.aviatur.com/images'];
  431.         $response simplexml_load_string(str_replace($searchImages$replaceImages$response->asXML()));
  432.         if (!$session->has($transactionId.'[package_detail_url]')) {
  433.             $session->set($transactionId.'[package_detail_url]'$this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params')));
  434.         }
  435.         if ($request->has('package')) {
  436.             $package $request->get('package');
  437.             $description $request->get('description');
  438.             $requestUrl $router->generate(
  439.                 'aviatur_package_availability',
  440.                 [
  441.                     'package' => $package,
  442.                     'description' => str_replace(' ''-'$description), 
  443.                 ]
  444.             );
  445.             $session->set($transactionId.'[mpt]'$requestUrl);
  446.         }
  447.         $referer explode('/'$fullRequest->server->get('HTTP_REFERER'));
  448.         // if (isset($referer) && count($referer) > 4) {
  449.         //     $description = $referer[5];
  450.         // } else {
  451.         // }
  452.         $description '';
  453.         if (!isset($response->Message) || !isset($response->Message->OTA_PkgAvailRS) || !isset($response->Message->OTA_PkgAvailRS->Package) || empty($response->Message)) {
  454.             return $this->redirect($aviaturErrorHandler->errorRedirect($fullRequest->server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor'));
  455.         }
  456.         $infoPackage $response->Message->OTA_PkgAvailRS->Package->asXml();
  457.         $codeCity = (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->CodeCiudad;
  458.         $searchCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findCityByIata($codeCity);
  459.         if (empty($searchCity)) {
  460.             $nameCity $codeCity;
  461.         } else {
  462.             $nameCity $searchCity[0]->getDescription();
  463.         }
  464.         $session->set($transactionId.'[mpt][infoPackage]'$infoPackage);
  465.         $salidaPackage = [];
  466.         if (!isset($response)) {
  467.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure'), '''No hay información'));
  468.         } elseif (is_object($response->Message->OTA_PkgAvailRS->Package)) {
  469.             if ('true' == $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->FormaVenta) {
  470.                 $session->set($transactionId.'[mpt]'.'[FormaVenta]''true');
  471.             } else {
  472.                 $session->set($transactionId.'[mpt]'.'[FormaVenta]''false');
  473.             }
  474.             foreach ($response->Message->OTA_PkgAvailRS->Package as $information) {
  475.                 $CostName $information->TPA_Extensions->ProductInfo->UnitCostName;
  476.                 $night 'noche';
  477.                 $ocupation 'ocupaci';
  478.                 $verificationNight strrpos($CostName$night);
  479.                 $verificationOcupation strrpos($CostName$ocupation);
  480.                 if (false === $verificationNight && false === $verificationOcupation) {
  481.                     //Unidad de Costo por Estadia
  482.                     $UnitCostValue 0;
  483.                 } elseif (false !== $verificationNight && false === $verificationOcupation) {
  484.                     //Unidad de Costo por Noche
  485.                     $UnitCostValue 1;
  486.                 } else {
  487.                     //Unidad de Costo por Ocupacion
  488.                     $UnitCostValue 2;
  489.                 }
  490.                 $count 0;
  491.                 foreach ($information->Cautions as $travelerInformation) {
  492.                     foreach ($travelerInformation as $caution) {
  493.                         $info explode('</Caution>'str_replace($caution['ID'].'">''</Caution>'$caution->asXml()));
  494.                         $caution['Info'] = isset($info[1]) ? htmlspecialchars_decode($info[1]) : '';
  495.                         $infoDocumentation[$count]['ID'] = (string) $caution['ID'];
  496.                         $infoDocumentation[$count]['INFO'] = (string) $caution['Info'];
  497.                         ++$count;
  498.                     }
  499.                 }
  500.                 $session->set($transactionId.'[mpt][infoCaution]'json_encode($infoDocumentation));
  501.                 $rangeDates = [];
  502.                 foreach ($information->TPA_Extensions->ProductInfo->Salidas->Salida as $salidas) {
  503.                     $salidaPackage[] = (string) $salidas['DepartureArrivalDate'];
  504.                     $beginDateTemp = new \DateTime((string) $salidas['BeginDate']);
  505.                     $endDateTemp = new \DateTime((string) $salidas['EndDate']);
  506.                     $endDateTemp->modify('-'.((int) $information->TPA_Extensions->ProductInfo->Noches 1).' day');
  507.                     $intervalTemp = new \DateInterval('P1D');
  508.                     $periodTemp = new \DatePeriod($beginDateTemp$intervalTemp$endDateTemp);
  509.                     foreach ($periodTemp as $dateTemp) {
  510.                         if ($dateTemp->format('Y-m-d') > date('Y-m-d'strtotime(date('Y-m-d').'+ '.$information->TPA_Extensions->ProductInfo->DiasAntesReserva.' days'))) {
  511.                             $rangeDates[] = $dateTemp->format('Y-m-d');
  512.                         }
  513.                     }
  514.                 }
  515.                 $salidaPackage array_unique($salidaPackage);
  516.                 $rangeDates array_unique($rangeDates);
  517.                 if ('' != $salidaPackage[0]) {
  518.                     $salidaPackage array_intersect($rangeDates$salidaPackage);
  519.                 } else {
  520.                     $salidaPackage $rangeDates;
  521.                 }
  522.                 $DestinationCode $information->TPA_Extensions->ProductInfo->CodePais;
  523.             }
  524.         } else {
  525.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure'), '''No hay información'));
  526.         }
  527.         $cautionsTotal count($response->Message->OTA_PkgAvailRS->Package->Cautions->Caution);
  528.         if ($configPackageAgency[0]->getTourismRegister()) {
  529.             $response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[$cautionsTotal]['ID'] = 'responsability_clausule';
  530.             $searchData = ['{agency_name}''{agency_nit}''{agency_rnt}'];
  531.             $replaceData = [$agency->getName(), $agency->getNit(), $configPackageAgency[0]->getTourismRegister()];
  532.             $responsability_clausule str_replace($searchData$replaceData$em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'responsability_clausule'));
  533.             $response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[$cautionsTotal]['Info'] = $responsability_clausule;
  534.             $minor_trip str_replace($searchData$replaceData$em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'minor_trip'));
  535.             $response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[($cautionsTotal 1)]['ID'] = 'minor_trip';
  536.             $response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[($cautionsTotal 1)]['Info'] = $minor_trip;
  537.         }
  538.         $startDate = (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->VigenciaInicial;
  539.         $Accommodation $response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation;
  540.         if ('19982' === $packageCode || '19989' === $packageCode || '19983' === $packageCode) {
  541.             $session->remove('promotionalCodePackage_code');
  542.         }
  543.         $urlDetail $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/package_detail.html.twig');
  544.         $valuePromo $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('promo_banca_mpt');
  545.         $seoUrl $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
  546.         $urlDescription['url'] = null != $seoUrl '/'.$seoUrl[0]->getUrl() : $requestUrl;
  547.         $twigVariables = [
  548.             'promo' => json_decode($valuePromo->getValue(), true),
  549.             'DestinationCode' => $DestinationCode,
  550.             'CiudadDestino' => $nameCity,
  551.             'nights' => $variable['nights'],
  552.             'count' => count($Accommodation),
  553.             'date' => $startDate,
  554.             'packageCode' => $packageCode,
  555.             'TipoProducto' => $TipoProducto,
  556.             'days' => null,
  557.             'salida' => null,
  558.             'description' => strtolower($description),
  559.             'UnitCostValue' => $UnitCostValue,
  560.             'transactionId' => $transactionId,
  561.             'correlationId' => $correlationId,
  562.             'ProviderId' => $provider->getProvideridentifier(),
  563.             'urlDescription' => $urlDescription,
  564.             // 'QSE' => $infoQse->commission_money,
  565.             'FormaVentaButton' => ('true' == (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->FormaVenta && == $valueReservation->getValue()) ? false true,
  566.         ];
  567.         if ($session->has($transactionId.'[availability_url]')) {
  568.             $twigVariables['referer'] = $session->get($transactionId.'[availability_url]');
  569.         }
  570.         if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
  571.             $safeUrl 'https://'.$agency->getDomain();
  572.         } else {
  573.             $safeUrl 'https://'.$agency->getDomainsecure();
  574.         }
  575.         return $this->render($urlDetail, ['ProductsDetail' => $response->Message'salidaPackage' => $salidaPackage'variables' => $twigVariables'safeUrl' => $safeUrl]);
  576.     }
  577.     public function redirectDetailAction(Request $requestAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryTwigFolder $twigFolder$id)
  578.     {
  579.         $em $this->managerRegistry;
  580.         $fullRequest $request;
  581.         $request $fullRequest->request;
  582.         $session $this->session;
  583.         $agency $this->agency;
  584.         $agencyFolder $twigFolder->twigFlux();
  585.         $values explode('-'$id);
  586.         $packageCode $values[0];
  587.         $TipoProducto $values[2];
  588.         $configPackageAgency $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
  589.         $provider $configPackageAgency[0]->getProvider();
  590.         $variable = [
  591.             'date' => date('Y-m-d'),
  592.             'packageCode' => $packageCode,
  593.             'nights' => $values[1],
  594.             'TipoProducto' => $values[2],
  595.             'ProviderId' => $provider->getProviderIdentifier(),
  596.         ];
  597.         $packageModel = new PackageModel();
  598.         $xmlTemplate $packageModel->getXmlDetail();
  599.         $xmlRequest $xmlTemplate;
  600.         $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgDetail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variabletrue);
  601.         //$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
  602.         if (isset($response['error']) || empty($response)) {
  603.             $titleError "No hemos encontrado información para el paquete solicitado.";
  604.             $messageError $response['error'] ?? "Ha sido redirigido al home para que pueda seguir explorando opciones.";
  605.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes'$titleError$messageError));
  606.         }
  607.         $searchImages = ['http://static.aviatur.com/images'];
  608.         $replaceImages = ['https://static.aviatur.com/images'];
  609.         $response simplexml_load_string(str_replace($searchImages$replaceImages$response->asXML()));
  610.         $transactionId $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
  611.         if (!$session->has($transactionId.'[package_detail_url]')) {
  612.             $session->set($transactionId.'[package_detail_url]'$this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params')));
  613.         }
  614.         $namePackage mb_strtolower($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->ProductName'UTF-8');
  615.         $namePackage trim($namePackage);
  616.         $caracteresEspeciales = [',''  - '' - ''- '' -'' -  '' – ''– '' –''  – '' –  ''. ''.''...''!''¡''!!''¡¡''#''$''%''&''('')''*''/''á''é''í''ó''ú''ñ'' ''  '];
  617.         $caracteres = [''' '' '' '' '' '' '' '' '' '' '' '' '''''''''''''''' porciento''y''''''''''a''e''i''o''u''n''-''-'];
  618.         $namePackageURL str_replace($caracteresEspeciales$caracteres$namePackage);
  619.         return $this->redirectToRoute('aviatur_package_detail_secure', ['id' => $id'name' => $namePackageURL], 301);
  620.     }
  621.     public function cautionsAsyncAction(Request $requestAviaturWebService $aviaturWebServiceExceptionLog $exceptionLogParameterBagInterface $parameterBag$id)
  622.     {
  623.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  624.         $providers = [];
  625.         if ($request->isXmlHttpRequest()) {
  626.             $domain str_replace('www.'''$request->getHost());
  627.             $em $this->managerRegistry;
  628.             $session $this->session;
  629.             $agency $this->agency;
  630.             $configPackageAgency $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
  631.             $transactionId $session->get($transactionIdSessionName);
  632.             $correlationId $request->get('correlationId');
  633.             if ($configPackageAgency) {
  634.                 $providers[] = $configPackageAgency[0]->getProvider()->getProvideridentifier();
  635.             } else {
  636.                 $exceptionLog->log('Error Fatal''No se encontró la agencia segun el dominio: '.$domainnullfalse);
  637.                 return new Response('No se encontraron agencias para consultar disponibilidad.');
  638.             }
  639.             $provider implode(';'$providers);
  640.             $values explode('-'$id);
  641.             $OriginDate date('Y-m-d');
  642.             $variable = [
  643.                 'date' => $OriginDate,
  644.                 'packageCode' => $values[0],
  645.                 'transactionId' => $transactionId,
  646.                 'correlationId' => $correlationId,
  647.                 'ProviderId' => $provider,
  648.                 'nights' => $values[1],
  649.                 'TipoProducto' => $values[2],
  650.             ];
  651.             $packageModel = new PackageModel();
  652.             $xmlTemplate $packageModel->getXmlDetail();
  653.             $xmlRequest $xmlTemplate;
  654.             $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgDetail''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse$variable['transactionId']);
  655.             //$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
  656.             if (!isset($response->Message) || !isset($response->Message->OTA_PkgAvailRS) || !isset($response->Message->OTA_PkgAvailRS->Package) || empty($response->Message)) {
  657.                 return $this->json(['error' => 'Error en la respuesta de nuestro proveedor']);
  658.             } elseif (!isset($response) || !is_object($response->Message->OTA_PkgAvailRS->Package)) {
  659.                 return $this->json(['error' => 'No hay información']);
  660.             } else {
  661.                 $searchImages = ['http://static.aviatur.com/images'];
  662.                 $replaceImages = ['https://static.aviatur.com/images'];
  663.                 $response simplexml_load_string(str_replace($searchImages$replaceImages$response->asXML()));
  664.                 $cautions = [];
  665.                 foreach ($response->Message->OTA_PkgAvailRS->Package->Cautions->Caution as $caution) {
  666.                     if (\strlen((string) $caution)) {
  667.                         switch ((string) $caution['ID'][0]) {
  668.                                 // map cautions to an array limited to six items
  669.                             case 'ContentInclude':
  670.                                 $cautions['Included'][] = (string) $caution;
  671.                                 break;
  672.                             case 'ContentNoInclude':
  673.                                 $cautions['NotIncluded'][] = (string) $caution;
  674.                                 break;
  675.                             case 'Itinerary':
  676.                                 $cautions['Itinerary'][] = (string) $caution;
  677.                                 break;
  678.                             case 'TravelerInformation':
  679.                             case 'Observations':
  680.                                 $cautions['InfoTraveler'][] = (string) $caution;
  681.                                 break;
  682.                             case 'AditionalNotes':
  683.                                 if ($session->has('operatorId')) {
  684.                                     $cautions['InfoAgent'][] = (string) $caution;
  685.                                 }
  686.                                 break;
  687.                             case 'PaymentPolicy':
  688.                             case 'CancellationRestrictionPolicy':
  689.                                 $cautions['Policy'][] = (string) $caution;
  690.                                 break;
  691.                             case 'Conditions':
  692.                                 $cautions['Conditions'][] = (string) $caution;
  693.                                 break;
  694.                         }
  695.                     }
  696.                 }
  697.                 $count 0;
  698.                 if (isset($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasAereas->Ruta)) {
  699.                     $cautions['TitulosRutas'] = [
  700.                         'Origin' => 'Origen',
  701.                         'Destination' => 'Destino',
  702.                         'Airline' => 'Aerolinea',
  703.                         'Flight' => 'Vuelo',
  704.                         'DateFlight' => 'Fecha de Vuelo',
  705.                         'DepartureHour' => 'Hora de Salida',
  706.                         'DateFlightArrival' => 'Llegada de vuelo',
  707.                         'ArriveHour' => 'Hora de llegada',
  708.                         'Baggage' => 'Equipaje',
  709.                     ];
  710.                     foreach ($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasAereas as $rutas) {
  711.                         foreach ($rutas->Ruta as $ruta) {
  712.                             $cautions['Rutas'][0][$count]['Origin'] = isset($ruta->Origin) ? (string) $ruta->Origin : (string) '';
  713.                             $cautions['Rutas'][0][$count]['Destination'] = isset($ruta->Destination) ? (string) $ruta->Destination : (string) '';
  714.                             $cautions['Rutas'][0][$count]['Airline'] = isset($ruta->Airline) ? (string) $ruta->Airline : (string) '';
  715.                             $cautions['Rutas'][0][$count]['Flight'] = isset($ruta->Flight) ? (string) $ruta->Flight : (string) '';
  716.                             $cautions['Rutas'][0][$count]['DateFlight'] = isset($ruta->DateFlight) ? (string) $ruta->DateFlight : (string) '';
  717.                             $cautions['Rutas'][0][$count]['DepartureHour'] = isset($ruta->DepartureHour) ? (string) $ruta->DepartureHour.' '.$ruta->DepartureMinute : (string) '';
  718.                             $cautions['Rutas'][0][$count]['DateFlightArrival'] = isset($ruta->DateFlightArrival) ? (string) $ruta->DateFlightArrival : (string) '';
  719.                             $cautions['Rutas'][0][$count]['ArriveHour'] = isset($ruta->Baggage) ? (string) $ruta->ArriveHour.' '.$ruta->ArriveMinute : (string) '';
  720.                             $cautions['Rutas'][0][$count]['Baggage'] = isset($ruta->Baggage) ? (string) $ruta->Baggage : (string) '';
  721.                             ++$count;
  722.                         }
  723.                     }
  724.                 } elseif (isset($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasItinerarios->RutaItinerario)) {
  725.                     $count 0;
  726.                     $Itinerary = [];
  727.                     foreach ($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasItinerarios->RutaItinerario as $itinerarios) {
  728.                         $Itinerary['Itinerarios'][0][$count]['Dia'] = isset($itinerarios->Dia) ? (string) rtrim($itinerarios->Dia) : (string) '';
  729.                         $Itinerary['Itinerarios'][0][$count]['NombreDia'] = isset($itinerarios->NombreDia) ? rtrim((string) $itinerarios->NombreDia) : (string) '';
  730.                         $Itinerary['Itinerarios'][0][$count]['HoraInicial'] = isset($itinerarios->HoraInicial) ? rtrim((string) $itinerarios->HoraInicial) : (string) '';
  731.                         $Itinerary['Itinerarios'][0][$count]['HoraFinal'] = isset($itinerarios->HoraFinal) ? rtrim((string) $itinerarios->HoraFinal) : (string) '';
  732.                         $Itinerary['Itinerarios'][0][$count]['Observacion'] = isset($itinerarios->Observacion) ? rtrim((string) $itinerarios->Observacion) : (string) '';
  733.                         ++$count;
  734.                     }
  735.                     $cautions['Itinerary'][1] = $Itinerary;
  736.                 } else {
  737.                     $cautions['Rutas'][0][0] = (string) '';
  738.                 }
  739.                 if ($configPackageAgency[0]->getTourismRegister()) {
  740.                     $cautions['Policy'][] = (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->ResponsibilityPolicy[0];
  741.                 }
  742.                 return $this->json($cautions);
  743.             }
  744.         } else {
  745.             return new Response('Acceso Restringido');
  746.         }
  747.     }
  748.     public function ExportPdfAction(Request $requestManagerRegistry $registryPDF $pdfParameterBagInterface $parameterBag)
  749.     {
  750.         $projectDir $parameterBag->get('kernel.project_dir');
  751.         $em $this->managerRegistry;
  752.         $fullRequest $request;
  753.         $request $fullRequest->request;
  754.         $session $this->session;
  755.         $server $fullRequest->server;
  756.         $domain $fullRequest->getHost();
  757.         $packageModel = new PackageModel();
  758.         $xmlTemplate $packageModel->getResponse();
  759.         $xmlRequest $xmlTemplate;
  760.         $response simplexml_load_string($xmlRequest);
  761.         foreach ($response->Message->OTA_PkgAvailRS->Package as $information) {
  762.             foreach ($information->Cautions->Caution as $travelerInformation) {
  763.                 $infoHtml[] = $travelerInformation->asXml();
  764.             }
  765.         }
  766.         $urlResume 'AviaturPackageBundle:Default:resumePdf.html.twig';
  767.         $archive $request->get('transactionId');
  768.         $voucherFile $projectDir.'/app/serviceLogs/PackagePDF/'.$archive.'.pdf';
  769.         $pdf->generateFromHtml(
  770.             $this->renderView(
  771.                 $urlResume,
  772.                 ['Package' => $response->Message->OTA_PkgAvailRS->Package'travelerInformation' => $infoHtml]
  773.             ),
  774.             $voucherFile
  775.         );
  776.         die;
  777.     }
  778.     public function infoHotelAction(Request $requestDetailAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryTwigFolder $twigFolderAuthorizationCheckerInterface $authorizationCheckerAviaturWebService $aviaturWebService)
  779.     {
  780.         $arrayCommission = [];
  781.         $tarifaCommissionPercentage null;
  782.         $commissionActive null;
  783.         $packageCommission null;
  784.         $packageCommissionPercentage null;
  785.         $isAgent false;
  786.         $em $this->managerRegistry;
  787.         $session $this->session;
  788.         $parameterTax $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_iva');
  789.         $aviaturPaymentIva $parameterTax->getValue();
  790.         $fullRequest $requestDetail;
  791.         $request $fullRequest->request;
  792.         $agencyFolder $twigFolder->twigFlux();
  793.         $dateStart $request->get('dateStart');
  794.         $dateEnd $request->get('dateEnd');
  795.         $packageCode $request->get('packageCode');
  796.         $nights $request->get('nights');
  797.         $TipoProducto $request->get('TipoProducto');
  798.         $transactionID $request->get('transactionId');
  799.         $correlationID $request->get('correlationId');
  800.         $ProviderId $request->get('ProviderId');
  801.         $UnitCostValue $request->get('UnitCostValue');
  802.         $VigenciaFinal $request->get('VigenciaFinal');
  803.         $detailXml simplexml_load_string($session->get($transactionID.'[mpt][infoPackage]'));
  804.         if (== $UnitCostValue) {
  805.             $salida strtotime('+'.$nights.'day 'strtotime($dateStart));
  806.             $salida date('Y-m-d'$salida);
  807.             $days $nights;
  808.         } elseif (== $UnitCostValue || == $UnitCostValue) {
  809.             $salida $dateEnd;
  810.             $segundos strtotime($dateEnd) - strtotime($dateStart);
  811.             $days = (string) intval($segundos 60 60 24);
  812.         }
  813.         $maxAditionals = (int) intval((strtotime($VigenciaFinal) - strtotime($dateEnd)) / 60 60 24);
  814.         $variable = [
  815.             'dateStart' => $dateStart,
  816.             'dateEnd' => $dateEnd,
  817.             'packageCode' => $packageCode,
  818.             'transactionId' => $transactionID,
  819.             'correlationId' => $correlationID,
  820.             'nights' => $nights,
  821.             'TipoProducto' => $TipoProducto,
  822.             'ProviderId' => $ProviderId,
  823.         ];
  824.         $packageModel = new PackageModel();
  825.         //        $xmlTemplate = $packageModel->getXmlDetail();
  826.         $xmlTemplate $packageModel->getXmlFares();
  827.         $xmlRequest $xmlTemplate;
  828.         $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgFares''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse$variable['transactionId']);
  829.         //$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgFares__RS.xml')));
  830.         // $transactionId = $session->get($transactionIdSessionName);
  831.         if (isset($response->Message) && isset($response->Message->OTA_PkgAvailRS) && isset($response->Message->OTA_PkgAvailRS['TransactionIdentifier'])) {
  832.             $transactionId = (string) $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
  833.         } else {
  834.             $titleError "Su búsqueda anterior ha caducado.";
  835.             $textError "Ha sido redirigido al home para que pueda seguir explorando opciones.";
  836.             if (!$requestDetail->isXmlHttpRequest()) {
  837.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes'$titleError$textError));
  838.             }
  839.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes''''No hay información'));
  840.         }
  841.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  842.             $nameProduct 'package';
  843.             $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  844.             $user $this->getUser();
  845.             $emailuser $user->getemail();
  846.             $agent $user->getAgent();
  847.             if (!empty($agent[0])) {
  848.                 $idagent $agent[0]->getid();
  849.                 $nombreagente $user->getFirstname().' '.$user->getLastname();
  850.                 $agencyFolder $twigFolder->twigFlux();
  851.                 $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
  852.                 $infoQse json_decode($agentCommission->getQseproduct());
  853.                 $infoQseNameProduct = empty($infoQse->$nameProduct) ? false $infoQse->$nameProduct;
  854.                 $infoQse = empty($infoQse) ? false $infoQseNameProduct;
  855.                 $tarifaCommissionPercentage $productCommission->getTacommissionpercentage();
  856.                 $productCommissionPercentage $productCommission->getQsecommissionpercentage();
  857.                 $packageCommission = ($infoQse) ? (int) $infoQse->commission_money 0;
  858.                 $packageCommissionPercentage = ($infoQse) ? (float) $infoQse->commission_percentage 0;
  859.                 $commissionActive = ($infoQse) ? (int) $infoQse->active 0;
  860.                 $activeDetail $agentCommission->getActivedetail();
  861.                 $isAgent true;
  862.             }
  863.         }
  864.         $packageCodeUrl $packageCode "-" $nights "-" $TipoProducto;
  865.         $namePackage mb_strtolower($detailXml->TPA_Extensions->ProductInfo->ProductName'UTF-8');
  866.         $namePackage trim($namePackage);
  867.         $caracteresEspeciales = [',''  - '' - ''- '' -'' -  '' – ''– '' –''  – '' –  ''. ''.''...''!''¡''!!''¡¡''#''$''%''&''('')''*''/''á''é''í''ó''ú''ñ'' ''  '];
  868.         $caracteres = [''' '' '' '' '' '' '' '' '' '' '' '' '''''''''''''''' porciento''y''''''''''a''e''i''o''u''n''-''-'];
  869.         $namePackageURL str_replace($caracteresEspeciales$caracteres$namePackage);
  870.         if (!isset($response) || isset($response['error'])) {
  871.             $titleError "No hay disponibilidad para las fechas seleccionadas.";
  872.             $textError "Ha sido redirigido al detalle para que pueda seguir explorando opciones.";
  873.             if (!$requestDetail->isXmlHttpRequest()) {
  874.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure', ['id' => $packageCodeUrl'name' => $namePackageURL]), $titleError$textError));
  875.             }
  876.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure', ['id' => $packageCodeUrl'name' => $namePackageURL]), '''No hay información'));
  877.         } else {
  878.             $serviceResponse $response->Message->OTA_PkgAvailRS->Package;
  879.             $infoHotel $response->Message->asXml();
  880.             $session->set($transactionID.'[mpt]'.'[InfoHotel]'$infoHotel);
  881.             $session->set($transactionID.'[mpt]'.'[ValueOptionals]'0);
  882.             $session->set($transactionID.'[mpt]'.'[ValueSelection]'0);
  883.             $session->set($transactionID.'[mpt]'.'[PriceOptionals]'0);
  884.             $i 0;
  885.             $j 0;
  886.             $count 0;
  887.             $countFailsCondition 0;
  888.             $error 0;
  889.             $datesRoom null;
  890.             $newDates null;
  891.             $addDates null;
  892.             $caracteres = ["'"];
  893.             if (!isset($detailXml->TPA_Extensions->ProductInfo->Description)) {
  894.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  895.             }
  896.             $newDescription str_replace($caracteres''strip_tags($detailXml->TPA_Extensions->ProductInfo->Description));
  897.             $datesTransaction = [
  898.                 'UnitCostValue' => $UnitCostValue,
  899.                 'days' => $days,
  900.                 'nightsPackage' => $nights,
  901.                 'entrada' => $dateStart,
  902.                 'salida' => $dateEnd,
  903.                 'IdPackage' => (string) $response->Message->OTA_PkgAvailRS->Package['ID'],
  904.                 'ProductName' => (string) $detailXml->TPA_Extensions->ProductInfo->ProductName,
  905.                 'Description' => $newDescription,
  906.                 'CodeCiudad' => (string) $detailXml->TPA_Extensions->ProductInfo->CodeCiudad,
  907.                 'TipoProducto' => (string) $detailXml->TPA_Extensions->ProductInfo->TipoProducto,
  908.                 'CurrencyCode' => (string) $detailXml->TPA_Extensions->ProductInfo->CurrencyCode,
  909.                 'FormaVenta' => (string) $detailXml->TPA_Extensions->ProductInfo->FormaVenta,
  910.                 'UnitCostName' => (string) $detailXml->TPA_Extensions->ProductInfo->UnitCostName,
  911.                 'ClaseServicio' => (string) $detailXml->TPA_Extensions->ProductInfo->ClaseServicio,
  912.                 'Email' => (string) $detailXml->TPA_Extensions->ProductInfo->Email,
  913.             ];
  914.             /*             * ******************** Commision Por Tarifa *************************** */
  915.             $arrayCommission['isAgent'] = $isAgent;
  916.             if ($isAgent) {
  917.                 $arrayCommission['commissionFarePay'] = round((float) $detailXml->TPA_Extensions->ProductInfo->Comision $tarifaCommissionPercentage);
  918.                 $arrayCommission['commissionActive'] = $commissionActive;
  919.                 $arrayCommission['commissionAgent'] = ('0' == $commissionActive) ? $packageCommission $packageCommissionPercentage;
  920.                 $arrayCommission['commissionClaseServicio'] = $detailXml->TPA_Extensions->ProductInfo->ClaseServicio.'-'.($aviaturPaymentIva);
  921.                 $arrayCommission['commissionActiveDetail'] = $activeDetail;
  922.             }
  923.             $datesTransaction['commissionInfo'] = $arrayCommission;
  924.             $totalTransaction json_encode($datesTransaction);
  925.             $session->set($transactionID.'[mpt][totalTransaction]'$totalTransaction);
  926.             $datesRoom['datesTransaction'] = $datesTransaction;
  927.             $datesRoom['ServiciosOpcionales'] = $detailXml->TPA_Extensions->ProductInfo->CantidadServiciosOpcionales;
  928.             foreach ($detailXml->Cautions as $travelerInformation) {
  929.                 foreach ($travelerInformation as $caution) {
  930.                     $info explode('</Caution>'str_replace($caution['ID'].'">''</Caution>'$caution->asXml()));
  931.                     $caution['Info'] = isset($info[1]) ? htmlspecialchars_decode($info[1]) : '';
  932.                     $infoHtml $travelerInformation;
  933.                     $travelerInformation $infoHtml;
  934.                 }
  935.             }
  936.             foreach ($response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $Accommodation) {
  937.                 $datesRoom['HotelCode'][$i][$j] = $Accommodation->Identity['HotelCode'];
  938.                 $datesRoom['HotelName'][$i][$j] = $Accommodation->Identity['HotelName'];
  939.                 $datesRoom['BrandCode'][$i][$j] = $Accommodation->Identity['BrandCode'];
  940.                 foreach ($Accommodation->RoomProfiles->RoomProfile as $RoomProfile) {
  941.                     $datesRoom['dateValidation'][$j] = $RoomProfile['EffectiveDate'].'*'.$RoomProfile['ExpireDate'].'*'.$RoomProfile['RoomTypeCode'];
  942.                     $roomDate explode('*'$datesRoom['dateValidation'][$j]);
  943.                     $fechaIni strtotime($roomDate[0]);
  944.                     $fechaFin strtotime($roomDate[1]);
  945.                     if (strtotime($dateStart) >= $fechaIni && strtotime($salida) <= $fechaFin && (int) $RoomProfile['CotQuantity'] <= $days) {
  946.                         $Rph $RoomProfile['RPH'];
  947.                         $AmountCHD[$i][$j] = 0;
  948.                         $AmountADT[$i][$j] = 0;
  949.                         $RangeCHD[$i][$j] = 0;
  950.                         $datesRoom['ADN'][$i][$j] = 0;
  951.                         $datesRoom['ADF'][$i][$j] = 0;
  952.                         $datesRoom['ANF'][$i][$j] = 0;
  953.                         $datesRoom['ADD'][$i][$j] = 0;
  954.                         $datesRoom['AAN'][$i][$j] = 0;
  955.                         $datesRoom['AFN'][$i][$j] = 0;
  956.                         $AmountCHD[$i][$j] = 0;
  957.                         $AmountCHN[$i][$j] = 0;
  958.                         $AmountCHF[$i][$j] = 0;
  959.                         $AmountCFN[$i][$j] = 0;
  960.                         $FreeChildFlag $RoomProfile['FreeChildFlag'];
  961.                         $MinOccupancy $RoomProfile['MinOccupancy'];
  962.                         $MaxOccupancy $RoomProfile['MaxOccupancy'];
  963.                         $RoomTypeCode = (int) $RoomProfile['RoomTypeCode'];
  964.                         $RoomProfile['RoomCategory'] = str_replace('*',' '$RoomProfile['RoomCategory']);
  965.                         $datesRoom['dateRoom'][$i][$RoomTypeCode] = $RoomProfile;
  966.                         foreach ($RoomProfile->Prices->Price as $Amount) {
  967.                             /* ----- DATOS ADULTOS ------ */
  968.                             //Adulto
  969.                             if ('ADT' == $Amount['PriceQualifier']) {
  970.                                 $AmountADT[$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  971.                                 $RangeADT[$i][$j] = $Amount['RangeMinimum'].'|'.$Amount['RangeMaximum'];
  972.                                 $countWeekDaysADT $this->countDaysByWeekDays($dateStart$dateEnd$Amount['WeekDay'], $nights);
  973.                             }
  974.                             //Adulto Noche Adicional
  975.                             if ('ADN' == $Amount['PriceQualifier']) {
  976.                                 $datesRoom['ADN'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  977.                             }
  978.                             //Adulto Fin de semana
  979.                             if ('ADF' == $Amount['PriceQualifier']) {
  980.                                 $datesRoom['ADF'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  981.                                 $countFdsDaysADT $this->countDaysByWeekDays($dateStart$dateEnd$Amount['WeekDay'], $nights);
  982.                             }
  983.                             //Adulto Noche Adicional Fin de semana
  984.                             if ('ANF' == $Amount['PriceQualifier']) {
  985.                                 $datesRoom['ANF'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  986.                             }
  987.                             /* ----- DATOS ADULTOS ADICIONALES------ */
  988.                             //Persona Adicional
  989.                             if ('ADD' == $Amount['PriceQualifier']) {
  990.                                 $datesRoom['ADD'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  991.                             }
  992.                             //Noche Adicional - Persona Adicional
  993.                             if ('AAN' == $Amount['PriceQualifier']) {
  994.                                 $datesRoom['AAN'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  995.                             }
  996.                             //Noche Adicional Adulto fin de semana
  997.                             if ('AFN' == $Amount['PriceQualifier']) {
  998.                                 $datesRoom['AFN'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
  999.                             }
  1000.                             /* ----- DATOS CHILDREN ------ */
  1001.                             //Children
  1002.                             if ('CHD' == $Amount['PriceQualifier']) {
  1003.                                 $newDates $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
  1004.                                 $AmountCHD[$i][$j] = $AmountCHD[$i][$j].'|'.$newDates;
  1005.                                 $RangeCHD[$i][$j] = $Amount['RangeMinimum'].'|'.$Amount['RangeMaximum'];
  1006.                                 $countWeekDaysCHD $this->countDaysByWeekDays($dateStart$dateEnd$Amount['WeekDay'], $nights);
  1007.                             }
  1008.                             //Noche Adicional Niño
  1009.                             if ('CHN' == $Amount['PriceQualifier']) {
  1010.                                 $addDates $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
  1011.                                 $AmountCHN[$i][$j] = $AmountCHN[$i][$j].'|'.$addDates;
  1012.                             }
  1013.                             //Fin de semana Niño
  1014.                             if ('CHF' == $Amount['PriceQualifier']) {
  1015.                                 $addDates $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
  1016.                                 $AmountCHF[$i][$j] = $AmountCHF[$i][$j].'|'.$addDates;
  1017.                                 $countFdsDaysCHD $this->countDaysByWeekDays($dateStart$dateEnd$Amount['WeekDay'], $nights);
  1018.                             }
  1019.                             //Noche Adicional fin de semana Niño
  1020.                             if ('CFN' == $Amount['PriceQualifier']) {
  1021.                                 $addDates $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
  1022.                                 $AmountCFN[$i][$j] = $AmountCFN[$i][$j].'|'.$addDates;
  1023.                             }
  1024.                         }
  1025.                         $dateRoomTrans[$i][$j] = $RoomProfile['MinOccupancy'].'*'.
  1026.                                 $RoomProfile['MaxOccupancy'].'*'.
  1027.                                 $AmountADT[$i][$j].'*'.
  1028.                                 $datesRoom['ADN'][$i][$j].'*'.
  1029.                                 $datesRoom['ADF'][$i][$j].'*'.
  1030.                                 $datesRoom['ANF'][$i][$j].'*'.
  1031.                                 $datesRoom['ADD'][$i][$j].'*'.
  1032.                                 $datesRoom['AAN'][$i][$j].'*'.
  1033.                                 $datesRoom['AFN'][$i][$j].'*'.
  1034.                                 $AmountCHD[$i][$j].'*'.
  1035.                                 $AmountCHN[$i][$j].'*'.
  1036.                                 $AmountCHF[$i][$j].'*'.
  1037.                                 $AmountCFN[$i][$j].'*'.
  1038.                                 $RangeADT[$i][$j].'*'.
  1039.                                 $RangeCHD[$i][$j].'*'.
  1040.                                 $RoomTypeCode.'*'.
  1041.                             $Rph;
  1042.                         $datesRoom['dateRoomTrans'][$i][] = $dateRoomTrans[$i][$j];
  1043.                         
  1044.                         // Verifica si el precio varía según el día y si hay noches adicionales sin precio definido.
  1045.                         // En ese caso, se elimina la habitación de los resultados.
  1046.                         if( 
  1047.                             ($datesRoom['ADF'][$i][$j] !== && (
  1048.                             (isset($countWeekDaysADT) && $countWeekDaysADT["extraNights"] > && $datesRoom['ADN'][$i][$j] == ) ||
  1049.                             (isset($countFdsDaysADT) && $countFdsDaysADT["extraNights"] > && $datesRoom['ANF'][$i][$j] == 
  1050.                             )) ||
  1051.                             ($AmountCHF[$i][$j] !== && (
  1052.                             (isset($countWeekDaysCHD) && $countWeekDaysCHD["extraNights"] > && $AmountCHN[$i][$j] == ) ||
  1053.                             (isset($countFdsDaysCHD) && $countFdsDaysCHD["extraNights"] > && $AmountCFN[$i][$j] == 
  1054.                             ))
  1055.                         ){
  1056.                             unset($datesRoom['dateRoom'][$i][$RoomTypeCode]);
  1057.                             unset($datesRoom['dateRoomTrans'][$i]);
  1058.                             ++$countFailsCondition;
  1059.                             continue;
  1060.                         }
  1061.                         ++$count;
  1062.                     }
  1063.                     ++$j;
  1064.                 }
  1065.                 ++$i;
  1066.             }
  1067.             if (== $count) {
  1068.                 $error 1;
  1069.                 $titleError $countFailsCondition "Este paquete tiene fechas fijas." "No hay disponibilidad para las fechas seleccionadas.";
  1070.                 $textError $countFailsCondition "Por favor, verifique las noches incluidas en el paquete." "Puede seguir explorando otras opciones.";
  1071.                 if (!$requestDetail->isXmlHttpRequest()) {
  1072.                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure', ['id' => $packageCodeUrl'name' => $namePackageURL]), $titleError$textError));
  1073.                 }
  1074.             }
  1075.             $datesOptionals $session->get($transactionID.'[mpt]'.'[ValueOptionals]');
  1076.             $errorMessage = ($error && isset($titleError)) ? $titleError ." "$textError : ($error "No hay disponibilidad para las fechas seleccionadas" "");
  1077.             $arrayImageItems $detailXml->TPA_Extensions->ProductInfo->Multimedia->ImageItems->ImageItem;
  1078.             $packageImg $arrayImageItems[0]->Url;
  1079.             $url $session->get($transactionID.'[mpt]');
  1080.             $urlDetail $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Includes/package_infoHotel.html.twig');
  1081.             $twigVariables = [
  1082.                 'referer' => $url,
  1083.                 'nights' => $variable['nights'],
  1084.                 'count' => is_countable($response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation) ? count($response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation) : 0,
  1085.                 'dateStart' => $dateStart,
  1086.                 'dateEnd' => $dateEnd,
  1087.                 'datesRoom' => $datesRoom,
  1088.                 'packageCode' => $packageCode,
  1089.                 'packageName' => (string) $detailXml->TPA_Extensions->ProductInfo->ProductName,
  1090.                 'packageImg' => (string) $packageImg,
  1091.                 'TipoProducto' => $TipoProducto,
  1092.                 'transactionId' => $transactionID,
  1093.                 'ProviderId' => $ProviderId,
  1094.                 'error' => $error,
  1095.                 'errorMessage' => $errorMessage,
  1096.                 'datesOptionals' => $datesOptionals,
  1097.                 'maxAditionals' => ($maxAditionals 0) ? ($maxAditionals 6) ? $maxAditionals 0,
  1098.             ];
  1099.             return $this->render($urlDetail, ['totalTransaction' => $totalTransaction'response' => $serviceResponse'datesRoom' => $datesRoom'variables' => $twigVariables]);
  1100.         }
  1101.     }
  1102.     public function InfoHotelErrorAction(Request $requestAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolderRouterInterface $routerSessionInterface $sessionParameterBagInterface $parameterBag)
  1103.     {
  1104.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1105.         $server $request->server;
  1106.         if (true === $session->has($transactionIdSessionName)) {
  1107.             $transactionId $session->get($transactionIdSessionName);
  1108.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  1109.             if (true === $session->has($transactionId.'[availability_url]')) {
  1110.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1111.             } elseif (true === $session->has($transactionId.'[package_detail_url]')) {
  1112.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[package_detail_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1113.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  1114.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtelo nuevamente'));
  1115.             } else {
  1116.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1117.             }
  1118.         } else {
  1119.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1120.         }
  1121.     }
  1122.     public function OptionalsAction(Request $requestTwigFolder $twigFolderAviaturWebService $aviaturWebService)
  1123.     {
  1124.         $fullRequest $request;
  1125.         $request $fullRequest->request;
  1126.         $session $this->session;
  1127.         $agencyFolder $twigFolder->twigFlux();
  1128.         $date $request->get('date');
  1129.         $destionation $request->get('destionation');
  1130.         $TipoProducto $request->get('TipoProducto');
  1131.         $transactionID $request->get('transactionId');
  1132.         $ProviderId $request->get('ProviderId');
  1133.         $salida $request->get('salida');
  1134.         $variable = [
  1135.             'date' => $date,
  1136.             'destination' => $destionation,
  1137.             'transactionId' => $transactionID,
  1138.             'TipoProducto' => $TipoProducto,
  1139.             'ProviderId' => $ProviderId,
  1140.             'salida' => $salida,
  1141.         ];
  1142.         $packageModel = new PackageModel();
  1143.         $xmlTemplate $packageModel->getOptionals();
  1144.         $xmlRequest $xmlTemplate;
  1145.         $salidaOpcionals null;
  1146.         $count 0;
  1147.         $totalTransaction $session->get($transactionID.'[mpt][totalTransaction]');
  1148.         $ValueSelection $session->get($transactionID.'[mpt][ValueSelection]');
  1149.         $response $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT''PkgOptions''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variablefalse$variable['transactionId']);
  1150.         if (!isset($response->Message) || empty($response->Message)) {
  1151.             $response "<font color='red'>Ha ocurrido un error inesperado en la consulta de Opcionales</font>";
  1152.             $infoOptionals $response;
  1153.         } else {
  1154.             $infoOptionals $response->Message->OTA_PkgAvailRS->asXml();
  1155.         }
  1156.         $session->set($transactionID.'[mpt]'.'[infoOptionals]'$infoOptionals);
  1157.         if (isset($response->Message->OTA_PkgAvailRS->Package)) {
  1158.             $searchImages = ['http://static.aviatur.com/images'];
  1159.             $replaceImages = ['https://static.aviatur.com/images'];
  1160.             $response simplexml_load_string(str_replace($searchImages$replaceImages$response->asXML()));
  1161.             foreach ($response->Message->OTA_PkgAvailRS->Package as $information) {
  1162.                 foreach ($information->TPA_Extensions->ServiciosOpcionales->TravelerInformation as $travelerInformation) {
  1163.                     $infoHtml $travelerInformation->asXml();
  1164.                     $infoPrint $travelerInformation;
  1165.                     $travelerInformation->html $infoHtml;
  1166.                     $travelerInformation->htmlPrint $travelerInformation;
  1167.                 }
  1168.                 foreach ($information->TPA_Extensions->ServiciosOpcionales->TarifasServiciosOpc->Tarifas as $dataInfo) {
  1169.                     ++$count;
  1170.                 }
  1171.                 $BeginDate $information->DateRange['Start'];
  1172.                 $EndDate $information->DateRange['End'];
  1173.                 $salidaOpcionals date('Y/m/d'strtotime($BeginDate)).'*'.date('Y/m/d'strtotime($EndDate));
  1174.             }
  1175.         } else {
  1176.             $response "<font color='red'>Ha ocurrido un error inesperado en la consulta de Opcionales</font>";
  1177.         }
  1178.         $urlDetail $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/optionals.html.twig');
  1179.         return $this->render($urlDetail, ['totalTransaction' => $totalTransaction'countInfo' => $count'salidaOpcionals' => $salidaOpcionals'ProductsDetail' => $response'variables' => ['ValueSelection' => $ValueSelection'date' => $date'destionation' => $destionation'TipoProducto' => $TipoProducto'transactionId' => $transactionID'ProviderId' => $ProviderId]]);
  1180.     }
  1181.     public function OptionalsErrorAction(Request $requestAviaturErrorHandler $aviaturErrorHandlerTwigFolder $twigFolderSessionInterface $sessionRouterInterface $routerParameterBagInterface $parameterBag)
  1182.     {
  1183.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1184.         $server $request->server;
  1185.         if (true === $session->has($transactionIdSessionName)) {
  1186.             $transactionId $session->get($transactionIdSessionName);
  1187.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  1188.             if (true === $session->has($transactionId.'[availability_url]')) {
  1189.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1190.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  1191.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtelo nuevamente'));
  1192.             } else {
  1193.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1194.             }
  1195.         } else {
  1196.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1197.         }
  1198.     }
  1199.     public function AditionalPriceAction(Request $fullRequest)
  1200.     {
  1201.         $Amount null;
  1202.         $request $fullRequest->request;
  1203.         $session $this->session;
  1204.         $infoTransaction $request->get('infoTransaction');
  1205.         $transactionID $request->get('transactionId');
  1206.         if ('optionals' == $infoTransaction) {
  1207.             $TotalvalueOptionals $request->get('Totalvalue');
  1208.             $totalValuesOptionals $request->get('totalValues');
  1209.             if ('0' == $TotalvalueOptionals || '' == $TotalvalueOptionals) {
  1210.                 $session->set($transactionID.'[mpt]'.'[ValueOptionals]''');
  1211.                 $session->set($transactionID.'[mpt]'.'[PriceOptionals]''');
  1212.                 $Amount $request->get('Amount');
  1213.             } else {
  1214.                 $session->set($transactionID.'[mpt]'.'[ValueOptionals]'$totalValuesOptionals);
  1215.                 $session->set($transactionID.'[mpt]'.'[PriceOptionals]'$TotalvalueOptionals);
  1216.                 $Amount $request->get('Amount');
  1217.             }
  1218.         } elseif ('transaction' == $infoTransaction) {
  1219.             $Amount $request->get('Amount');
  1220.             $session->set($transactionID.'[mpt]'.'[ValueSelection]'$Amount);
  1221.         }
  1222.         return new Response($Amount);
  1223.     }
  1224.     public function AditionalsPriceErrorAction(Request $requestRouterInterface $routerAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionTwigFolder $twigFolderParameterBagInterface $parameterBag)
  1225.     {
  1226.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1227.         $server $request->server;
  1228.         if (true === $session->has($transactionIdSessionName)) {
  1229.             $transactionId $session->get($transactionIdSessionName);
  1230.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  1231.             if (true === $session->has($transactionId.'[availability_url]')) {
  1232.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1233.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  1234.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtelo nuevamente'));
  1235.             } else {
  1236.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1237.             }
  1238.         } else {
  1239.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1240.         }
  1241.     }
  1242.     public function documentationAction(Request $fullRequestAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionTwigFolder $twigFolder)
  1243.     {
  1244.         $request $fullRequest->request;
  1245.         $codeCountry $request->get('codeCountry');
  1246.         $documentationModel = new Models\DocumentationModel();
  1247.         $xmlTemplate $documentationModel->getXml($codeCountry);
  1248.         $agencyFolder $twigFolder->twigFlux();
  1249.         $response $aviaturWebService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  1250.         if (isset($response->RESULTADO)) {
  1251.             $response 'No se encuentra Información del país seleccionado';
  1252.         }
  1253.         $urlDetail $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/package_Documentation.html.twig');
  1254.         return $this->render($urlDetail, ['response' => $response]);
  1255.     }
  1256.     public function documentationErrorAction(Request $requestTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerSessionInterface $sessionParameterBagInterface $parameterBag)
  1257.     {
  1258.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1259.         $server $request->server;
  1260.         if (true === $session->has($transactionIdSessionName)) {
  1261.             $transactionId $session->get($transactionIdSessionName);
  1262.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  1263.             if (true === $session->has($transactionId.'[availability_url]')) {
  1264.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1265.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  1266.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtelo nuevamente'));
  1267.             } else {
  1268.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1269.             }
  1270.         } else {
  1271.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1272.         }
  1273.     }
  1274.     public function formreservaAction(AviaturWebService $aviaturWebServiceAviaturLogSave $aviaturLogSaveCustomerMethodPaymentService $customerMethodPaymentServiceRequest $requestAviaturLoginService $aviaturLoginServiceTokenStorageInterface $tokenStorageAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderManagerRegistry $registryParameterBagInterface $parameterBagAviaturErrorHandler $aviaturErrorHandler)
  1275.     {
  1276.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1277.         $transactionId null;
  1278.         $room = [];
  1279.         $AddPerson = [];
  1280.         $AditionalRoom = [];
  1281.         $personTotal = [];
  1282.         $codigoHotel = [];
  1283.         $codigoRoom = [];
  1284.         $codigoBrand = [];
  1285.         $typeRoom = [];
  1286.         $categoryRoom = [];
  1287.         $codeBooking = [];
  1288.         $adtCant = [];
  1289.         $chdCant = [];
  1290.         $aditionalPerson = [];
  1291.         $totalTarifas = [];
  1292.         $tarifaReal = [];
  1293.         $TotalValor = [];
  1294.         $tarifaCommissionPercentage null;
  1295.         $commissionActive null;
  1296.         $packageCommissionPercentage null;
  1297.         $productCommissionPercentage null;
  1298.         $exchangeValues null;
  1299.         $typePerson = [];
  1300.         $detail_data_package null;
  1301.         $isAgent false;
  1302.         $em $this->managerRegistry;
  1303.         $parameterTax $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_iva');
  1304.         $aviaturPaymentIva $parameterTax->getValue();
  1305.         $fullRequest $request;
  1306.         $session $this->session;
  1307.         $productInfo = new PackageModel();
  1308.         $agency $this->agency;
  1309.         $request $fullRequest->request;
  1310.         $phoneService = new PhoneNumberService($em);
  1311.         $phonePrefixes $phoneService->getActivePrefixes();
  1312.         $domain $fullRequest->getHost();
  1313.         $routeName $fullRequest->get('_route');
  1314.         $agencyFolder $twigFolder->twigFlux();
  1315.         $typeGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  1316.         $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1317.         $documentPassengerType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAllActiveConfigured();
  1318.         $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions');
  1319.         if (true === $request->has('transactionId')) {
  1320.             $transactionId $request->get('transactionId');
  1321.             $session->set($transactionIdSessionName$transactionId);
  1322.             $session->set($transactionId.'[mpt]'.'[request]'$request);
  1323.         } elseif (true === $session->has($transactionIdSessionName)) {
  1324.             $transactionId $session->get($transactionIdSessionName);
  1325.             $request $session->get($transactionId.'[mpt]'.'[request]');
  1326.         }
  1327.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  1328.             $nameProduct 'package';
  1329.             $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  1330.             $user $this->getUser();
  1331.             $emailuser $user->getemail();
  1332.             $agent $user->getAgent();
  1333.             if (!empty($agent[0])) {
  1334.                 $idagent $agent[0]->getid();
  1335.                 $nombreagente $user->getFirstname().' '.$user->getLastname();
  1336.                 $agencyFolder $twigFolder->twigFlux();
  1337.                 $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
  1338.                 $infoQse json_decode($agentCommission->getQseproduct());
  1339.                 $infoQseNameProduct = empty($infoQse->$nameProduct) ? false $infoQse->$nameProduct;
  1340.                 $infoQse = empty($infoQse) ? false $infoQseNameProduct;
  1341.                 $tarifaCommissionPercentage $productCommission->getTacommissionpercentage();
  1342.                 $productCommissionPercentage $productCommission->getQsecommissionpercentage();
  1343.                 $packageCommission = ($infoQse) ? (int) $infoQse->commission_money 0;
  1344.                 $packageCommissionPercentage = ($infoQse) ? (float) $infoQse->commission_percentage 0;
  1345.                 $commissionActive = ($infoQse) ? (int) $infoQse->active 0;
  1346.                 $activeDetail $agentCommission->getActivedetail();
  1347.                 $isAgent true;
  1348.             }
  1349.         }
  1350.         if ('aviatur_package_retry_secure' == $routeName) {
  1351.             $reintento true;
  1352.             $twig_readonly true;
  1353.             $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($session->get($transactionId.'[mpt][provider]'));
  1354.             $ValuePrestador $session->get($transactionId.'[mpt][ValuePrestador]');
  1355.             $detail $session->get($transactionId.'[mpt]'.'[detail]');
  1356.             $TotalADT $detail->get('TotalADT');
  1357.             $TotalCHD $detail->get('TotalCHD');
  1358.             $parameters $detail->get('parameters');
  1359.             $detail_data_package json_decode($session->get($transactionId.'[mpt]'.'[detail_data_package]'));
  1360.             $billingData $detail_data_package->BD;
  1361.             $infopassenger $detail_data_package->PI;
  1362.             $paymentData $detail_data_package->PD;
  1363.             $contactData $detail_data_package->CD;
  1364.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detail_data_package->BD->id);
  1365.             if (isset($paymentData->cusPOptSelected) && true === $aviaturLoginService->validActiveSession()) {
  1366.                 $customerLogin $tokenStorage->getToken()->getUser();
  1367.                 if (is_object($customerLogin)) {
  1368.                     $paymentsSaved $customerMethodPaymentService->getMethodsByCustomer($customerLoginfalse);
  1369.                 }
  1370.             }
  1371.         } else  {
  1372.             $TotalADT $request->get('TotalADT');
  1373.             $TotalCHD $request->get('TotalCHD');
  1374.             $parameters $request->get('parameters');
  1375.             $reintento false;
  1376.             $twig_readonly false;
  1377.             $infopassenger '';
  1378.             $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($request->get('ProviderId'));
  1379.             if (isset($provider)) {
  1380.                 $session->set($transactionId.'[mpt]'.'[provider]'$provider->getProvideridentifier());
  1381.                 $session->set($transactionId.'[mpt][detail]'$request);
  1382.                 $session->set($transactionId.'[mpt]'.'[TotalADT]'$TotalADT);
  1383.                 $session->set($transactionId.'[mpt]'.'[TotalCHD]'$TotalCHD);
  1384.                 $ValuePrestador substr($request->get('ValuePrestador'), 1);
  1385.                 $session->set($transactionId.'[mpt]'.'[ValuePrestador]'$ValuePrestador);
  1386.                 if (== $session->get($transactionId.'[mpt]'.'[ValueOptionals]')) {
  1387.                     $session->set($transactionId.'[mpt]'.'[infoOptionals]'null);
  1388.                 }
  1389.             } else {
  1390.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  1391.             }
  1392.         }
  1393.         $aviaturLogSave->logSave(print_r($requesttrue), 'PkgRequestDetail''RQ'$transactionId);
  1394.         $datesTransaction json_decode($session->get($transactionId.'[mpt][totalTransaction]'), true);
  1395.         $infoHotel simplexml_load_string($session->get($transactionId.'[mpt][InfoHotel]'));
  1396.         $infopackage simplexml_load_string($session->get($transactionId.'[mpt][infoPackage]'));
  1397.         $paymentOptions = [];
  1398.         $cybersource = [];
  1399.         $banks = [];
  1400.         $isPaymentOnline 'true' == $infopackage->TPA_Extensions->ProductInfo->FormaVenta;
  1401.      
  1402.         
  1403.         if ($isPaymentOnline) {
  1404.             $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  1405.             foreach ($paymentMethodAgency as $payMethod) {
  1406.                 $paymentCode $payMethod->getPaymentMethod()->getCode();
  1407.                 if (!in_array($paymentCode$paymentOptions)) {
  1408.                     if ('p2p' == $paymentCode || 'cybersource' == $paymentCode) {
  1409.                         $paymentOptions[] = $paymentCode;
  1410.                     }
  1411.                 }
  1412.             }
  1413.             if (in_array('cybersource'$paymentOptions)) {
  1414.                 $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  1415.                 $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  1416.             }
  1417.             foreach ($paymentOptions as $key => $paymentOption) {
  1418.                 if ('cybersource' == $paymentOption) {
  1419.                     unset($paymentOptions[$key]); // strip from other renderizable payment methods
  1420.                 }
  1421.             }
  1422.             if (in_array('pse'$paymentOptions)) {
  1423.                 $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  1424.             }
  1425.         }
  1426.     
  1427.         $tarifas = [
  1428.             'AmountADT' => 0,
  1429.             'AmountADN' => 0,
  1430.             'AmountADF' => 0,
  1431.             'AmountANF' => 0,
  1432.             'AmountADD' => 0,
  1433.             'AmountAAN' => 0,
  1434.             'AmountAFN' => 0,
  1435.             'AmountCHD' => 0,
  1436.             'AmountCHN' => 0,
  1437.             'AmountCHF' => 0,
  1438.             'AmountCFN' => 0,
  1439.         ];
  1440.         $WeekDay = [
  1441.             'ADT' => 0,
  1442.             'ADN' => 0,
  1443.             'ADF' => 0,
  1444.             'ANF' => 0,
  1445.             'ADD' => 0,
  1446.             'AAN' => 0,
  1447.             'AFN' => 0,
  1448.             'CHD' => 0,
  1449.             'CHN' => 0,
  1450.             'CHF' => 0,
  1451.             'CFN' => 0,
  1452.         ];
  1453.         $ageMinCHD null;
  1454.         $ageMaxCHD null;
  1455.         $ChdValues null;
  1456.         $ageMinCHN null;
  1457.         $ageMaxCHN null;
  1458.         $ChnValues null;
  1459.         $ageMinCHF null;
  1460.         $ageMaxCHF null;
  1461.         $ChfValues null;
  1462.         $ageMinCFN null;
  1463.         $ageMaxCFN null;
  1464.         $CfnValues null;
  1465.         $subTotal 0;
  1466.         $Amount 0;
  1467.         $CantADT 0;
  1468.         $CantCHD 0;
  1469.         $ChdAmount 0;
  1470.         $ChnAmount 0;
  1471.         $TotalDays $datesTransaction['days'];
  1472.         $UnitCostValue $datesTransaction['UnitCostValue'];
  1473.         $UnitCostName $datesTransaction['UnitCostName'];
  1474.         $countFestivos 0;
  1475.         $selectValue null;
  1476.         $AmountTotal 0;
  1477.         $Name $ValuePrestador;
  1478.         $search '|';
  1479.         $verification strpos($Name$search);
  1480.         /* Cuenta los fines de semana */
  1481.         $fecha1 $datesTransaction['entrada'];
  1482.         $fecha2 $datesTransaction['salida'];
  1483.         $PriceOptionals $session->get($transactionId.'[mpt]'.'[PriceOptionals]');
  1484.         $AmountBaby 0;
  1485.         if (false === $verification) {
  1486.             $datePrestador $ValuePrestador;
  1487.             $prestadorValue explode('*'$datePrestador);
  1488.             $CodeRoom $prestadorValue[0];
  1489.             $BrandCode $prestadorValue[1];
  1490.             $CodeHotel $prestadorValue[2];
  1491.             $RoomType $prestadorValue[3];
  1492.             $RoomCategory $prestadorValue[4];
  1493.             $BookingCode $prestadorValue[5];
  1494.             $iteration $prestadorValue[6];
  1495.             $cantADT $prestadorValue[7];
  1496.             $cantCHD $prestadorValue[8];
  1497.             $TotalPerson = (int)$cantADT + (int)$cantCHD;
  1498.             $room[] = $prestadorValue[9];
  1499.             $PersonAdd $prestadorValue[10];
  1500.             $AddPerson[] = $PersonAdd;
  1501.             $AditionalRoom[] = $room;
  1502.             $personTotal[] = $TotalPerson;
  1503.             $codigoHotel[] = $CodeHotel;
  1504.             $codigoRoom[] = $CodeRoom;
  1505.             $codigoBrand[] = $BrandCode;
  1506.             $typeRoom[] = $RoomType;
  1507.             $categoryRoom[] = $RoomCategory;
  1508.             $codeBooking[] = $BookingCode;
  1509.             $adtCant[] = $cantADT;
  1510.             $chdCant[] = $cantCHD;
  1511.             $ADTotal $parameters['adults_'.$iteration];
  1512.             $CHDTotal $parameters['children_'.$iteration];
  1513.             $CantADT $ADTotal $CantADT;
  1514.             $CantCHD $CHDTotal $CantCHD;
  1515.             if (isset($AditionalRoom[0][0])) {
  1516.                 $final strtotime('+'.$AditionalRoom[0][0].'day'strtotime($fecha2));
  1517.                 $final date('Y-m-d'$final);
  1518.                 $fecha2 $final;
  1519.             }
  1520.             if (empty($parameters['roomAditional_'.$iteration])) {
  1521.                 $parameters['roomAditional_'.$iteration] = 0;
  1522.             }
  1523.             if (empty($parameters['personAditional_'.$iteration])) {
  1524.                 $parameters['personAditional_'.$iteration] = 0;
  1525.             }
  1526.             $age explode(','$parameters['room_'.$iteration.'_childage']);
  1527.             for ($i 1$i <= $CHDTotal; ++$i) {
  1528.                 $selectValue[] = (string) $age[$i 1];
  1529.             }
  1530.             $roomAditional $parameters['roomAditional_'.$iteration];
  1531.             $personAditional $parameters['personAditional_'.$iteration];
  1532.             $aditionalPerson[] = $personAditional;
  1533.             foreach ($infoHotel->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $Accommodations) {
  1534.                 $BrandCode $Accommodations->Identity['BrandCode'];
  1535.                 $HotelCode $Accommodations->Identity['HotelCode'];
  1536.                 if ($HotelCode == $CodeHotel) {
  1537.                     foreach ($Accommodations->RoomProfiles->RoomProfile as $RoomProfiles) {
  1538.                         $RoomTypeCode $RoomProfiles['RoomTypeCode'];
  1539.                         if ($RoomTypeCode == $CodeRoom) {
  1540.                             $BrandName[] = isset($Accommodations->Identity['BrandName']) ? (int) $Accommodations->Identity['BrandName'] : '';
  1541.                             foreach ($RoomProfiles->Prices->Price as $RoomProfile) {
  1542.                                 /* Calculo de Tarifa Adulto */
  1543.                                 if ('ADT' == $RoomProfile['PriceQualifier']) {
  1544.                                     $tarifas['AmountADT'] = (int) $RoomProfile['Amount'];
  1545.                                     $WeekDay['ADT'] = $RoomProfile['WeekDay'];
  1546.                                     $tarifas['ADTotal'] = $ADTotal;
  1547.                                     $tarifas['CountADT'] = (int) $RoomProfile['Count'];
  1548.                                 }
  1549.                                 if ('ADN' == $RoomProfile['PriceQualifier']) {
  1550.                                     $tarifas['AmountADN'] = (int) $RoomProfile['Amount'];
  1551.                                     $WeekDay['ADN'] = $RoomProfile['WeekDay'];
  1552.                                     $tarifas['CountADN'] = (int) $RoomProfile['Count'];
  1553.                                 }
  1554.                                 if ('ADF' == $RoomProfile['PriceQualifier']) {
  1555.                                     $tarifas['AmountADF'] = (int) $RoomProfile['Amount'];
  1556.                                     $WeekDay['ADF'] = $RoomProfile['WeekDay'];
  1557.                                     $tarifas['CountADF'] = (int) $RoomProfile['Count'];
  1558.                                 }
  1559.                                 if ('ANF' == $RoomProfile['PriceQualifier']) {
  1560.                                     $tarifas['AmountANF'] = (int) $RoomProfile['Amount'];
  1561.                                     $WeekDay['ANF'] = $RoomProfile['WeekDay'];
  1562.                                     $tarifas['CountANF'] = (int) $RoomProfile['Count'];
  1563.                                 }
  1564.                                 if ('ADD' == $RoomProfile['PriceQualifier']) {
  1565.                                     $tarifas['AmountADD'] = (int) $RoomProfile['Amount'];
  1566.                                     $WeekDay['ADD'] = $RoomProfile['WeekDay'];
  1567.                                     $tarifas['CountADD'] = (int) $RoomProfile['Count'];
  1568.                                 }
  1569.                                 if ('AAN' == $RoomProfile['PriceQualifier']) {
  1570.                                     $tarifas['AmountAAN'] = (int) $RoomProfile['Amount'];
  1571.                                     $WeekDay['AAN'] = $RoomProfile['WeekDay'];
  1572.                                     $tarifas['CountAAN'] = (int) $RoomProfile['Count'];
  1573.                                 }
  1574.                                 if ('AFN' == $RoomProfile['PriceQualifier']) {
  1575.                                     $tarifas['AmountAFN'] = (int) $RoomProfile['Amount'];
  1576.                                     $WeekDay['AFN'] = $RoomProfile['WeekDay'];
  1577.                                     $tarifas['CountAFN'] = (int) $RoomProfile['Count'];
  1578.                                 }
  1579.                                 if ('CHD' == $RoomProfile['PriceQualifier']) {
  1580.                                     $ageMinCHD[] = (string) $RoomProfile['Age'];
  1581.                                     $ageMaxCHD[] = (string) $RoomProfile['AgeQualifyingCode'];
  1582.                                     $ChdValues[] = (string) $RoomProfile['Amount'];
  1583.                                     $ChdAmount $RoomProfile['Amount'];
  1584.                                     $WeekDay['CHD'] = $RoomProfile['WeekDay'];
  1585.                                     $tarifas['CHDTotal'] = $CHDTotal;
  1586.                                     $tarifas['ageMinCHD'] = (int) $RoomProfile['Age'];
  1587.                                     $tarifas['ageMaxCHD'] = (int) $RoomProfile['AgeQualifyingCode'];
  1588.                                     $tarifas['CountCHD'] = (int) $RoomProfile['Count'];
  1589.                                 }
  1590.                                 if ('CHN' == $RoomProfile['PriceQualifier']) {
  1591.                                     $ageMinCHN[] = (string) $RoomProfile['Age'];
  1592.                                     $ageMaxCHN[] = (string) $RoomProfile['AgeQualifyingCode'];
  1593.                                     $ChnValues[] = (string) $RoomProfile['Amount'];
  1594.                                     $ChnAmount $RoomProfile['Amount'];
  1595.                                     $WeekDay['CHN'] = $RoomProfile['WeekDay'];
  1596.                                     $tarifas['CountCHN'] = (int) $RoomProfile['Count'];
  1597.                                 }
  1598.                                 if ('CHF' == $RoomProfile['PriceQualifier']) {
  1599.                                     $ageMinCHF[] = (string) $RoomProfile['Age'];
  1600.                                     $ageMaxCHF[] = (string) $RoomProfile['AgeQualifyingCode'];
  1601.                                     $ChfValues[] = (string) $RoomProfile['Amount'];
  1602.                                     $WeekDay['CHF'] = $RoomProfile['WeekDay'];
  1603.                                     $tarifas['CountCHF'] = (int) $RoomProfile['Count'];
  1604.                                 }
  1605.                                 if ('CFN' == $RoomProfile['PriceQualifier']) {
  1606.                                     $ageMinCFN[] = (string) $RoomProfile['Age'];
  1607.                                     $ageMaxCFN[] = (string) $RoomProfile['AgeQualifyingCode'];
  1608.                                     $CfnValues[] = (string) $RoomProfile['Amount'];
  1609.                                     $WeekDay['CFN'] = $RoomProfile['WeekDay'];
  1610.                                     $tarifas['CountCFN'] = (int) $RoomProfile['Count'];
  1611.                                 }
  1612.                             }
  1613.                         }
  1614.                     }
  1615.                 }
  1616.             }// End Foreach
  1617.             if (== $UnitCostValue) {
  1618.                 /* si Unidad de costo = 0 la tarifa es por estadia */
  1619.                 $TotalDays 1;
  1620.             } elseif (== $UnitCostValue) {
  1621.                 /* si Unidad de costo = 2 la tarifa es por ocupación */
  1622.                 $ADTotal 1;
  1623.                 if ($CHDTotal 0) {
  1624.                     $CHDTotal 1;
  1625.                 }
  1626.             }
  1627.             if ($tarifas['AmountADF'] > 0) {
  1628.                 /* -------------------- Cálculo cuando hay tarifa fin de semana -------------------------- */
  1629.                 $Amount $this->calculoTarifaFinDeSemana($roomAditional$personAditional$fecha1$fecha2$ADTotal$CHDTotal$tarifas$WeekDay$ageMinCHD$ageMaxCHD$ChdValues$selectValue$ageMinCHN$ageMaxCHN$ChnValues$ageMinCHF$ageMaxCHF$ChfValues$ageMinCFN$ageMaxCFN$CfnValues$UnitCostValue$datesTransaction['days']);
  1630.                 $totalTarifas[] = $Amount['tarifas'];
  1631.                 $tarifaReal[] = $Amount['tarifaReal'];
  1632.                 $Amount $Amount['SubTotal'];
  1633.             } else {
  1634.                 /* -------------------- Cálculo cuando NO hay tarifa fin de semana -------------------------- */
  1635.                 $subTotal $tarifas['AmountADT'] * $ADTotal $TotalDays;
  1636.                 $AmountBaby 0;
  1637.                 if ($ChdAmount 0) {
  1638.                     $tarifas['AmountCHD'] = $this->AmountCHD($AmountBaby$selectValue$ageMinCHD$ageMaxCHD$tarifas['AmountADT'], $ChdValues);
  1639.                     $subTotal $subTotal + ($tarifas['AmountCHD'] * $TotalDays);
  1640.                 }
  1641.                 if ($ChnAmount 0) {
  1642.                     $tarifas['AmountCHN'] = $this->AmountCHD($AmountBaby$selectValue$ageMinCHN$ageMaxCHN$tarifas['AmountADN'], $ChnValues);
  1643.                 }
  1644.                 $totalTarifas[] = $tarifas;
  1645.                 $Amount $this->calculoTarifa($subTotal$TotalDays$tarifas$roomAditional$personAditional$ADTotal$CHDTotal$datesTransaction['days']);
  1646.                 $tarifaReal[] = $Amount['tarifaReal'];
  1647.                 $Amount $Amount['SubTotal'];
  1648.             }
  1649.             $TotalValor[] = $Amount;
  1650.             $Amount $Amount $PriceOptionals;
  1651.         } else {
  1652.             $prestador explode('|'$ValuePrestador);
  1653.             foreach ($prestador as $datePrestador) {
  1654.                 $prestadorValue explode('*'$datePrestador);
  1655.                 $CodeRoom $prestadorValue[0];
  1656.                 $BrandCode $prestadorValue[1];
  1657.                 $CodeHotel $prestadorValue[2];
  1658.                 $RoomType $prestadorValue[3];
  1659.                 $RoomCategory $prestadorValue[4];
  1660.                 $BookingCode $prestadorValue[5];
  1661.                 $iteration $prestadorValue[6];
  1662.                 $cantADT $prestadorValue[7];
  1663.                 $cantCHD $prestadorValue[8];
  1664.                 $TotalPerson $cantADT $cantCHD;
  1665.                 $room[] = $prestadorValue[9];
  1666.                 $PersonAdd $prestadorValue[10];
  1667.                 $AddPerson[] = $PersonAdd;
  1668.                 $AditionalRoom[] = $room;
  1669.                 $personTotal[] = $TotalPerson;
  1670.                 $codigoHotel[] = $CodeHotel;
  1671.                 $codigoRoom[] = $CodeRoom;
  1672.                 $codigoBrand[] = $BrandCode;
  1673.                 $typeRoom[] = $RoomType;
  1674.                 $categoryRoom[] = $RoomCategory;
  1675.                 $codeBooking[] = $BookingCode;
  1676.                 $adtCant[] = $cantADT;
  1677.                 $chdCant[] = $cantCHD;
  1678.                 $ChdValues = [];
  1679.                 $ChnValues = [];
  1680.                 $ChfValues = [];
  1681.                 $CfnValues = [];
  1682.                 $ADTotal $parameters['adults_'.$iteration];
  1683.                 $CHDTotal $parameters['children_'.$iteration];
  1684.                 if (isset($AditionalRoom[0][0])) {
  1685.                     $final strtotime('+'.$AditionalRoom[0][0].'day'strtotime($fecha2));
  1686.                     $final date('Y-m-d'$final);
  1687.                     $fecha2 $final;
  1688.                 }
  1689.                 $CantADT $ADTotal $CantADT;
  1690.                 $CantCHD $CHDTotal $CantCHD;
  1691.                 if (empty($parameters['roomAditional_'.$iteration])) {
  1692.                     $parameters['roomAditional_'.$iteration] = 0;
  1693.                 }
  1694.                 if (empty($parameters['personAditional_'.$iteration])) {
  1695.                     $parameters['personAditional_'.$iteration] = 0;
  1696.                 }
  1697.                 $selectValue null;
  1698.                 $age explode(','$parameters['room_'.$iteration.'_childage']);
  1699.                 for ($i 1$i <= $CHDTotal; ++$i) {
  1700.                     $selectValue[] = (string) $age[$i 1];
  1701.                 }
  1702.                 $roomAditional $parameters['roomAditional_'.$iteration];
  1703.                 $personAditional $parameters['personAditional_'.$iteration];
  1704.                 $aditionalPerson[] = $personAditional;
  1705.                 foreach ($infoHotel->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $Accommodations) {
  1706.                     $BrandCode $Accommodations->Identity['BrandCode'];
  1707.                     $HotelCode $Accommodations->Identity['HotelCode'];
  1708.                     if ($HotelCode == $CodeHotel) {
  1709.                         $BrandName[] = (int) $Accommodations->Identity['BrandName'];
  1710.                         foreach ($Accommodations->RoomProfiles->RoomProfile as $RoomProfiles) {
  1711.                             $RoomTypeCode $RoomProfiles['RoomTypeCode'];
  1712.                             if ($RoomTypeCode == $CodeRoom) {
  1713.                                 foreach ($RoomProfiles->Prices->Price as $RoomProfile) {
  1714.                                     /* Calculo de Tarifa Adulto */
  1715.                                     if ('ADT' == $RoomProfile['PriceQualifier']) {
  1716.                                         $tarifas['AmountADT'] = (int) $RoomProfile['Amount'];
  1717.                                         $WeekDay['ADT'] = $RoomProfile['WeekDay'];
  1718.                                         $tarifas['ADTotal'] = $ADTotal;
  1719.                                         $tarifas['CountADT'] = (int) $RoomProfile['Count'];
  1720.                                     }
  1721.                                     if ('ADN' == $RoomProfile['PriceQualifier']) {
  1722.                                         $tarifas['AmountADN'] = (int) $RoomProfile['Amount'];
  1723.                                         $WeekDay['ADN'] = $RoomProfile['WeekDay'];
  1724.                                         $tarifas['CountADN'] = (int) $RoomProfile['Count'];
  1725.                                     }
  1726.                                     if ('ADF' == $RoomProfile['PriceQualifier']) {
  1727.                                         $tarifas['AmountADF'] = (int) $RoomProfile['Amount'];
  1728.                                         $WeekDay['ADF'] = $RoomProfile['WeekDay'];
  1729.                                         $tarifas['CountADF'] = (int) $RoomProfile['Count'];
  1730.                                     }
  1731.                                     if ('ANF' == $RoomProfile['PriceQualifier']) {
  1732.                                         $tarifas['AmountANF'] = (int) $RoomProfile['Amount'];
  1733.                                         $WeekDay['ANF'] = $RoomProfile['WeekDay'];
  1734.                                         $tarifas['CountANF'] = (int) $RoomProfile['Count'];
  1735.                                     }
  1736.                                     if ('ADD' == $RoomProfile['PriceQualifier']) {
  1737.                                         $tarifas['AmountADD'] = (int) $RoomProfile['Amount'];
  1738.                                         $WeekDay['ADD'] = $RoomProfile['WeekDay'];
  1739.                                         $tarifas['CountADD'] = (int) $RoomProfile['Count'];
  1740.                                     }
  1741.                                     if ('AAN' == $RoomProfile['PriceQualifier']) {
  1742.                                         $tarifas['AmountAAN'] = (int) $RoomProfile['Amount'];
  1743.                                         $WeekDay['AAN'] = $RoomProfile['WeekDay'];
  1744.                                         $tarifas['CountAAN'] = (int) $RoomProfile['Count'];
  1745.                                     }
  1746.                                     if ('AFN' == $RoomProfile['PriceQualifier']) {
  1747.                                         $tarifas['AmountAFN'] = (int) $RoomProfile['Amount'];
  1748.                                         $WeekDay['AFN'] = $RoomProfile['WeekDay'];
  1749.                                         $tarifas['CountAFN'] = (int) $RoomProfile['Count'];
  1750.                                     }
  1751.                                     if ('CHD' == $RoomProfile['PriceQualifier']) {
  1752.                                         $ageMinCHD[] = (string) $RoomProfile['Age'];
  1753.                                         $ageMaxCHD[] = (string) $RoomProfile['AgeQualifyingCode'];
  1754.                                         $ChdValues[] = (string) $RoomProfile['Amount'];
  1755.                                         $ChdAmount $RoomProfile['Amount'];
  1756.                                         $tarifas['CHDTotal'] = $CHDTotal;
  1757.                                         $tarifas['ageMinCHD'] = (int) $RoomProfile['Age'];
  1758.                                         $tarifas['ageMaxCHD'] = (int) $RoomProfile['AgeQualifyingCode'];
  1759.                                         $tarifas['CountCHD'] = (int) $RoomProfile['Count'];
  1760.                                     }
  1761.                                     if ('CHN' == $RoomProfile['PriceQualifier']) {
  1762.                                         $ageMinCHN[] = (string) $RoomProfile['Age'];
  1763.                                         $ageMaxCHN[] = (string) (int) $RoomProfile['AgeQualifyingCode'];
  1764.                                         $ChnValues[] = (string) (int) $RoomProfile['Amount'];
  1765.                                         $ChnAmount $RoomProfile['Amount'];
  1766.                                         $WeekDay['CHN'] = $RoomProfile['WeekDay'];
  1767.                                         $tarifas['CountCHN'] = (int) $RoomProfile['Count'];
  1768.                                     }
  1769.                                     if ('CHF' == $RoomProfile['PriceQualifier']) {
  1770.                                         $ageMinCHF[] = (string) $RoomProfile['Age'];
  1771.                                         $ageMaxCHF[] = (string) $RoomProfile['AgeQualifyingCode'];
  1772.                                         $ChfValues[] = (string) $RoomProfile['Amount'];
  1773.                                         $WeekDay['CHF'] = $RoomProfile['WeekDay'];
  1774.                                         $tarifas['CountCHN'] = (int) $RoomProfile['Count'];
  1775.                                     }
  1776.                                     if ('CFN' == $RoomProfile['PriceQualifier']) {
  1777.                                         $ageMinCFN[] = (string) $RoomProfile['Age'];
  1778.                                         $ageMaxCFN[] = (string) $RoomProfile['AgeQualifyingCode'];
  1779.                                         $CfnValues[] = (string) $RoomProfile['Amount'];
  1780.                                         $WeekDay['CFN'] = $RoomProfile['WeekDay'];
  1781.                                         $tarifas['CountCFN'] = (int) $RoomProfile['Count'];
  1782.                                     }
  1783.                                 }
  1784.                             }
  1785.                         }
  1786.                     }
  1787.                 }// End Foreach
  1788.                 if (== $UnitCostValue) {
  1789.                     /* si Unidad de costo = 0 la tarifa es por estadia */
  1790.                     $TotalDays 1;
  1791.                 } elseif (== $UnitCostValue) {
  1792.                     /* si Unidad de costo = 2 la tarifa es por ocupación */
  1793.                     $ADTotal 1;
  1794.                     if ($CHDTotal 0) {
  1795.                         $CHDTotal 1;
  1796.                     }
  1797.                 }
  1798.                 if ($tarifas['AmountADF'] > 0) {
  1799.                     /* -------------------- Cálculo cuando hay tarifa fin de semana -------------------------- */
  1800.                     $SubTotal $this->calculoTarifaFinDeSemana($roomAditional$personAditional$fecha1$fecha2$ADTotal$CHDTotal$tarifas$WeekDay$ageMinCHD$ageMaxCHD$ChdValues$selectValue$ageMinCHN$ageMaxCHN$ChnValues$ageMinCHF$ageMaxCHF$ChfValues$ageMinCFN$ageMaxCFN$CfnValues$UnitCostValue$datesTransaction['days']);
  1801.                     $totalTarifas[] = $SubTotal['tarifas'];
  1802.                     $tarifaReal[] = $SubTotal['tarifaReal'];
  1803.                     $SubTotal $SubTotal['SubTotal'];
  1804.                 } else {
  1805.                     /* -------------------- Cálculo cuando NO hay tarifa fin de semana -------------------------- */
  1806.                     $subTotal $tarifas['AmountADT'] * $ADTotal $TotalDays;
  1807.                     $AmountBaby 0;
  1808.                     if ($ChdAmount 0) {
  1809.                         $tarifas['AmountCHD'] = 0;
  1810.                         $tarifas['AmountCHD'] = $this->AmountCHD($AmountBaby$selectValue$ageMinCHD$ageMaxCHD$tarifas['AmountADT'], $ChdValues);
  1811.                         $subTotal $subTotal + ($tarifas['AmountCHD'] * $TotalDays);
  1812.                     }
  1813.                     if ($ChnAmount 0) {
  1814.                         $tarifas['AmountCHN'] = $this->AmountCHD($AmountBaby$selectValue$ageMinCHN$ageMaxCHN$tarifas['AmountADN'], $ChnValues);
  1815.                     }
  1816.                     $SubTotal $this->calculoTarifa($subTotal$TotalDays$tarifas$roomAditional$personAditional$ADTotal$CHDTotal$datesTransaction['days']);
  1817.                     $totalTarifas[] = $tarifas;
  1818.                     $tarifaReal[] = $SubTotal['tarifaReal'];
  1819.                     $SubTotal $SubTotal['SubTotal'];
  1820.                 }
  1821.                 $Amount $Amount $SubTotal;
  1822.                 $ValorTotal[] = $SubTotal;
  1823.                 $TotalValor $ValorTotal;
  1824.             }
  1825.             $Amount $Amount $PriceOptionals;
  1826.         }
  1827.         if (isset($AditionalRoom)) {
  1828.             $keys array_pop($AditionalRoom);
  1829.             $keys2 max($keys);
  1830.             $final strtotime('+'.$keys2.'day'strtotime($datesTransaction['salida']));
  1831.             $final date('Y-m-d'$final);
  1832.             $datesTransaction['salida'] = $final;
  1833.         }
  1834.         $arrayCommissionAgent = [$isAgent];
  1835.         /*         * ***************************** Commission Agent *********************** */
  1836.         if ($isAgent) {
  1837.             $commissionFare round((float) $infopackage->TPA_Extensions->ProductInfo->Comision $tarifaCommissionPercentage);
  1838.             $claseServicio $infopackage->TPA_Extensions->ProductInfo->ClaseServicio;
  1839.             $totalAmount = ('N' == $claseServicio) ? (float) $Amount / (float) ($aviaturPaymentIva) : $Amount;
  1840.             //$totalAmount=round($totalAmount);
  1841.             $commissionFareAll round($totalAmount * ((float) $infopackage->TPA_Extensions->ProductInfo->Comision 100));
  1842.             $commissionFare round($totalAmount * ($commissionFare 100));
  1843.             $agentCommission $packageCommission;
  1844.             $textCommission 'QSE($)';
  1845.             if ('1' == $commissionActive) {
  1846.                 $agentCommission round($totalAmount $packageCommissionPercentage);
  1847.                 $textCommission 'QSE(%)';
  1848.             }
  1849.             $Amount += (float) $agentCommission;
  1850.             $valueQsePay round(($agentCommission / ($aviaturPaymentIva)) * $productCommissionPercentage);
  1851.             $commissionPay $commissionFare $valueQsePay;
  1852.             $info_product = [
  1853.                 'amountQse' => (float) $agentCommission,
  1854.                 'commissionQse' => (float) $valueQsePay,
  1855.                 'amountTa' => (float) $commissionFareAll,
  1856.                 'commissionTa' => (float) $commissionFare,
  1857.                 'amountProduct' => round((float) $Amount) - (float) $agentCommission - (float) $commissionFareAll,
  1858.                 'amountFare' => round((float) $Amount) - (float) $agentCommission,
  1859.                 'percentageTarifa' => isset($infopackage->TPA_Extensions->ProductInfo->Comision) ? (float) $infopackage->TPA_Extensions->ProductInfo->Comision 0,
  1860.             ];
  1861.             $arrayCommissionAgent = [$isAgent$commissionFare$agentCommission$textCommission$commissionPay$activeDetail$info_product];
  1862.         }
  1863.         $infoDates = [
  1864.             'TotalADT' => $CantADT,
  1865.             'TotalCHD' => $CantCHD,
  1866.             'Amount' => $Amount,
  1867.             'transactionId' => $transactionId,
  1868.             'datesTransaction' => $datesTransaction,
  1869.             'BrandCode' => $codigoBrand,
  1870.             'BrandName' => $BrandName,
  1871.             'HotelCode' => $codigoHotel,
  1872.             'CodeRoom' => $codigoRoom,
  1873.             'typeRoom' => $typeRoom,
  1874.             'categoryRoom' => $categoryRoom,
  1875.             'codeBooking' => $codeBooking,
  1876.             'adtCant' => $adtCant,
  1877.             'chdCant' => $chdCant,
  1878.             'personTotal' => $personTotal,
  1879.             'personAditional' => $aditionalPerson,
  1880.             'AditionalRoom' => $room,
  1881.             'CantAditionalRoom' => $room,
  1882.             'AddPerson' => $AddPerson,
  1883.             'ValorTotal' => $TotalValor,
  1884.             'totalTarifas' => $totalTarifas,
  1885.             'tarifaReal' => $tarifaReal,
  1886.             'reintento' => $reintento,
  1887.             'optionals' => '',
  1888.             'infopassenger' => $infopassenger,
  1889.             'requestInformation' => $request->get('parameters'),
  1890.         ];
  1891.         if ($isAgent) {
  1892.             $infoDates['commissionAgent'] = $arrayCommissionAgent;
  1893.         }
  1894.         if ('COP' != mb_strtoupper($infoDates['datesTransaction']['CurrencyCode']) && 'true' == $infoDates['datesTransaction']['FormaVenta']) {
  1895.             $hoy date('Y-m-d');
  1896.             $xmlTemplate $productInfo->getTasaCambio($hoy);
  1897.             $aviaturLogSave->logSave(print_r($xmlTemplatetrue), 'TASAS_CAMBIO''RQ');
  1898.             $financial $aviaturWebService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  1899.             $aviaturLogSave->logSave(print_r($financialtrue), 'TASAS_CAMBIO''RS');
  1900.             $validate false;
  1901.             foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
  1902.                 if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && mb_strtoupper($infoDates['datesTransaction']['CurrencyCode']) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
  1903.                     $financialValue = (int) $tasa->VALOR;
  1904.                     $exchangeValues = [
  1905.                         'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
  1906.                         'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
  1907.                     ];
  1908.                     $validate true;
  1909.                 }
  1910.             }
  1911.             if (!$validate) {
  1912.                 $hoy date('Y-m-d'strtotime('-1 day'strtotime(date('Y-m-d'))));
  1913.                 $xmlTemplate $productInfo->getTasaCambio($hoy);
  1914.                 $financial $aviaturWebService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  1915.                 foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
  1916.                     if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && mb_strtoupper($infoDates['datesTransaction']['CurrencyCode']) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
  1917.                         $financialValue = (int) $tasa->VALOR;
  1918.                         $exchangeValues = [
  1919.                             'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
  1920.                             'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
  1921.                         ];
  1922.                     }
  1923.                 }
  1924.             }
  1925.             if (!isset($financialValue) || !is_numeric($financialValue)) {
  1926.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_search_package'), '''Error en la conversión de moneda'));
  1927.             } else {
  1928.                 $infoDates['AmountTotal'] = $infoDates['Amount'] * $financialValue;
  1929.                 $session->set('[mpt][finantial_rate]'$financialValue);
  1930.                 $session->set($transactionId.'[mpt][exchangeValues]'json_encode($exchangeValues));
  1931.             }
  1932.         } else {
  1933.             $infoDates['AmountTotal'] = $infoDates['Amount'];
  1934.         }
  1935.         $typePerson[1] = [
  1936.             'ADT' => $CantADT,
  1937.             'CHD' => $CantCHD,
  1938.             'INF' => 0,
  1939.         ];
  1940.         $urlDetail $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/detail.html.twig');
  1941.         $infoOptionals simplexml_load_string($session->get($transactionId.'[mpt]'.'[infoOptionals]'));
  1942.         $ValueOptionals $session->get($transactionId.'[mpt]'.'[ValueOptionals]');
  1943.         $optionalsValue explode('*'substr($ValueOptionals0, -1));
  1944.         if (!= $ValueOptionals) {
  1945.             $optionalsValue explode('*'substr($ValueOptionals0, -1));
  1946.             foreach ($optionalsValue as $optional) {
  1947.                 $optionals explode('|'$optional);
  1948.                 $fareID $optionals[5];
  1949.                 $fecha $optionals[1];
  1950.                 $cantidad $optionals[2];
  1951.                 foreach ($infoOptionals->Package as $tarifas) {
  1952.                     $tarifas->TPA_Extensions->ServiciosOpcionales->TravelerInformation null;
  1953.                     $tarifas->TPA_Extensions->ServiciosOpcionales->LongDescription null;
  1954.                     foreach ($tarifas->TPA_Extensions->ServiciosOpcionales->TarifasServiciosOpc->Tarifas as $tarifa) {
  1955.                         if ($fareID == $tarifa->FareId) {
  1956.                             $ProductName $tarifas->TPA_Extensions->ServiciosOpcionales->ProductName;
  1957.                             $infoDates['optionals']['ProductName'][] = $ProductName;
  1958.                             $infoDates['optionals']['infOptional'][] = base64_encode($tarifas);
  1959.                             $infoDates['optionals']['FechaInicio'][] = $fecha;
  1960.                             $infoDates['optionals']['cantSelection'][] = $cantidad;
  1961.                             $infoDates['optionals']['FareSale'][] = $tarifa->FareSale;
  1962.                             $infoDates['optionals']['Axis1Attribute'][] = $tarifa->Axis1Attribute;
  1963.                         }
  1964.                     }
  1965.                 }
  1966.             }
  1967.         }
  1968.         $referer $session->get($transactionId.'[package_detail_url]');
  1969.         $session->set($transactionId.'[mpt][infoDates]'json_encode($infoDates));
  1970.         $repositoryDocumentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  1971.         $queryDocumentType $repositoryDocumentType
  1972.             ->createQueryBuilder('p')
  1973.             ->where('p.paymentcode != :paymentcode')
  1974.             ->setParameter('paymentcode''')
  1975.             ->getQuery();
  1976.         $documentPaymentType $queryDocumentType->getResult();
  1977.         $twigVariables = [
  1978.             'referer' => $referer,
  1979.             'FormaVenta' => (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta,
  1980.             'banks' => $banks,
  1981.             'cybersource' => $cybersource,
  1982.             'contactData' => $contactData ?? null,
  1983.             'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findAll(),
  1984.             'twig_readonly' => $twig_readonly,
  1985.             'paymentOptions' => $paymentOptions,
  1986.             'infoDates' => $infoDates,
  1987.             'doc_type' => $typeDocument,
  1988.             'documentPassengerType' => $documentPassengerType,
  1989.             'billingData' => $billingData ?? null,
  1990.             'services' => $typePerson,
  1991.             'gender' => $typeGender,
  1992.             'conditions' => $conditions,
  1993.             'payment_type_form_name' => $provider->getPaymentType()->getTwig(),
  1994.             'payment_doc_type' => $documentPaymentType,
  1995.             'infoPackage' => $infopackage,
  1996.             'passengers' => $detail_data_package->PI ?? null,
  1997.             'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  1998.             'phone_prefixes' => $phonePrefixes,
  1999.             'default_country' => 'CO',
  2000.         ];
  2001.         return $this->render($urlDetail$twigVariables);
  2002.     }
  2003.     public function prePaymentStep1Action(Request $requestTokenizerService $aviaturTokenizerAviaturEncoder $aviaturEncoderCustomerMethodPaymentService $customerMethodPaymentServiceTokenStorageInterface $tokenStorageTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  2004.     {
  2005.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2006.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  2007.         $isFront $this->session->has('operatorId');
  2008.         $redirectResponse $this->maintenanceTimeValidator->validateMaintenanceTime();
  2009.         if ($redirectResponse !== null && !$isFront) {
  2010.             return $this->json(['error' => 'error''message' => $redirectResponse["message"]]);
  2011.         }
  2012.         if ($request->isXmlHttpRequest()) {
  2013.             $request $request->request;
  2014.             $transactionId $session->get($transactionIdSessionName);
  2015.             $billingData $request->get('BD');
  2016.             $em $this->managerRegistry;
  2017.             $postData $request->all();
  2018.             $publicKey $aviaturEncoder->aviaturRandomKey();
  2019.             if (isset($postData['PD']['card_num'])) {
  2020.                 $postDataInfo $postData;
  2021.                 if (isset($postDataInfo['PD']['cusPOptSelected'])) {
  2022.                     $customerLogin $tokenStorage->getToken()->getUser();
  2023.                     $infoMethodPaymentByClient $customerMethodPaymentService->getMethodsByCustomer($customerLogintrue);
  2024.                     $cardToken $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
  2025.                     $postDataInfo['PD']['card_num'] = $cardToken;
  2026.                     $postData['PD']['card_num'] = $cardToken;
  2027.                 } else {
  2028.                     $postDataInfo['PD']['card_num'] = $aviaturTokenizer->getToken($postData['PD']['card_num']);
  2029.                 }
  2030.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  2031.             }
  2032.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
  2033.             $formUserInfo = new FormUserInfo();
  2034.             $formUserInfo->setInfo($encodedInfo);
  2035.             $formUserInfo->setPublicKey($publicKey);
  2036.             $em->persist($formUserInfo);
  2037.             $em->flush();
  2038.             $session->set($transactionId.'[mpt][user_info]'$formUserInfo->getId());
  2039.             if ((true !== $session->has($transactionId.'[mpt][retry]')) || (true !== $session->has($transactionId.'[mpt][prepayment_check]'))) {
  2040.                 if (true === $session->has($transactionId.'[mpt][detail]')) {
  2041.                     //$postData = $request->all();
  2042.                     $session->set($transactionId.'[mpt][detail_data_package]'json_encode($postData));
  2043.                     $passangersData $request->get('PI');
  2044.                     $passangerNames = [];
  2045.                     for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  2046.                         $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  2047.                         $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  2048.                     }
  2049.                     $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  2050.                     if (== sizeof($nameWhitelist)) {
  2051.                         $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  2052.                         if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  2053.                             (sizeof($nameBlacklist)) ||
  2054.                                 (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  2055.                             return $this->json(['error' => 'error''message' => 'nombre inválido']);
  2056.                         }
  2057.                     }
  2058.                     $isFront $session->has('operatorId');
  2059.                     if ($isFront) {
  2060.                         $customer null;
  2061.                         $ordersProduct null;
  2062.                     } else {
  2063.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  2064.                         $ordersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
  2065.                     }
  2066.                     if (null == $ordersProduct) {
  2067.                         $documentTypes $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  2068.                         $arrayDocumentTypes = [];
  2069.                         foreach ($documentTypes as $documentType) {
  2070.                             $arrayDocumentTypes[$documentType->getExternalCode()] = $documentType->getId();
  2071.                         }
  2072.                         $genders $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  2073.                         $arrayGenders = [];
  2074.                         foreach ($genders as $gender) {
  2075.                             $arrayGenders[$gender->getCode()] = $gender->getExternalCode();
  2076.                         }
  2077.                         $session->set($transactionId.'[mpt][retry]'$aviaturPaymentRetryTimes);
  2078.                         $detail $session->get($transactionId.'[mpt][detail]');
  2079.                         $session->set($transactionId.'[mpt][prepayment]'$detail);
  2080.                         $cancelPenalties = (string) '';
  2081.                         $ajaxUrl $this->generateUrl('aviatur_package_prepayment_step_2_secure');
  2082.                         return $this->json(['cancelPenalties' => $cancelPenalties'ajax_url' => $ajaxUrl]);
  2083.                     } else {
  2084.                         $booking = [];
  2085.                         $cus = [];
  2086.                         foreach ($ordersProduct as $orderProduct) {
  2087.                             $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  2088.                             $paymentResponse json_decode($productResponse);
  2089.                             array_push($booking'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
  2090.                             if (isset($paymentResponse->x_approval_code)) {
  2091.                                 array_push($cus$paymentResponse->x_approval_code);
  2092.                             } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  2093.                                 array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  2094.                             }
  2095.                         }
  2096.                         return $this->json([
  2097.                             'error' => 'pending payments',
  2098.                             'message' => 'pending_payments',
  2099.                             'booking' => $booking,
  2100.                             'cus' => $cus,
  2101.                         ]);
  2102.                     }
  2103.                 } else {
  2104.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
  2105.                 }
  2106.             } else {
  2107.                 $paymentData $request->get('PD');
  2108.                 $paymentData json_decode(json_encode($paymentData));
  2109.                 $json json_decode($session->get($transactionId.'[mpt][order]'));
  2110.                 if (!is_null($json)) {
  2111.                     $json->ajax_url $this->generateUrl('aviatur_package_prepayment_step_2_secure');
  2112.                     // reemplazar datos de pago por los nuevos.
  2113.                     $oldPostData json_decode($session->get($transactionId.'[mpt][detail_data_package]'));
  2114.                     if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
  2115.                         if (isset($paymentData->cusPOptSelected)) {
  2116.                             $customerLogin $tokenStorage->getToken()->getUser();
  2117.                             $infoMethodPaymentByClient $customerMethodPaymentService->getMethodsByCustomer($customerLogintrue);
  2118.                             $card_num_token $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  2119.                         } else {
  2120.                             $card_num_token $aviaturTokenizer->getToken($paymentData->card_num);
  2121.                         }
  2122.                         $card_values = ['card_num_token' => $card_num_token'card_num' => $paymentData->card_num];
  2123.                     }
  2124.                     unset($oldPostData->PD);
  2125.                     $oldPostData->PD $paymentData;
  2126.                     if (isset($card_num_token)) {
  2127.                         $oldPostData->PD->card_values $card_values;
  2128.                     }
  2129.                     $session->set($transactionId.'[mpt][detail_data_package]'json_encode($oldPostData));
  2130.                     $response = new Response(json_encode($json));
  2131.                     $response->headers->set('Content-Type''application/json');
  2132.                     return $response;
  2133.                 } else {
  2134.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos datos de tu orden, por favor vuelve a intentarlo')]);
  2135.                 }
  2136.             }
  2137.         } else {
  2138.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  2139.         }
  2140.     }
  2141.     public function prePaymentStep2Action(Request $requestOrderController $aviaturOrderControllerAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  2142.     {
  2143.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2144.         $order = [];
  2145.         if ($request->isXmlHttpRequest()) {
  2146.             $request $request->request;
  2147.             $em $this->managerRegistry;
  2148.             $session $this->session;
  2149.             $agency $this->agency;
  2150.             $billingData $request->get('BD');
  2151.             $transactionId $session->get($transactionIdSessionName);
  2152.             $session->set($transactionId.'[mpt][prepayment_check]'true);
  2153.             $infoDates json_decode($session->get($transactionId.'[mpt][infoDates]'), true);
  2154.             if (true !== $session->has($transactionId.'[mpt][order]')) {
  2155.                 if (true === $session->has($transactionId.'[mpt][detail]')) {
  2156.                     $isFront $session->has('operatorId');
  2157.                     if ($isFront) {
  2158.                         $customer $billingData;
  2159.                         $customer['isFront'] = true;
  2160.                         $status 'B2T';
  2161.                     } else {
  2162.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  2163.                         $status 'waiting';
  2164.                     }
  2165.                     if (isset($agency)) {
  2166.                         $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('MPT');
  2167.                         if ($isFront) {
  2168.                             $orderIdentifier '{order_product_reservation}';
  2169.                         } else {
  2170.                             $orderIdentifier '{order_product_num}';
  2171.                         }
  2172.                         $order $aviaturOrderController->createAction($agency$customer$productType$orderIdentifier$status);
  2173.                         $orderId str_replace('ON'''$order['order']);
  2174.                         $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  2175.                         $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[mpt][user_info]'));
  2176.                         $formUserInfo->setOrder($orderEntity);
  2177.                         $em->persist($formUserInfo);
  2178.                         $em->flush();
  2179.                         // Agent Transaction, Save commission QSE or Percentage
  2180.                         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  2181.                             $orderProductCode $session->get($transactionId.'[mpt][order]');
  2182.                             $productId str_replace('PN'''json_decode($orderProductCode)->products);
  2183.                             $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2184.                             $agentId $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  2185.                             $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agentId);
  2186.                             $arrayInfo $infoDates['commissionAgent'];
  2187.                             $agentTransaction = new AgentTransaction();
  2188.                             $agentTransaction->setAgent($agentId);
  2189.                             $agentTransaction->setAgentCommission($agentCommission);
  2190.                             $agentTransaction->setOrderProduct($orderProduct);
  2191.                             $agentTransaction->setCommissionvalue(round((float) ($arrayInfo[4])));
  2192.                             $agentTransaction->setAmountQse($arrayInfo[6]['amountQse']);
  2193.                             $agentTransaction->setCommissionQse($arrayInfo[6]['commissionQse']);
  2194.                             $agentTransaction->setAmountTarifa($arrayInfo[6]['amountTa']);
  2195.                             $agentTransaction->setCommissionTarifa($arrayInfo[6]['commissionTa']);
  2196.                             $agentTransaction->setAmountProduct($arrayInfo[6]['amountProduct']);
  2197.                             $agentTransaction->setPercentageTarifa($arrayInfo[6]['percentageTarifa']);
  2198.                             $em->persist($agentTransaction);
  2199.                             $em->flush();
  2200.                         }
  2201.                         if ($isFront) {
  2202.                             $order['url'] = $this->makeReservation($transactionId);
  2203.                         } else {
  2204.                             $order['url'] = $this->generateUrl('aviatur_package_payment_secure');
  2205.                         }
  2206.                         return $this->json($order);
  2207.                     } else {
  2208.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró la agencia con el dominio: '.$request->getHost()));
  2209.                     }
  2210.                 } else {
  2211.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
  2212.                 }
  2213.             } else {
  2214.                 $order['url'] = $this->generateUrl('aviatur_package_payment_secure');
  2215.                 return $this->json($order);
  2216.             }
  2217.         } else {
  2218.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  2219.         }
  2220.     }
  2221.     public function paymentAction(Request $requestPSEController $aviaturPsePaymentControllerP2PController $aviaturP2pPaymentController, \Swift_Mailer $mailerSafetypayController $aviaturSafetypayControllerTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag,OrderController $aviaturOrderController)
  2222.     {
  2223.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2224.         $emailNotification $parameterBag->get('email_notification');
  2225.         $orderProduct = [];
  2226.         $emissionData null;
  2227.         $response null;
  2228.         $em $this->managerRegistry;
  2229.         $transactionId $session->get($transactionIdSessionName);
  2230.         $postData json_decode($session->get($transactionId.'[mpt][detail_data_package]'));
  2231.         $orderInfo json_decode($session->get($transactionId.'[mpt][order]'));
  2232.         $infoDates json_decode($session->get($transactionId.'[mpt][infoDates]'), true);
  2233.         $infoPackage simplexml_load_string((string) $session->get($transactionId.'[mpt][infoPackage]'));
  2234.         $productId str_replace('PN'''$orderInfo->products);
  2235.         $orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2236.         $paymentData $postData->PD;
  2237.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  2238.         $x_total_amount = (int) $infoDates['AmountTotal'];
  2239.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  2240.         $aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
  2241.         $x_amount_base $x_total_amount / ($aviaturPaymentIva);
  2242.         $x_amount_iva $x_amount_base $aviaturPaymentIva;
  2243.         if ('p2p' == $paymentData->type) {
  2244.             $array = [
  2245.                 'x_currency_code' => (string) 'COP',
  2246.                 'x_amount' => number_format(round((float) ($x_total_amount)), 0'.'''),
  2247.                 'x_tax' => number_format(round((float) ($x_amount_iva)), 2'.'''),
  2248.                 'x_amount_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  2249.                 'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  2250.                 'x_first_name' => $customer->getFirstname(),
  2251.                 'x_last_name' => $customer->getLastname(),
  2252.                 'x_description' => 'Paquete - '.$infoDates['datesTransaction']['Description'],
  2253.                 'x_cust_id' => $customer->getDocumentType()->getPaymentcode().' '.$customer->getDocumentnumber(),
  2254.                 'x_address' => $customer->getAddress(),
  2255.                 'x_phone' => $customer->getPhone(),
  2256.                 'x_email' => $customer->getEmail(),
  2257.                 'x_card_num' => $paymentData->card_num,
  2258.                 'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
  2259.                 'x_card_code' => $paymentData->card_code,
  2260.                 'x_differed' => $paymentData->differed,
  2261.                 'x_client_id' => $postData->BD->id,
  2262.                 'product_type' => 'mpt',
  2263.             ];
  2264.             if (isset($paymentData->card_values)) {
  2265.                 $array['card_values'] = (array) $paymentData->card_values;
  2266.             }
  2267.             if (isset($paymentData->cusPOptSelected)) {
  2268.                 $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  2269.             }
  2270.             if (isset($postData->PD->savePaymProc)) {
  2271.                 $array['x_provider_id'] = 1;
  2272.             } elseif (isset($paymentData->cusPOptSelected)) {
  2273.                 if (isset($paymentData->cusPOptSelectedStatus)) {
  2274.                     if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
  2275.                         $array['x_provider_id'] = 1;
  2276.                     } else {
  2277.                         $array['x_provider_id'] = 2;
  2278.                     }
  2279.                 } else {
  2280.                     $array['x_provider_id'] = 2;
  2281.                 }
  2282.             }
  2283.             $paymentResponse $aviaturP2pPaymentController->placetopayAction($array);
  2284.             unset($array['x_client_id']);
  2285.             if (null != $paymentResponse) {
  2286.                 return $this->redirect($this->generateUrl('aviatur_package_payment_p2p_return_url_secure', [], true));
  2287.             } else {
  2288.                 $orderProduct[0]->setStatus('pending');
  2289.                 $em->persist($orderProduct[0]);
  2290.                 $em->flush();
  2291.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), '''No hay respuesta por parte del servicio de pago, por favor intente nuevamente o comuníquese con nosotros para finalizar su transacción'));
  2292.             }
  2293.         } elseif ('pse' == $paymentData->type) {
  2294.             $array = [
  2295.                 'x_doc_num' => $paymentData->pse_doc_num,
  2296.                 'x_doc_type' => $paymentData->pse_doc_type,
  2297.                 // 'x_doc_num' => $customer->getDocumentnumber(),
  2298.                 // 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  2299.                 'x_first_name' => $customer->getFirstname(),
  2300.                 'x_last_name' => $customer->getLastname(),
  2301.                 'x_company' => 'Aviatur',
  2302.                 'x_email' => $customer->getEmail(),
  2303.                 'x_address' => $customer->getAddress(),
  2304.                 'x_city' => $customer->getCity()->getDescription(),
  2305.                 'x_province' => $customer->getCity()->getDescription(),
  2306.                 'x_country' => $customer->getCountry()->getDescription(),
  2307.                 'x_phone' => $customer->getPhone(),
  2308.                 'x_mobile' => $customer->getCellphone(),
  2309.                 'x_bank' => $paymentData->pse_bank,
  2310.                 'x_type' => $paymentData->pse_type,
  2311.                 'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  2312.                 'x_description' => 'Paquete - '.$infoDates['datesTransaction']['Description'],
  2313.                 'x_currency' => (string) 'COP',
  2314.                 'x_total_amount' => number_format(round((float) ($x_total_amount)), 0'.'''),
  2315.                 'x_tax_amount' => number_format(round((float) ($x_amount_iva)), 2'.'''),
  2316.                 'x_devolution_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  2317.                 'x_tax' => number_format(round((float) (0)), 2'.'''),
  2318.                 'x_tip_amount' => number_format(round((float) (0)), 2'.'''),
  2319.                 'product_type' => 'mpt',
  2320.             ];
  2321.             $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  2322.             $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  2323.             if ($isMulti) {
  2324.                 return $this->json($array);
  2325.             }
  2326.             $paymentResponse $aviaturPsePaymentController->sendPaymentAction$request,$session,$router,$parameterBag,$mailer,$aviaturOrderController,$array$orderProduct);
  2327.             if (!isset($paymentResponse->error)) {
  2328.                 switch ($paymentResponse->createTransactionResult->returnCode) {
  2329.                     case 'SUCCESS':
  2330.                         return $this->redirect($paymentResponse->createTransactionResult->bankURL);
  2331.                     case 'FAIL_EXCEEDEDLIMIT':
  2332.                         return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '');
  2333.                     case 'FAIL_BANKUNREACHEABLE':
  2334.                         return $this->redirect($this->generateUrl('aviatur_package_retry_secure'), '');
  2335.                     default:
  2336.                         return $this->redirect($this->generateUrl('aviatur_package_retry_secure'), '');
  2337.                 }
  2338.             } else {
  2339.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), 'Error al procesar el pago''Ocurrió un problema al intentar crear su transacción, '.$paymentResponse->error));
  2340.             }
  2341.         } elseif ('safety' == $paymentData->type) {
  2342.             $transactionUrl $this->generateUrl('aviatur_payment_safetypay', [], true);
  2343.             $array = [
  2344.                 'x_doc_num' => $customer->getDocumentnumber(),
  2345.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  2346.                 'x_first_name' => $customer->getFirstname(),
  2347.                 'x_last_name' => $customer->getLastname(),
  2348.                 'x_company' => 'Aviatur',
  2349.                 'x_email' => $customer->getEmail(),
  2350.                 'x_address' => $customer->getAddress(),
  2351.                 'x_city' => $customer->getCity()->getDescription(),
  2352.                 'x_province' => $customer->getCity()->getDescription(),
  2353.                 'x_country' => $customer->getCountry()->getDescription(),
  2354.                 'x_phone' => $customer->getPhone(),
  2355.                 'x_mobile' => $customer->getCellphone(),
  2356.                 'x_reference' => $orderInfo->products,
  2357.                 'x_booking' => $request->get('PlanID'),
  2358.                 'x_description' => 'Paquete - '.$infoDates['datesTransaction']['Description'],
  2359.                 'x_currency' => 'COP',
  2360.                 'x_total_amount' => number_format(round((float) ($x_total_amount)), 2'.'''),
  2361.                 'x_tax_amount' => number_format(round((float) (0)), 2'.'''),
  2362.                 'x_devolution_base' => number_format(round((float) (0)), 2'.'''),
  2363.                 'x_tip_amount' => number_format(round(0), 2'.'''),
  2364.                 'x_payment_data' => $paymentData->type,
  2365.                 'x_type_description' => 'package',
  2366.             ];
  2367.             $parametMerchant = [
  2368.                 'MerchantSalesID' => $array['x_reference'],
  2369.                 'Amount' => $array['x_total_amount'],
  2370.                 'transactionUrl' => $transactionUrl,
  2371.                 'dataTrans' => $array,
  2372.             ];
  2373.             $safeTyPay $aviaturSafetypayController->safetyAction($router$parameterBag$mailer$parametMerchant$array);
  2374.             if ('ok' == $safeTyPay['status']) {
  2375.                 if ('baloto' == $paymentData->type) {
  2376.                     $cash '&CountryId=COL&ChannelId=CASH';
  2377.                     $session->set($transactionId.'[mpt][retry]'0);
  2378.                     return $this->redirect($safeTyPay['response'].$cash);
  2379.                 } else {
  2380.                     return $this->redirect($safeTyPay['response']);
  2381.                 }
  2382.             } else {
  2383.                 $emissionData->x_booking $array['x_booking'];
  2384.                 $emissionData->x_first_name $array['x_first_name'];
  2385.                 $emissionData->x_last_name $array['x_last_name'];
  2386.                 $emissionData->x_doc_num $array['x_doc_num'];
  2387.                 $emissionData->x_reference $array['x_reference'];
  2388.                 $emissionData->x_description $array['x_description'];
  2389.                 $emissionData->x_total_amount $array['x_total_amount'];
  2390.                 $emissionData->x_email $array['x_email'];
  2391.                 $emissionData->x_address $array['x_address'];
  2392.                 $emissionData->x_phone $array['x_phone'];
  2393.                 $emissionData->x_type_description $array['x_type_description'];
  2394.                 $emissionData->x_resultSafetyPay $safeTyPay;
  2395.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($responsetrue);
  2396.                 $message = (new \Swift_Message())
  2397.                     ->setContentType('text/html')
  2398.                     ->setFrom($session->get('emailNoReply'))
  2399.                     ->setTo($emailNotification)
  2400.                         ->setSubject('Error Creación Token SafetyPay AssistCard'.$emissionData->x_reference)
  2401.                     ->setBody($mailInfo);
  2402.                 $mailer->send($message);
  2403.                 return $this->redirect($this->generateUrl('aviatur_package_payment_rejected_secure'));
  2404.             }
  2405.         } else {
  2406.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), '''El tipo de pago es inválido'));
  2407.         }
  2408.     }
  2409.     public function p2pCallbackAction(AviaturMailer $aviaturMailerAviaturEncoder $aviaturEncoderValidateSanctionsRenewal $aviaturValidateSanctionsOrderController $aviaturOrderControllerCustomerMethodPaymentService $customerMethodPaymentServiceSessionInterface $sessionTokenStorageInterface $tokenStorageAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBag,Request $request, \Swift_Mailer $mailer,AuthorizationCheckerInterface $authorizationChecker,TwigFolder $twigFolder,Pdf $pdf,AviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebService)
  2410.     {
  2411.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2412.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  2413.         $postData null;
  2414.         $em $this->managerRegistry;
  2415.         $transactionId $session->get($transactionIdSessionName);
  2416.         $orderProductCode $session->get($transactionId.'[mpt][order]');
  2417.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  2418.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2419.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  2420.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  2421.         $jsonSendEmail $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
  2422.         if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
  2423.             $email json_decode($jsonSendEmail->getDescription())->email->CallBack;
  2424.         }
  2425.         $reference str_replace('{"order":"'''$orderProductCode);
  2426.         $reference str_replace('","products":"''-'$reference);
  2427.         $reference str_replace('"}'''$reference);
  2428.         $references $reference;
  2429.         $bookings $orderProduct->getBooking();
  2430.         if (null != $decodedResponse) {
  2431.             $agency $orderProduct->getOrder()->getAgency();
  2432.             $twig '';
  2433.             $retryCount = (int) $session->get($transactionId.'[mpt][retry]');
  2434.             $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,false,$aviaturWebService);
  2435.             if (!isset($decodedResponse->x_response_code)) {
  2436.                 $twig 'aviatur_package_payment_rejected_secure';
  2437.             } else {
  2438.                 if (isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber)) {
  2439.                     $decodedResponse->x_response_code_case 99;
  2440.                 } else {
  2441.                     $decodedResponse->x_response_code_case $decodedResponse->x_response_code;
  2442.                 }
  2443.                 switch ($decodedResponse->x_response_code_case) {
  2444.                     case 99:
  2445.                         //rechazado cybersource
  2446.                         $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  2447.                         if ($parameters) {
  2448.                             if (== $parameters->getValue()) {
  2449.                                 if (== $decodedResponse->x_response_code) {
  2450.                                     if (isset($postData->PD->cusPOptSelected)) {
  2451.                                         if (isset($postData->PD->cusPOptSelectedStatus)) {
  2452.                                             if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  2453.                                                 $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  2454.                                                 $customerLogin $tokenStorage->getToken()->getUser();
  2455.                                                 $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2456.                                             }
  2457.                                         }
  2458.                                     }
  2459.                                     if (isset($postData->PD->savePaymProc)) {
  2460.                                         $customerLogin $tokenStorage->getToken()->getUser();
  2461.                                         $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2462.                                     }
  2463.                                 }
  2464.                             }
  2465.                         }
  2466.                         $twig 'aviatur_package_payment_rejected_secure';
  2467.                         // no break
  2468.                     case 3:// pendiente p2p
  2469.                         $twig '' != $twig $twig 'aviatur_package_payment_pending_secure';
  2470.                         $updateOrder $aviaturOrderController->updatePaymentAction($orderProduct);
  2471.                         $retryCount 1;
  2472.                         break;
  2473.                     case 0:// error p2p
  2474.                         $twig 'aviatur_package_payment_error_secure';
  2475.                         if (isset($email)) {
  2476.                             $from $session->get('emailNoReply');
  2477.                             $error $twig;
  2478.                             $subject $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
  2479.                             $body '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  2480.                             $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  2481.                         }
  2482.                         // no break
  2483.                     case 2:// rechazada p2p
  2484.                         $twig '' != $twig $twig 'aviatur_package_payment_rejected_secure';
  2485.                         if (isset($email)) {
  2486.                             $from $session->get('emailNoReply');
  2487.                             $error $twig;
  2488.                             $subject $orderProduct->getDescription().':Transacción rechazada';
  2489.                             $body '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  2490.                             $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  2491.                         }
  2492.                         break;
  2493.                     case 1:// aprobado p2p
  2494.                         $updateOrder $aviaturOrderController->updatePaymentAction($orderProduct);
  2495.                         $transactionId $session->get($transactionIdSessionName);
  2496.                         $postData json_decode($session->get($transactionId.'[mpt][detail_data_package]'));
  2497.                         if (isset($postData->PD->cusPOptSelected)) {
  2498.                             if (isset($postData->PD->cusPOptSelectedStatus)) {
  2499.                                 if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  2500.                                     $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  2501.                                     $customerLogin $tokenStorage->getToken()->getUser();
  2502.                                     $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2503.                                 }
  2504.                             }
  2505.                         }
  2506.                         if (isset($postData->PD->savePaymProc)) {
  2507.                             $customerLogin $tokenStorage->getToken()->getUser();
  2508.                             $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  2509.                         }
  2510.                         $twig 'aviatur_package_payment_success_secure';
  2511.                         //Reemplazar por consumo de reserva!!!!
  2512.                         $aviaturOrderController->updatePaymentAction($orderProductfalsenull);
  2513.                         $response $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true$aviaturWebService);
  2514.                         $result json_decode($response->getContent(), true);
  2515.                         $session->set($transactionId.'[mpt][retry]'$aviaturPaymentRetryTimes);
  2516.                         break;
  2517.                 }
  2518.             }
  2519.             $session->set($transactionId.'[mpt][retry]'$retryCount 1);
  2520.             //////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
  2521.             // if ($session->has('Marked_name') && $session->has('Marked_document')) {
  2522.             //     $product = 'Vacaciones';
  2523.             //     $aviaturValidateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
  2524.             // }
  2525.             /* Pero solo si hay condicionados (no bloqueados) y que paguen con Tarjeta */
  2526.             if ($session->has('Marked_users')) {
  2527.                 $product 'Vacaciones';
  2528.                 $aviaturValidateSanctions->sendMarkedEmail($orderProductCode$session$agency$orderProduct$transactionId$product);
  2529.             }
  2530.             ////////////////////////////////////////////////////////////////////////////////////
  2531.             return $this->redirect($this->generateUrl($twig));
  2532.         } else {
  2533.             $orderProduct->setStatus('pending');
  2534.             $em->persist($orderProduct);
  2535.             $em->flush();
  2536.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  2537.         }
  2538.     }
  2539.     public function pseCallbackAction(AviaturEncoder $aviaturEncoderPSEController $aviaturPsePaymentControllerOrderController $aviaturOrderControllerSessionInterface $sessionTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBag$transaction,Request $request,\Swift_Mailer $mailerAuthorizationCheckerInterface $authorizationCheckerPdf $pdf,AviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebService)
  2540.     {
  2541.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2542.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  2543.         $status null;
  2544.         $twig null;
  2545.         $em $this->managerRegistry;
  2546.         if ($session->has('agencyId')) {
  2547.             $agency $this->agency;
  2548.         } else {
  2549.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1);
  2550.         }
  2551.         $paymentMethod $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pse');
  2552.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findOneBy(['agency' => $agency'paymentMethod' => $paymentMethod]);
  2553.         $tranKey $paymentMethodAgency->getTrankey();
  2554.         $decodedUrl json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
  2555.         $transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
  2556.         $orders $decodedUrl['x_orders'];
  2557.         if (isset($orders['mpt'])) {
  2558.             $mptOrders explode('+'$orders['mpt']);
  2559.             $orderProductCode $mptOrders[0];
  2560.             $productId $mptOrders[0];
  2561.             $retryCount 1;
  2562.         } else {
  2563.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró identificador de la transacción'));
  2564.         }
  2565.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2566.         if (empty($orderProduct)) {
  2567.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  2568.         } else {
  2569.             if ('approved' == $orderProduct->getStatus()) {
  2570.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  2571.             } else {
  2572.                 $agency $orderProduct->getOrder()->getAgency();
  2573.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  2574.                 if (isset($decodedResponse->createTransactionResult)) {
  2575.                     $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,false$aviaturWebService);
  2576.                     $pseTransactionId $decodedResponse->createTransactionResult->transactionID;
  2577.                     $paymentResponse $aviaturPsePaymentController->pseCallbackAction$aviaturOrderController,$pseTransactionId);
  2578.                     if (!isset($paymentResponse->error)) {
  2579.                         if (!$session->has($transactionId.'[mpt][resumeView]')) {
  2580.                             $message 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
  2581.                             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra'$message));
  2582.                         }
  2583.                         $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  2584.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  2585.                         $orderProduct->setUpdatingdate(new \DateTime());
  2586.                         $em->persist($orderProduct);
  2587.                         $em->flush();
  2588.                         if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
  2589.                             switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
  2590.                                 case 'OK':
  2591.                                     $twig 'aviatur_package_payment_success_secure';
  2592.                                     $status 'approved';
  2593.                                     break;
  2594.                                 case 'PENDING':
  2595.                                     $twig 'aviatur_package_payment_pending_secure';
  2596.                                     $status 'pending';
  2597.                                     break;
  2598.                                 case 'NOT_AUTHORIZED':
  2599.                                     $twig 'aviatur_package_payment_error_secure';
  2600.                                     $status 'rejected';
  2601.                                     break;
  2602.                                 case 'FAILED':
  2603.                                     $twig 'aviatur_package_payment_error_secure';
  2604.                                     $status 'failed';
  2605.                                     break;
  2606.                             }
  2607.                             $orderProduct->setStatus($status);
  2608.                             $orderProduct->getOrder()->setStatus($status);
  2609.                             $orderProduct->setUpdatingdate(new \DateTime());
  2610.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  2611.                             $em->persist($orderProduct);
  2612.                             $em->flush();
  2613.                             if ('approved' == $status) {
  2614.                                 //Reemplazar por consumo de reserva!!!!
  2615.                                 $aviaturOrderController->updatePaymentAction($orderProductfalsenull);
  2616.                                 $response $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true$aviaturWebService);
  2617.                                 $result json_decode($response->getContent(), true);
  2618.                                 $session->set($transactionId.'[mpt][retry]'$aviaturPaymentRetryTimes);
  2619.                             }
  2620.                             return $this->redirect($this->generateUrl($twig));
  2621.                         } elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
  2622.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  2623.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor, espere
  2624.                             unos minutos y vuelva a consultar más tarde para verificar si su pago fue confirmado de
  2625.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  2626.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  2627.                             inquietudes al email mispagos@micomercio.com y preguntar por el estado de la
  2628.                             transacción <#CUS> .';
  2629.                             $orderProduct->setEmissiondata('error');
  2630.                             $orderProduct->setUpdatingdate(new \DateTime());
  2631.                             $em->persist($orderProduct);
  2632.                             $em->flush();
  2633.                             $twig 'aviatur_package_payment_error_secure';
  2634.                         }
  2635.                         if ($session->has($transactionId.'[mpt][retry]')) {
  2636.                             $session->set($transactionId.'[mpt][retry]'$retryCount 1);
  2637.                         }
  2638.                         return $this->redirect($this->generateUrl($twig));
  2639.                     } else {
  2640.                         $decodedResponse->getTransactionInformationResult $paymentResponse;
  2641.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  2642.                         $orderProduct->setUpdatingdate(new \DateTime());
  2643.                         $em->persist($orderProduct);
  2644.                         $em->flush();
  2645.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  2646.                     }
  2647.                 } else {
  2648.                     return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  2649.                 }
  2650.             }
  2651.         }
  2652.     }
  2653.     public function safetyCallbackOkAction(AviaturEncoder $aviaturEncoderSafetypayController $aviaturSafetypayControllerOrderController $aviaturOrderControllerSessionInterface $sessionTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBag,Request $request,\Swift_Mailer $mailer,AuthorizationCheckerInterface $authorizationChecker,Pdf $pdf,AviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebService)
  2654.     {
  2655.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2656.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  2657.         $status null;
  2658.         $twig null;
  2659.         $em $this->managerRegistry;
  2660.         $safeTyPay $aviaturSafetypayController->safetyok();
  2661.         if (true === $session->has($transactionIdSessionName)) {
  2662.             $transactionId $session->get($transactionIdSessionName);
  2663.             if (true === $session->has($transactionId.'[mpt][order]')) {
  2664.                 $orderProductCode $session->get($transactionId.'[mpt][order]');
  2665.                 $productId str_replace('PN'''json_decode($orderProductCode)->products);
  2666.                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2667.                 $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  2668.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  2669.                 $payError $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
  2670.                 $notifyError $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
  2671.                 if (isset($decodedResponse->payResponse->OperationResponse)) {
  2672.                     $response $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true$aviaturWebService);
  2673.                     if (== $payError) {
  2674.                         $retryCount = (int) $session->get($transactionId.'[mpt][retry]');
  2675.                         if (== $notifyError) {
  2676.                             switch ($payError) {
  2677.                                 case 0:
  2678.                                     $twig 'aviatur_package_payment_success_secure';
  2679.                                     $status 'approved';
  2680.                                     break;
  2681.                                 case 2:
  2682.                                     $twig 'aviatur_package_payment_error_secure';
  2683.                                     $status 'failed';
  2684.                                     break;
  2685.                             }
  2686.                             $orderProduct->setStatus($status);
  2687.                             $orderProduct->getOrder()->setStatus($status);
  2688.                             $orderProduct->setUpdatingdate(new \DateTime());
  2689.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  2690.                             $em->persist($orderProduct);
  2691.                             $em->flush();
  2692.                             $aviaturOrderController->updatePaymentAction($orderProduct);
  2693.                             if (== $payError) {
  2694.                                 if ('approved' == $status) {
  2695.                                     //Reemplazar por consumo de reserva!!!!
  2696.                                     $response $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true$aviaturWebService);
  2697.                                     $result json_decode($response->getContent(), true);
  2698.                                     $session->set($transactionId.'[mpt][retry]'$aviaturPaymentRetryTimes);
  2699.                                     if ('Ok' != $result['Estado'][0]) {
  2700.                                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Hubo un error en la creación de la reserva, comuníquese con nosotros por favor'));
  2701.                                     }
  2702.                                 }
  2703.                             }
  2704.                         } else {
  2705.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  2706.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor, espere
  2707.                             unos minutos y vuelva a consultar más tarde para verificar si su pago fue confirmado de
  2708.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  2709.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  2710.                             inquietudes al email mispagos@micomercio.com y preguntar por el estado de la
  2711.                             transacción <#CUS> .';
  2712.                             $orderProduct->setEmissiondata('error');
  2713.                             $orderProduct->setUpdatingdate(new \DateTime());
  2714.                             $em->persist($orderProduct);
  2715.                             $em->flush();
  2716.                             $twig 'aviatur_package_payment_error_secure';
  2717.                         }
  2718.                         $session->set($transactionId.'[mpt][retry]'$retryCount 1);
  2719.                         return $this->redirect($this->generateUrl($twig));
  2720.                     } else {
  2721.                         $decodedResponse->payResponse->OperationResponse->ListOfOperations $paymentResponse;
  2722.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  2723.                         $orderProduct->setUpdatingdate(new \DateTime());
  2724.                         $em->persist($orderProduct);
  2725.                         $em->flush();
  2726.                         return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  2727.                     }
  2728.                 } else {
  2729.                     return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción, por favor comuniquese con nosotros'));
  2730.                 }
  2731.             } else {
  2732.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  2733.             }
  2734.         } else {
  2735.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró identificador de la transacción'));
  2736.         }
  2737.     }
  2738.     public function safetyCallbackErrorAction(AviaturEncoder $aviaturEncoderSessionInterface $sessionTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryParameterBagInterface $parameterBag)
  2739.     {
  2740.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2741.         $status null;
  2742.         $em $this->managerRegistry;
  2743.         $transactionId $session->get($transactionIdSessionName);
  2744.         $retryCount = (int) $session->get($transactionId '[mpt][retry]');
  2745.         $orderProductCode json_decode($session->get($transactionId '[mpt][order]'));
  2746.         $productId str_replace('PN'''$orderProductCode->products);
  2747.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2748.         $payResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  2749.         $payRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
  2750.         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
  2751.         if ('baloto' == $payRequest->dataTransf->x_payment_data) {
  2752.             $status 'pending';
  2753.             $payResponse->dataTransf->x_response_code 100;
  2754.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
  2755.         } elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
  2756.             $status 'rejected';
  2757.             $payResponse->dataTransf->x_response_code 100;
  2758.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
  2759.         }
  2760.         $orderProduct->setStatus($status);
  2761.         $orderProduct->setUpdatingdate(new \DateTime());
  2762.         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  2763.         $order $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
  2764.         $order->setStatus($status);
  2765.         $em->persist($order);
  2766.         $em->persist($orderProduct);
  2767.         $em->flush();
  2768.         if (true === $session->has($transactionId '[mpt][order]')) {
  2769.             $orderProductCode $session->get($transactionId '[mpt][order]');
  2770.         } else {
  2771.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  2772.         }
  2773.         $session->set($transactionId '[mpt][retry]'$retryCount 1);
  2774.         return $this->redirect($this->generateUrl('aviatur_package_payment_rejected_secure'));
  2775.     }
  2776.     public function paymentOutputAction(Request $requestAviaturEncoder $aviaturEncoderTwigFolder $twigFolderSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBagAviaturLogSave $aviaturLogSave)
  2777.     {
  2778.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2779.         $clientFranquice = [];
  2780.         $paymentResume = [];
  2781.         header('Content-Type: text/html;charset=utf-8');
  2782.         $em $this->managerRegistry;
  2783.         $transactionId $session->get($transactionIdSessionName);
  2784.         $infoDates json_decode($session->get($transactionId '[mpt]' '[infoDates]'), true);
  2785.         $detail $session->get($transactionId '[mpt]' '[detail]');
  2786.         $detail_data_package json_decode($session->get($transactionId '[mpt]' '[detail_data_package]'));
  2787.         $orderProductCode json_decode($session->get($transactionId '[mpt]' '[order]'));
  2788.         $ProductInfo json_decode($session->get($transactionId '[mpt]' '[ProductInfo]'), true);
  2789.         $resumeView json_decode($session->get($transactionId '[mpt]' '[resumeView]'), true);
  2790.         $infoClient json_decode($session->get($transactionId '[mpt]' '[infoClient]'));
  2791.         $infoSelection json_decode($session->get($transactionId '[mpt]' '[infoSelection]'));
  2792.         $infoOptionals json_decode($session->get($transactionId '[mpt]' '[optionalSelection]'));
  2793.         $InfoHotel $session->get($transactionId '[mpt][InfoHotel]');
  2794.         $ProductInfo ?? null;
  2795.         $resumeView ?? null;
  2796.         $agency $this->agency;
  2797.         $agencyData = [
  2798.             'agency_name' => $agency->getName(),
  2799.             'agency_nit' => $agency->getNit(),
  2800.             'agency_phone' => $agency->getPhone(),
  2801.             'agency_email' => $agency->getMailContact(),
  2802.         ];
  2803.         $product simplexml_load_string(html_entity_decode($ProductInfo));
  2804.         $productId str_replace('PN'''$orderProductCode->products);
  2805.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2806.         $opRequestInitial json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  2807.         $opRequest $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
  2808.         $opResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  2809.         if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
  2810.             $franquiceCode str_replace(['CR_''RM_''CDNSA'], ['''''CS'], $opResponse->x_franchise);
  2811.             $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
  2812.         } else {
  2813.             $clientFranquice['description'] = 'error';
  2814.         }
  2815.         $paymentData $detail_data_package->BD;
  2816.         $emailData json_decode($orderProduct->getEmail(), true);
  2817.         if ((null != $opRequest) && (null != $opResponse)) {
  2818.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
  2819.             if (isset($opResponse->x_description)) {
  2820.                 $paymentResume = [
  2821.                     'transaction_state' => $opResponse->x_response_code,
  2822.                     'ta_transaction_state' => $opResponse->x_ta_response_code,
  2823.                     'id' => $orderProduct->getBooking(),
  2824.                     'id_context' => $opRequest->x_invoice_num,
  2825.                     'total_amount' => $opResponse->x_amount,
  2826.                     'currency' => $opResponse->x_bank_currency,
  2827.                     'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  2828.                     'iva' => $opRequest->x_tax,
  2829.                     'ip_address' => $opRequest->x_customer_ip,
  2830.                     'bank_name' => $opResponse->x_bank_name,
  2831.                     'client_franquice' => ['description' => @$clientFranquice->getDescription()],
  2832.                     'cuotas' => $opRequest->x_differed,
  2833.                     'card_num' => '************' substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  2834.                     'reference' => $opResponse->x_transaction_id,
  2835.                     'auth' => $opResponse->x_approval_code,
  2836.                     'transaction_date' => $opResponse->x_transaction_date,
  2837.                     'description' => $opResponse->x_description,
  2838.                     'reason_code' => $opResponse->x_response_reason_code,
  2839.                     'reason_description' => $opResponse->x_response_reason_text,
  2840.                     'client_names' => $opResponse->x_first_name ' ' $opResponse->x_last_name,
  2841.                     'client_email' => $opResponse->x_email,
  2842.                 ];
  2843.             } elseif (isset($opRequest->dataTransf)) {
  2844.                 if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
  2845.                     $state $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
  2846.                 if (102 == $state):
  2847.                         $state 1;
  2848.                         $reason_description 'SafetyPay recibe la confirmación del pago de un Banco Asociado';
  2849.                     elseif (101 == $state) :
  2850.                         $state 2;
  2851.                         $reason_description 'Transacción creada';
  2852.                     endif;
  2853.                     $paymentResume = [
  2854.                         'transaction_state' => $state,
  2855.                         'id' => $orderProduct->getBooking(),
  2856.                         'currency' => $opRequest->dataTransf->x_currency,
  2857.                         'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
  2858.                         'amount' => null,
  2859.                         'iva' => null,
  2860.                         'ip_address' => $opRequest->dataTransf->dirIp,
  2861.                         'airport_tax' => null,
  2862.                         'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
  2863.                         'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
  2864.                         'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
  2865.                         'description' => $opRequest->dataTransf->x_description,
  2866.                         'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
  2867.                         'reason_description' => $reason_description,
  2868.                         'client_names' => $opRequest->dataTransf->x_first_name ' ' $opRequest->dataTransf->x_last_name,
  2869.                         'client_email' => $opRequest->dataTransf->x_email,
  2870.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  2871.                         'client_franquice' => ['description' => 'SafetyPay'],
  2872.                         'id_context' => $orderProductCode->order '-' $orderProductCode->products,
  2873.                     ];
  2874.                 else :
  2875.                     $paymentResume = [
  2876.                         'transaction_state' => 2,
  2877.                         'id' => $orderProduct->getBooking(),
  2878.                         'currency' => $opRequest->dataTransf->x_currency,
  2879.                         'total_amount' => $opRequest->dataTransf->x_total_amount,
  2880.                         'amount' => null,
  2881.                         'iva' => null,
  2882.                         'ip_address' => $opRequest->dataTransf->dirIp,
  2883.                         'airport_tax' => null,
  2884.                         'reference' => $opRequest->dataTransf->x_reference,
  2885.                         'auth' => null,
  2886.                         'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
  2887.                         'description' => $opRequest->dataTransf->x_description,
  2888.                         'reason_code' => 101,
  2889.                         'reason_description' => 'Transacción creada',
  2890.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  2891.                         'client_names' => $opRequest->dataTransf->x_first_name ' ' $opRequest->dataTransf->x_last_name,
  2892.                         'client_email' => $opRequest->dataTransf->x_email,
  2893.                     ];
  2894.                 endif;
  2895.                 if ('baloto' == $opRequest->dataTransf->x_payment_data) {
  2896.                     $paymentResume['transaction_state'] = 3;
  2897.                 }
  2898.             } else {
  2899.                 $bank_info $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
  2900.                 $bank_name $bank_info->getName();
  2901.                 $clientFranquice['description'] = 'PSE';
  2902.                 $paymentResume = [
  2903.                     'transaction_state' => $opResponse->getTransactionInformationResult->responseCode ?? $opResponse->createTransactionResult->responseReasonCode,
  2904.                     'id' => $orderProduct->getBooking(),
  2905.                     'id_context' => $opRequest->reference,
  2906.                     'currency' => $opRequest->currency,
  2907.                     'total_amount' => $opRequest->totalAmount,
  2908.                     'amount' => $opRequest->devolutionBase,
  2909.                     'iva' => $opRequest->taxAmount,
  2910.                     'ip_address' => $opRequest->ipAddress,
  2911.                     'bank_name' => $bank_name,
  2912.                     'client_franquice' => $clientFranquice,
  2913.                     'reference' => $opResponse->createTransactionResult->transactionID,
  2914.                     'auth' => $opResponse->getTransactionInformationResult->trazabilityCode ?? $opResponse->createTransactionResult->trazabilityCode,
  2915.                     'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate ?? '',
  2916.                     'description' => $opRequest->description,
  2917.                     'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode ?? $opResponse->createTransactionResult->responseReasonCode,
  2918.                     'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText ?? $opResponse->createTransactionResult->responseReasonText,
  2919.                     'client_names' => $opRequest->payer->firstName ' ' $opRequest->payer->lastName,
  2920.                     'client_email' => $opRequest->payer->emailAddress,
  2921.                 ];
  2922.             }
  2923.         } else {
  2924.             $customer null;
  2925.             $paymentResume['id'] = $orderProduct->getBooking();
  2926.         }
  2927.         $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  2928.         if (false !== strpos($paymentData->first_name'***')) {
  2929.             $facturationResume = [
  2930.                 'customer_names' => $customer->getFirstname() . ' ' $customer->getLastname(),
  2931.                 'customer_address' => $customer->getAddress(),
  2932.                 'customer_doc_num' => $customer->getDocumentnumber(),
  2933.                 'customer_phone' => $customer->getPhone(),
  2934.                 'customer_email' => $customer->getEmail(),
  2935.             ];
  2936.         } else {
  2937.             $facturationResume = [
  2938.                 'customer_names' => $paymentData->first_name ' ' $paymentData->last_name,
  2939.                 'customer_address' => $paymentData->address ?? null,
  2940.                 'customer_doc_num' => $paymentData->doc_num,
  2941.                 'customer_phone' => $paymentData->phone,
  2942.                 'customer_email' => $paymentData->email ?? null,
  2943.             ];
  2944.         }
  2945.         if (false !== strpos($detail_data_package->PI->first_name_1_1'***')) {
  2946.             $detail_data_package->PI->first_name_1_1 $customer->getFirstname();
  2947.             $detail_data_package->PI->last_name_1_1 $customer->getLastname();
  2948.             $detail_data_package->PI->email_1_1 $customer->getEmail();
  2949.             $detail_data_package->PI->address_1_1 $customer->getAddress();
  2950.             $detail_data_package->CD->phone $customer->getPhone();
  2951.         }
  2952.         $clientFranquice '';
  2953.         $retryCount = (int) $session->get($transactionId '[mpt][retry]');
  2954.         $agencyFolder $twigFolder->twigFlux();
  2955.         $routeName $request->get('_route');
  2956.         $info_travelers $detail_data_package->PI;
  2957.         $emailData = [
  2958.             'product' => $product,
  2959.             'retry_count' => $retryCount,
  2960.             'paymentResume' => $paymentResume,
  2961.             'agencyData' => $agencyData,
  2962.             'order' => $orderProductCode->order,
  2963.             'products' => $orderProductCode->products,
  2964.             'Name' => $infoDates['datesTransaction']['Description'],
  2965.             'info_travelers' => (array) $detail_data_package->PI,
  2966.             'contact_phone' => $detail_data_package->CD->phone,
  2967.             'transactionID' => $transactionId,
  2968.             'infoClient' => $facturationResume,
  2969.             'dateEntry' => $infoDates['datesTransaction']['entrada'],
  2970.             'dateEnd' => $infoDates['datesTransaction']['salida'],
  2971.             'total_amount' => $infoDates['Amount'],
  2972.             'resumeView' => $resumeView,
  2973.         ];
  2974.         $urlResume $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/package/Default/resume.html.twig');
  2975.         $renderResumeView $emailData;
  2976.         if ('jetset_semana' === $agency->getAssetsFolder()) {
  2977.             $urlReturn $this->CallAPI($session$aviaturLogSave$registry'GET'$transactionId);
  2978.             $renderResumeView['urlReturn'] = $urlReturn ?? null;
  2979.         }
  2980.         $renderResumeView['infos'][0] = $emailData;
  2981.         $setResume $this->render($urlResume$renderResumeView);
  2982.         $orderProduct->setEmail(json_encode($renderResumeView));
  2983.         $orderProduct->setResume($setResume);
  2984.         $bookinData json_decode($session->get($transactionId '[mpt][resumeView]'), true);
  2985.         if (isset($bookinData['Estado'][0]) && 'OK' == mb_strtoupper($bookinData['Estado'][0])) {
  2986.             $emissionData json_decode($orderProduct->getEmissionData(), true);
  2987.             $emissionData['emission'] = $bookinData['message'][0];
  2988.             $orderProduct->setEmissionData(json_encode($emissionData));
  2989.         }
  2990.         $em->persist($orderProduct);
  2991.         $em->flush();
  2992.         return $setResume;
  2993.     }
  2994.     public function createOrderPackageAction(Request $request, \Swift_Mailer $mailerOrderController $aviaturOrderControllerAviaturEncoder $aviaturEncoderAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBagPdf $pdfAviaturLogSave $aviaturLogSave$emission trueAviaturWebService $aviaturWebService)
  2995.     {
  2996.         $env $parameterBag->get('kernel.environment');
  2997.         $projectDir $parameterBag->get('kernel.project_dir');
  2998.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2999.         $emailNotification $parameterBag->get('email_notification');
  3000.         $packageCommissionPercentage null;
  3001.         $infoRoom = [];
  3002.         $arrayAdult = [];
  3003.         $emissionData = [];
  3004.         $agentId null;
  3005.         $agentCommission null;
  3006.         $fullRequest $request;
  3007.         $isAgent false;
  3008.         $em $this->managerRegistry;
  3009.         $session $this->session;
  3010.         $agency $this->agency;
  3011.         $request $fullRequest->request;
  3012.         $transactionId $session->get($transactionIdSessionName);
  3013.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId '_isActiveQse')) {
  3014.             $nameProduct 'package';
  3015.             $user $this->getUser();
  3016.             $emailuser $user->getemail();
  3017.             $agent $user->getAgent();
  3018.             if (!empty($agent[0])) {
  3019.                 $idagent $agent[0]->getid();
  3020.                 $nombreagente $user->getFirstname() . ' ' $user->getLastname();
  3021.                 $agencyFolder $twigFolder->twigFlux();
  3022.                 $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
  3023.                 $infoQse json_decode($agentCommission->getQseproduct());
  3024.                 $infoQseNameProduct = empty($infoQse->$nameProduct) ? false $infoQse->$nameProduct;
  3025.                 $infoQse = empty($infoQse) ? false $infoQseNameProduct;
  3026.                 $idAgentCommision $agentCommission->getId();
  3027.                 $packageCommissionPercentage = (($infoQse) ? (float) $infoQse->commission_percentage 0) * 100;
  3028.                 $agentId $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  3029.                 // $parameters = json_decode($session->get($request->getHost() . '[parameters]')); // Como se tenía antes
  3030.                 $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_iva');
  3031.                 $aviaturPaymentIva = (float) $parameters->getValue();
  3032.                 $isAgent true;
  3033.             }
  3034.         }
  3035.         $agencyFolder $twigFolder->twigFlux();
  3036.         $productInfo = new PackageModel();
  3037.         $configPackageAgency $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findOneByAgency($agency);
  3038.         $hotelsInfo simplexml_load_string($session->get($transactionId '[mpt][InfoHotel]'));
  3039.         $infopackage simplexml_load_string($session->get($transactionId '[mpt][infoPackage]'));
  3040.         $OfficeId $configPackageAgency->getOfficeID();
  3041.         if ('wmcorona' == $configPackageAgency->getAgency()->getAssetsFolder()) {
  3042.             $OfficeId $configPackageAgency->getAgency()->getOfficeID();
  3043.         }
  3044.         $toMails explode(';'$configPackageAgency->getMails());
  3045.         $resumeView '';
  3046.         $infoDates json_decode($session->get($transactionId '[mpt][infoDates]'), true);
  3047.         $urlResume $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Package/Default/email.html.twig');
  3048.         $data_package json_decode($session->get($transactionId '[mpt][detail_data_package]'));
  3049.         $data $session->get($transactionId '[mpt][detail]');
  3050.         $ProviderId $session->get($transactionId '[mpt][provider]');
  3051.         $environment $env;
  3052.         $adults null;
  3053.         $children null;
  3054.         $adultsInfo null;
  3055.         $getInfoPrestador null;
  3056.         $getPrestadorOptional null;
  3057.         $infoOptional null;
  3058.         $cliente null;
  3059.         if ($fullRequest->isXmlHttpRequest()) {
  3060.             $passangersData $request->get('PI');
  3061.             $passangerNames = [];
  3062.             for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  3063.                 $passangerNames[] = mb_strtolower($passangersData['first_name_1_' $i]);
  3064.                 $passangerNames[] = mb_strtolower($passangersData['last_name_1_' $i]);
  3065.             }
  3066.             $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  3067.             if (== sizeof($nameWhitelist)) {
  3068.                 $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  3069.                 if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  3070.                     (sizeof($nameBlacklist)) ||
  3071.                     (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))
  3072.                 ) {
  3073.                     $resumeView = ['Estado' => ['ERROR'], 'Description' => 'Nombre Inválido''message' => 'Nombre Inválido'];
  3074.                     $arraydecode json_encode($resumeView);
  3075.                     $response = new Response($arraydecode);
  3076.                     $response->headers->set('Content-Type''application/json');
  3077.                     return $response;
  3078.                 }
  3079.             }
  3080.             // pago Offline
  3081.             /* Datos de Pasajeros Adultos */
  3082.             $passengerADT $request->get('PI');
  3083.             /* Datos de Cliente */
  3084.             $passengerCLI $request->get('BD');
  3085.             /* Datos de Prestador */
  3086.             $informationPrestador = [
  3087.                 'IdHotelCode' => json_decode($request->get('HotelCode')),
  3088.                 'IdPrestador' => json_decode($request->get('HotelCode')),
  3089.                 'IdBrandName' => json_decode($request->get('BrandName')),
  3090.                 'IdPrestadorNew' => json_decode($request->get('BrandCode')),
  3091.                 'TipoHabitacion' => json_decode($request->get('typeRoom')),
  3092.                 'CategoriaHabitacion' => json_decode($request->get('categoryRoom')),
  3093.                 'CantidadAdultos' => json_decode($request->get('adtCant')),
  3094.                 'CantidadNiños' => json_decode($request->get('chdCant')),
  3095.                 'AditionalRoom' => json_decode($request->get('AditionalRoom')),
  3096.                 'personTotal' => json_decode($request->get('personTotal')),
  3097.                 'ValorTotal' => json_decode($request->get('ValorTotal')),
  3098.                 'TotalADT' => json_decode($request->get('TotalADT')),
  3099.                 'personAditional' => $infoDates['personAditional'],
  3100.                 'codeBooking' => $infoDates['codeBooking'],
  3101.                 'TotalCHD' => json_decode($request->get('TotalCHD')),
  3102.                 'totalTarifas' => json_decode($request->get('totalTarifas')),
  3103.                 'tarifaReal' => json_decode($request->get('tarifaReal')),
  3104.                 'optionals' => json_decode($request->get('optionals')),
  3105.             ];
  3106.             $transaction json_decode($request->get('Transaction'), true);
  3107.             $TotalADT json_decode($request->get('TotalADT'));
  3108.             $TotalCHD json_decode($request->get('TotalCHD'));
  3109.             $amount = (int) $request->get('Amount');
  3110.             $HotelCode json_decode($request->get('HotelCode'));
  3111.             $typeRoom is_countable(json_decode($request->get('typeRoom'))) ? count(json_decode($request->get('typeRoom'))) : 0;
  3112.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($passengerCLI['id']);
  3113.             if (isset($customer) && == $customer->getAviaturClientId()) {
  3114.                 $this->createCustomer($parameterBag$aviaturWebService$mailer$session$registry$customer);
  3115.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($passengerCLI['id']);
  3116.             }
  3117.             $fromCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata($transaction['CurrencyCode']);
  3118.         } else {
  3119.             // pago Online
  3120.             /* Datos de Pasajeros Adultos */
  3121.             $passengerADT = (array) $data_package->PI;
  3122.             /* Datos de Cliente */
  3123.             $passengerCLI $data_package->BD;
  3124.             /* Datos de Prestador */
  3125.             $informationPrestador = [
  3126.                 'IdHotelCode' => $infoDates['HotelCode'],
  3127.                 'IdPrestador' => $infoDates['HotelCode'],
  3128.                 'IdBrandName' => $infoDates['BrandName'],
  3129.                 'IdPrestadorNew' => $infoDates['BrandCode'],
  3130.                 'TipoHabitacion' => $infoDates['typeRoom'],
  3131.                 'CategoriaHabitacion' => $infoDates['categoryRoom'],
  3132.                 'CantidadAdultos' => $infoDates['adtCant'],
  3133.                 'CantidadNiños' => $infoDates['chdCant'],
  3134.                 'AditionalRoom' => $infoDates['AditionalRoom'],
  3135.                 'CantAditionalRoom' => $infoDates['CantAditionalRoom'],
  3136.                 'personAditional' => $infoDates['personAditional'],
  3137.                 'codeBooking' => $infoDates['codeBooking'],
  3138.                 'AddPerson' => $infoDates['AddPerson'],
  3139.                 'personTotal' => $infoDates['personTotal'],
  3140.                 'ValorTotal' => $infoDates['ValorTotal'],
  3141.                 'TotalADT' => $infoDates['TotalADT'],
  3142.                 'TotalCHD' => $infoDates['TotalCHD'],
  3143.                 'totalTarifas' => $infoDates['totalTarifas'],
  3144.                 'tarifaReal' => $infoDates['tarifaReal'],
  3145.                 'optionals' => $infoDates['optionals'],
  3146.             ];
  3147.             $transaction $infoDates['datesTransaction'];
  3148.             $TotalADT $infoDates['TotalADT'];
  3149.             $TotalCHD $infoDates['TotalCHD'];
  3150.             $amount $infoDates['Amount'];
  3151.             $HotelCode $infoDates['HotelCode'];
  3152.             $typeRoom is_countable($infoDates['typeRoom']) ? count($infoDates['typeRoom']) : 0;
  3153.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($data_package->BD->id);
  3154.             if (isset($customer) && == $customer->getAviaturClientId()) {
  3155.                 $this->createCustomer($parameterBag$aviaturWebService$mailer$session$registry$customer);
  3156.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($data_package->BD->id);
  3157.             }
  3158.             $fromCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata($transaction['CurrencyCode']);
  3159.         }
  3160.         if ($isAgent) {
  3161.             $qseAmount $infoDates['commissionAgent'][2];
  3162.             $qseText = ('QSE (%)' == $infoDates['commissionAgent'][3]) ? 'QSE (' $packageCommissionPercentage '%)' $infoDates['commissionAgent'][3];
  3163.         }
  3164.         if (false !== strpos($passengerADT['first_name_1_1'], '***')) {
  3165.             $passengerADT['first_name_1_1'] = $customer->getFirstname();
  3166.             $passengerADT['last_name_1_1'] = $customer->getLastname();
  3167.             $passengerADT['email_1_1'] = $customer->getEmail();
  3168.             $passengerADT['address_1_1'] = $customer->getAddress();
  3169.         }
  3170.         $cliente = [
  3171.             'Id' => $customer->getAviaturclientid(),
  3172.             'Name' => $customer->getFirstname(),
  3173.             'Last_name' => $customer->getLastname(),
  3174.             'address' => $customer->getAddress(),
  3175.             'phone' => $customer->getPhone(),
  3176.             'email' => $customer->getEmail(),
  3177.             'doc_num' => $customer->getDocumentNumber(),
  3178.         ];
  3179.         if ('aviatur' === $agency->getAssetsFolder()) {
  3180.             if (false !== strpos($transaction['ProductName'], 'Crucero')) {
  3181.                 $toMails null;
  3182.                 $toMails[] = 'julieth.cotrino@aviatur.com';
  3183.             } /* elseif (mb_strtoupper((string) $infopackage->TPA_Extensions->ProductInfo->ClaseServicio) == 'I') {
  3184.               $toMails[] = 'j_uriza@aviatur.com';
  3185.               $toMails[] = 'operadorbogint@aviatur.com';
  3186.               $toMails[] = 'cc_diaz@aviatur.com';
  3187.               } elseif (mb_strtoupper((string) $infopackage->TPA_Extensions->ProductInfo->ClaseServicio) == 'N') {
  3188.               $toMails[] = 'operadorbognal@aviatur.com';
  3189.               $toMails[] = 'f_arias@aviatur.com';
  3190.               } */
  3191.         }
  3192.         if ($session->has($transactionId '[mpt][exchangeValues]')) {
  3193.             $trm $session->get('[mpt][finantial_rate]');
  3194.         } else {
  3195.             $trm 1;
  3196.         }
  3197.         $AmountTotal $infoDates['AmountTotal'];
  3198.         $infoProducto = [
  3199.             'ProductId' => $transaction['IdPackage'],
  3200.             'ProductName' => $transaction['ProductName'],
  3201.             'LongDescription' => $transaction['Description'],
  3202.             'CiudadDestino' => $transaction['CodeCiudad'],
  3203.             'UnitCostValue' => $transaction['UnitCostValue'],
  3204.             'UnitCostName' => $transaction['UnitCostName'],
  3205.             'CodeIATA' => $transaction['CurrencyCode'],
  3206.             'CurrencyName' => $fromCurrency->getDescription(),
  3207.             'Noches' => $transaction['days'],
  3208.             'FechaInicial' => str_replace('/''-'$transaction['entrada']),
  3209.             'FechaFinal' => str_replace('/''-'$transaction['salida']),
  3210.             'TipoProducto' => $transaction['TipoProducto'],
  3211.             'CurrencyCodeEx' => $transaction['CurrencyCode'],
  3212.             'CurrencyNameEx' => $fromCurrency->getDescription(),
  3213.             'TasaCambioEx' => ('COP' == $transaction['CurrencyCode']) ? $trm,
  3214.             'ProviderId' => $ProviderId,
  3215.             'TipoVenta' => $transaction['FormaVenta'],
  3216.             'SesionId' => $transactionId,
  3217.             'Ref_externa' => null,
  3218.         ];
  3219.         if ($session->has('whitemark')) {
  3220.             $infoProducto['Ref_externa'] = $session->get('whitemark');
  3221.         }
  3222.         $ProductInfo $productInfo->getInfoProducto($infoProducto);
  3223.         $ProductInfo preg_replace('/&(?!#?[a-z0-9]+;)/''y'$ProductInfo);
  3224.         /* ---------------- informacion del prestador ------------  */
  3225.         for ($j 0$j $typeRoom; ++$j) {
  3226.             if ('undefined' == $informationPrestador['AditionalRoom'][$j] || 'null' == $informationPrestador['AditionalRoom'][$j]) {
  3227.                 $informationPrestador['AditionalRoom'][$j] = 'false';
  3228.             }
  3229.             $infoRoom[$j] = [
  3230.                 'IdHotelCode' => $informationPrestador['IdHotelCode'][$j],
  3231.                 'IdPrestador' => (== $informationPrestador['IdPrestadorNew'][$j]) ? $informationPrestador['IdBrandName'][$j] : $informationPrestador['IdPrestador'][$j],
  3232.                 'IdPrestadorNew' => 0,
  3233.                 'TipoHabitacion' => $informationPrestador['TipoHabitacion'][$j],
  3234.                 'CategoriaHabitacion' => $informationPrestador['CategoriaHabitacion'][$j],
  3235.                 'CantidadNiños' => $informationPrestador['CantidadNiños'][$j],
  3236.                 'CantidadAdultos' => $informationPrestador['CantidadAdultos'][$j],
  3237.                 'NumeroPasajeros' => $informationPrestador['personTotal'][$j],
  3238.                 'AceptaAdicional' => (!= $informationPrestador['personAditional'][$j]) ? 'true' 'false',
  3239.                 'ValorTotal' => $informationPrestador['ValorTotal'][$j],
  3240.                 'totalTarifas' => (array) $informationPrestador['totalTarifas'][$j],
  3241.                 'tarifaReal' => (array) $informationPrestador['tarifaReal'][$j],
  3242.                 'CodeIATA' => $transaction['CurrencyCode'],
  3243.                 'LifeTimeId' => $informationPrestador['codeBooking'][$j],
  3244.             ];
  3245.         }
  3246.         $uniqueHotel array_unique($HotelCode);
  3247.         $arrayTarifa = [];
  3248.         $ValueOptionals $session->get($transactionId '[mpt]' '[ValueOptionals]');
  3249.         $optionals explode('*'substr($ValueOptionals0, -1));
  3250.         $infoOptionals simplexml_load_string($session->get($transactionId '[mpt]' '[infoOptionals]'));
  3251.         $contador 0;
  3252.         foreach ($uniqueHotel as $keyNew => $value_array) {
  3253.             $IdPrestadorNew $infoRoom[$keyNew]['IdPrestadorNew'];
  3254.             $getInfoPrestador[$keyNew] = '<objPrestadores_RQ>' $productInfo->getObjPrestadores_RQ($infoRoom[$keyNew]) . '<Acomodacion>';
  3255.             foreach ($infoRoom as $keyRoom => $value_room) {
  3256.                 if ($uniqueHotel[$keyNew] == $infoRoom[$keyRoom]['IdHotelCode']) {
  3257.                     $TipoHabitacion $infoRoom[$keyRoom]['TipoHabitacion'];
  3258.                     $CategoriaHabitacion $infoRoom[$keyRoom]['CategoriaHabitacion'];
  3259.                     $CodeIATA $infoRoom[$keyRoom]['CodeIATA'];
  3260.                     //$getInfoPrestador[$keyNew] .= "<objAcomodacion_RQ>" . $productInfo->getObjAcomodacion_RQ($infoRoom[$keyRoom]) . "<Tarifas>";
  3261.                     $getInfoPrestador[$keyNew] .= '<objAcomodacion_RQ>' $productInfo->getObjAcomodacion_RQ($infoRoom[$keyRoom]);
  3262.                     if ($isAgent) {
  3263.                         $baseQse round($qseAmount / ($aviaturPaymentIva));
  3264.                         $taxQse round($qseAmount $baseQse);
  3265.                         $arrayQSE = [
  3266.                             'CodigoFee' => 'GV057',
  3267.                             'BaseFee' => (int) $baseQse,
  3268.                             'PorcentajeIVA' => ($aviaturPaymentIva 100),
  3269.                             'TaxFee' => (int) $taxQse,
  3270.                             'TotalFee' => (int) $qseAmount,
  3271.                         ];
  3272.                         $getInfoPrestador[$keyNew] .= '<objFee_RQ>' $productInfo->getObjValorQse($arrayQSE) . '</objFee_RQ>';
  3273.                     }
  3274.                     $getInfoPrestador[$keyNew] .= '<Tarifas>';
  3275.                     $array json_decode(json_encode($value_room['totalTarifas']), true);
  3276.                     $arrayReal json_decode(json_encode($value_room['tarifaReal']), true);
  3277.                     $ADTotal $array['ADTotal'];
  3278.                     if (isset($array['CHDTotal'])) {
  3279.                         $CHDTotal $array['CHDTotal'];
  3280.                         if (!= $array['CHDTotal']) {
  3281.                             $Age $array['ageMinCHD'];
  3282.                             $AgeEnd $array['ageMaxCHD'];
  3283.                         }
  3284.                     }
  3285.                     foreach ($arrayReal as $keyRate => $Rate) {
  3286.                         $dateVar $keyRate;
  3287.                         $arrayTarifa null;
  3288.                         if (!= $Rate && false === strpos($dateVar'DAYS')) {
  3289.                             if (isset($arrayReal['DAYS_' $dateVar]) && != $arrayReal['DAYS_' $dateVar]) {
  3290.                                 if ('ADT' == $dateVar || 'ADN' == $dateVar || 'ADF' == $dateVar || 'ANF' == $dateVar || 'ADD' == $dateVar || 'AAN' == $dateVar || 'AFN' == $dateVar) {
  3291.                                     $NroPersonas = ('ADD' == $dateVar || 'AAN' == $dateVar || 'AFN' == $dateVar) ? $ADTotal;
  3292.                                     $arrayTarifa = [
  3293.                                         'FareId' => $array['Count' $dateVar],
  3294.                                         'TipoPersona' => $dateVar,
  3295.                                         'Valor' => $Rate,
  3296.                                         'Noches' => $arrayReal['DAYS_' $dateVar],
  3297.                                         'NroPersonas' => $NroPersonas,
  3298.                                     ];
  3299.                                 }
  3300.                                 if ('CHD' == $dateVar || 'CHN' == $dateVar || 'CHF' == $dateVar || 'CFN' == $dateVar) {
  3301.                                     $NroPersonas $CHDTotal;
  3302.                                     $arrayTarifa = [
  3303.                                         'FareId' => $array['Count' $dateVar],
  3304.                                         'TipoPersona' => $dateVar,
  3305.                                         'Valor' => (int) ($Rate $NroPersonas),
  3306.                                         'NroPersonas' => $NroPersonas,
  3307.                                         'Noches' => $arrayReal['DAYS_' $dateVar],
  3308.                                         'Age' => (int) $Age,
  3309.                                         'AgeEnd' => (int) $AgeEnd,
  3310.                                     ];
  3311.                                 }
  3312.                                 $getInfoPrestador[$keyNew] .= '<objTarifas_RQ>' $productInfo->getObjTarifas_RQ($arrayTarifa) . '</objTarifas_RQ>';
  3313.                             }
  3314.                         }
  3315.                     }
  3316.                     $getInfoPrestador[$keyNew] .= '</Tarifas></objAcomodacion_RQ>';
  3317.                 }
  3318.             }
  3319.             $getInfoPrestador[$keyNew] .= '</Acomodacion></objPrestadores_RQ>';
  3320.         }
  3321.         $infoPrestador implode(''$getInfoPrestador);
  3322.         /* ------------------ Informacion de los opcionales -------------- */
  3323.         if (!= $ValueOptionals) {
  3324.             foreach ($optionals as $valueOptionals) {
  3325.                 $dateOptionals explode('|'$valueOptionals);
  3326.                 foreach ($infoOptionals->Package as $Opcionales) {
  3327.                     foreach ($Opcionales->TPA_Extensions->ServiciosOpcionales as $ServiciosOpcionales) {
  3328.                         foreach ($ServiciosOpcionales->TarifasServiciosOpc->Tarifas as $Tarifas) {
  3329.                             if ($Tarifas->FareId == $dateOptionals[5]) {
  3330.                                 $arrayPrestador[] = [
  3331.                                     'IdPrestadorNew' => $IdPrestadorNew,
  3332.                                     'IdPrestador' => (int) $Tarifas->IdPrestador,
  3333.                                 ];
  3334.                                 $getPrestadorOptional[] = '<objPrestadores_RQ>' $productInfo->getObjPrestadores_RQ($arrayPrestador[$contador]) . '<Acomodacion>';
  3335.                                 $PrestadorAcomodacion[] = [
  3336.                                     'TipoHabitacion' => $TipoHabitacion,
  3337.                                     'CategoriaHabitacion' => $CategoriaHabitacion,
  3338.                                     'CantidadNiños' => 0,
  3339.                                     'CantidadAdultos' => $dateOptionals[2],
  3340.                                     'AceptaAdicional' => (string) ($Tarifas->Additional 0) ? 'true' 'false',
  3341.                                     'NumeroPasajeros' => $dateOptionals[2],
  3342.                                     'CodeIATA' => $CodeIATA,
  3343.                                     'ValorTotal' => (int) $Tarifas->FareSale,
  3344.                                 ];
  3345.                                 $getPrestadorOptional[] .= '<objAcomodacion_RQ>' $productInfo->getObjAcomodacion_RQ($PrestadorAcomodacion[$contador]);
  3346.                                 if ($isAgent) {
  3347.                                     $baseQse round($qseAmount / ($aviaturPaymentIva));
  3348.                                     $taxQse round($qseAmount $baseQse);
  3349.                                     $arrayQSE = [
  3350.                                         'CodigoFee' => 'GV057',
  3351.                                         'BaseFee' => (int) $baseQse,
  3352.                                         'PorcentajeIVA' => $aviaturPaymentIva 100,
  3353.                                         'TaxFee' => (int) $taxQse,
  3354.                                         'TotalFee' => (int) $qseAmount,
  3355.                                     ];
  3356.                                     $getPrestadorOptional[] .= '<objFee_RQ>' $productInfo->getObjValorQse($arrayQSE) . '</objFee_RQ>';
  3357.                                 }
  3358.                                 $getPrestadorOptional[] .= '<Tarifas>';
  3359.                                 $arrayOptionals = [
  3360.                                     'FareId' => (int) $Tarifas->FareId,
  3361.                                     'TipoPersona' => $Tarifas->TypeOfPerson,
  3362.                                     'Valor' => (int) $Tarifas->FareSale,
  3363.                                     'Noches' => $transaction['days'],
  3364.                                     'NroPersonas' => $dateOptionals[2],
  3365.                                 ];
  3366.                                 $getPrestadorOptional[] .= '<objTarifas_RQ>' $productInfo->getObjTarifas_RQ($arrayOptionals) . '</objTarifas_RQ>';
  3367.                                 ++$contador;
  3368.                             }
  3369.                         }
  3370.                     }
  3371.                 }
  3372.                 $getPrestadorOptional[] .= '</Tarifas></objAcomodacion_RQ>';
  3373.                 $getPrestadorOptional[] .= '</Acomodacion></objPrestadores_RQ>';
  3374.             }
  3375.             $infoOptional implode(''$getPrestadorOptional);
  3376.             $infoPrestador $infoPrestador $infoOptional;
  3377.         }
  3378.         $prestadorInfo '<Prestador>' $infoPrestador '</Prestador>';
  3379.         $infoClient $productInfo->getInfoClient($cliente);
  3380.         /* ------------------ Informacion de los pasajeros -------------- */
  3381.         for ($i 1$i <= ($TotalADT $TotalCHD); ++$i) {
  3382.             if ('ADT' == $passengerADT['passanger_type_1_' $i]) {
  3383.                 if (335 == $passengerADT['gender_1_' $i]) {
  3384.                     $type 'M';
  3385.                 } else {
  3386.                     $type 'F';
  3387.                 }
  3388.                 $arrayAdult[$i] = [
  3389.                     'Passenger_number' => $i,
  3390.                     'Type' => $type,
  3391.                     'First_name' => $passengerADT['first_name_1_' $i],
  3392.                     'First_last_name' => $passengerADT['last_name_1_' $i],
  3393.                     'Document_type' => $passengerADT['doc_type_1_' $i],
  3394.                     'Document_id' => $passengerADT['doc_type_1_' $i],
  3395.                     'Document_number' => $passengerADT['doc_num_1_' $i],
  3396.                     'Nationality' => $passengerADT['nationality_1_' $i],
  3397.                     'birthday' => $passengerADT['birthday_1_' $i],
  3398.                 ];
  3399.                 $adults $productInfo->getInfoPassengers($arrayAdult[$i]) . $adults;
  3400.             }
  3401.         }
  3402.         $adultsInfo '<Pasajeros>' $adults '</Pasajeros>';
  3403.         $arrayChildren null;
  3404.         for ($j 1$j <= ($TotalADT $TotalCHD); ++$j) {
  3405.             if ('CHD' == $passengerADT['passanger_type_1_' $j]) {
  3406.                 if (335 == $passengerADT['gender_1_' $j]) {
  3407.                     $type 'M';
  3408.                 } else {
  3409.                     $type 'F';
  3410.                 }
  3411.                 $arrayChildren[$j] = [
  3412.                     'Passenger_number' => $j,
  3413.                     'Type' => $type,
  3414.                     'First_name' => $passengerADT['first_name_1_' $j],
  3415.                     'First_last_name' => $passengerADT['last_name_1_' $j],
  3416.                     'Document_type' => $passengerADT['doc_type_1_' $j],
  3417.                     'Document_id' => $passengerADT['doc_type_1_' $j],
  3418.                     'Document_number' => $passengerADT['doc_num_1_' $j],
  3419.                     'Nationality' => $passengerADT['nationality_1_' $j],
  3420.                     'birthday' => $passengerADT['birthday_1_' $j],
  3421.                 ];
  3422.                 $children $productInfo->getInfoPassengers($arrayChildren[$j]) . $children;
  3423.             }
  3424.         }
  3425.         if ($TotalCHD 0) {
  3426.             $infoPasseenger '<Pasajeros>' $adults $children '</Pasajeros>';
  3427.         } else {
  3428.             $infoPasseenger '<Pasajeros>' $adults '</Pasajeros>';
  3429.         }
  3430.         $infoVendedor $productInfo->getInfoVendedor($OfficeId);
  3431.         $xmlTemplateHead "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
  3432.             '<soap:Body>';
  3433.         $xmlTemplateBody utf8_encode("<CrearSolicitudPaquetes xmlns='http://www.aviatur.com.co/'>"
  3434.             '<Request>'
  3435.             $ProductInfo
  3436.             $prestadorInfo
  3437.             $infoClient
  3438.             $infoPasseenger
  3439.             $infoVendedor
  3440.             '</Request>'
  3441.             '</CrearSolicitudPaquetes>');
  3442.         $xmlTemplatefooter '</soap:Body>'
  3443.             '</soap:Envelope>';
  3444.         $emissionData['xml'] = $xmlTemplateBody;
  3445.         $emissionData['agencyId'] = $session->get('agencyId');
  3446.         $emissionData['infoDates'] = $infoDates;
  3447.         $DataEmail = [
  3448.             'ProductInfo' => simplexml_load_string(utf8_encode($ProductInfo)),
  3449.             'clientInformation' => ['infoClient' => simplexml_load_string($infoClient), 'documentNumber' => $customer->getDocumentNumber(), 'address' => $customer->getAddress(), 'phone' => $customer->getPhone(), 'email' => $customer->getEmail()],
  3450.             'informationPrestador' => $informationPrestador,
  3451.             'passengerADT' => $arrayAdult,
  3452.             'passengerCHD' => $arrayChildren,
  3453.             'amount' => $amount,
  3454.             'AmountTotal' => $AmountTotal,
  3455.         ];
  3456.         $emissionData['emailData'] = $DataEmail;
  3457.         if ($session->has($transactionId '[mpt][order]')) {
  3458.             $orderProductCode $session->get($transactionId '[mpt][order]');
  3459.             $productId str_replace('PN'''json_decode($orderProductCode)->products);
  3460.             $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3461.             $orderProduct->setEmissiondata(json_encode($emissionData));
  3462.             $em->persist($orderProduct);
  3463.             $em->flush();
  3464.         }
  3465.         $response true;
  3466.         if (true === $emission) {
  3467.             $this->CallAPI($session$aviaturLogSave$registry'POST'$transactionId);
  3468.             $objectTemplate = \simplexml_load_string($xmlTemplateBody);
  3469.             $urlEmission $configPackageAgency->getWsUrl();
  3470.             $client = new \SoapClient($urlEmission '?wsdl', ['trace' => 1]);
  3471.             try {
  3472.                 $aviaturLogSave->logSave(print_r($xmlTemplateHead $xmlTemplateBody $xmlTemplatefootertrue), 'CrearSolicitudPaquetes''RQ'$transactionId);
  3473.                 $response $client->__doRequest($xmlTemplateHead $xmlTemplateBody $xmlTemplatefooter$urlEmission'http://www.aviatur.com.co/CrearSolicitudPaquetes'1);
  3474.                 //$response = str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\CrearSolicitudPaquetes__RS.xml'));
  3475.                 $aviaturLogSave->logSave(print_r($responsetrue), 'CrearSolicitudPaquetes''RS'$transactionId);
  3476.                 $xml str_replace('&lt;''<'$response);
  3477.                 $xml str_replace('&gt;''>'$xml);
  3478.                 $xml str_replace('<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>'''$xml);
  3479.                 $xml str_replace('</soap:Body></soap:Envelope>'''$xml);
  3480.                 $xmlResponse = \simplexml_load_string($xml);
  3481.                 $estado = (string) $xmlResponse->CrearSolicitudPaquetesResult->RESPUESTA->ESTADO;
  3482.                 $descriptionError = (string) $xmlResponse->CrearSolicitudPaquetesResult->RESPUESTA->DESC_ERROR;
  3483.                 $respuesta = (string) $xmlResponse->CrearSolicitudPaquetesResult->RESPUESTA->MESSAGE;
  3484.                 $soapFault false;
  3485.             } catch (\SoapFault $e) {
  3486.                 var_dump($e->faultcode);
  3487.                 var_dump($e->faultstring);
  3488.                 $soapFault true;
  3489.                 $descriptionError 'Error de servicio';
  3490.                 $estado 'ERROR';
  3491.                 $respuesta 'ERROR';
  3492.             }
  3493.             if (null == $customer) {
  3494.                 $clientInformation = ['infoClient' => simplexml_load_string($infoClient), 'documentNumber' => $passengerCLI['doc_num'], 'address' => $passengerCLI['address'], 'phone' => $passengerCLI['phone'], 'email' => $passengerCLI['email']];
  3495.             } else {
  3496.                 $clientInformation = ['infoClient' => simplexml_load_string($infoClient), 'documentNumber' => $customer->getDocumentNumber(), 'address' => $customer->getAddress(), 'phone' => $customer->getPhone(), 'email' => $customer->getEmail()];
  3497.             }
  3498.             $resumeView = ['Estado' => $estado'Description' => $descriptionError'message' => $respuesta];
  3499.             $session->set($transactionId '[mpt][resumeView]'json_encode($resumeView));
  3500.             $session->set($transactionId '[mpt][ProductInfo]'json_encode(utf8_encode($ProductInfo)));
  3501.             $session->set($transactionId '[mpt][infoClient]'json_encode($clientInformation));
  3502.             $session->set($transactionId '[mpt][infoSelection]'json_encode($informationPrestador));
  3503.             $session->set($transactionId '[mpt][optionalSelection]'json_encode($informationPrestador['optionals']));
  3504.             $hotelInfo '';
  3505.             $emailData = [
  3506.                 'resumeView' => $resumeView,
  3507.                 'ProductInfo' => simplexml_load_string(utf8_encode($ProductInfo)),
  3508.                 'clientInformation' => $clientInformation,
  3509.                 'informationPrestador' => $informationPrestador,
  3510.                 'optionals' => $informationPrestador['optionals'],
  3511.                 'passengerADT' => $arrayAdult,
  3512.                 'passengerCHD' => $arrayChildren,
  3513.                 'amount' => $amount,
  3514.                 'AmountTotal' => $AmountTotal,
  3515.                 'agencyData' => $agency,
  3516.             ];
  3517.             if ($isAgent) {
  3518.                 $emailData['qseAmount'] = $qseAmount;
  3519.                 $emailData['qseText'] = $qseText;
  3520.             }
  3521.             if ($session->has($transactionId '[mpt]' '[infoCaution]')) {
  3522.                 $emailData['infoCaution'] = json_decode($session->get($transactionId '[mpt]' '[infoCaution]'));
  3523.             }
  3524.             foreach ($emailData['informationPrestador']['IdPrestador'] as $idprestador) {
  3525.                 foreach ($hotelsInfo->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $hotelInfo) {
  3526.                     if ($idprestador == $hotelInfo->Identity['HotelCode']) {
  3527.                         $emailData['informationPrestador']['nameHotel'][] = $hotelInfo->Identity['HotelName'];
  3528.                     }
  3529.                 }
  3530.             }
  3531.             $postData $request->all();
  3532.             $publicKey $aviaturEncoder->aviaturRandomKey();
  3533.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postData), $publicKey);
  3534.             $formUserInfo = new FormUserInfo();
  3535.             $formUserInfo->setInfo($encodedInfo);
  3536.             $formUserInfo->setPublicKey($publicKey);
  3537.             $em->persist($formUserInfo);
  3538.             $em->flush();
  3539.             $session->set($transactionId '[mpt][user_info]'$formUserInfo->getId());
  3540.             if ('false' == (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta) {
  3541.                 if (true !== $session->has($transactionId '[mpt][order]')) {
  3542.                     if (true === $session->has($transactionId '[mpt][detail]')) {
  3543.                         $session->set($transactionId '[mpt][detail_data_package]'json_encode($postData));
  3544.                         $billingData $request->get('BD');
  3545.                         $isFront $session->has('operatorId');
  3546.                         if ($isFront) {
  3547.                             $customer $billingData;
  3548.                             $customer['isFront'] = true;
  3549.                             $status 'B2T';
  3550.                         } else {
  3551.                             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  3552.                             $status 'waiting';
  3553.                         }
  3554.                         if (isset($agency)) {
  3555.                             $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('MPT');
  3556.                             if ($isFront) {
  3557.                                 $orderIdentifier '{order_product_reservation}';
  3558.                             } else {
  3559.                                 $orderIdentifier '{order_product_num}';
  3560.                             }
  3561.                             $order $aviaturOrderController->createAction($agency$customer$productType$orderIdentifier$status);
  3562.                             $orderId str_replace('ON'''$order['order']);
  3563.                             $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  3564.                             $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId '[mpt][user_info]'));
  3565.                             $formUserInfo->setOrder($orderEntity);
  3566.                             $em->persist($formUserInfo);
  3567.                             $em->flush();
  3568.                             /*
  3569.                              * Agent Octopus
  3570.                              * Agent Transaction, Save commission QSE or Percentage
  3571.                              */
  3572.                             if ($isAgent) {
  3573.                                 $orderProductCode $session->get($transactionId '[mpt][order]');
  3574.                                 $productId str_replace('PN'''json_decode($orderProductCode)->products);
  3575.                                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3576.                                 $arrayInfo $infoDates['commissionAgent'];
  3577.                                 $agentTransaction = new AgentTransaction();
  3578.                                 $agentTransaction->setAgent($agentId);
  3579.                                 $agentTransaction->setAgentCommission($agentCommission);
  3580.                                 $agentTransaction->setOrderProduct($orderProduct);
  3581.                                 $agentTransaction->setCommissionvalue(round((float) ($arrayInfo[4])));
  3582.                                 $agentTransaction->setAmountQse($arrayInfo[6]['amountQse']);
  3583.                                 $agentTransaction->setCommissionQse($arrayInfo[6]['commissionQse']);
  3584.                                 $agentTransaction->setAmountTarifa($arrayInfo[6]['amountTa']);
  3585.                                 $agentTransaction->setCommissionTarifa($arrayInfo[6]['commissionTa']);
  3586.                                 $agentTransaction->setAmountProduct($arrayInfo[6]['amountProduct']);
  3587.                                 $agentTransaction->setPercentageTarifa($arrayInfo[6]['percentageTarifa']);
  3588.                                 $em->persist($agentTransaction);
  3589.                                 $em->flush();
  3590.                             }
  3591.                         } else {
  3592.                             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró la agencia con el dominio: ' $request->getHost()));
  3593.                         }
  3594.                     } else {
  3595.                         return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId '[availability_url]'), '''No encontramos información del detalle de su búsqueda, por favor vuelva a intentarlo')]);
  3596.                     }
  3597.                 }
  3598.                 $arraydecode json_encode($resumeView);
  3599.                 $response = new Response($arraydecode);
  3600.                 $response->headers->set('Content-Type''application/json');
  3601.             } else {
  3602.                 $response $this->redirect($this->generateUrl('aviatur_package_resume_secure'));
  3603.             }
  3604.             $orderProductCode $session->get($transactionId '[mpt][order]');
  3605.             $productId str_replace('PN'''json_decode($orderProductCode)->products);
  3606.             $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3607.             if ($session->has('promotionalCodePackage_code') && '0' !== $session->get('promotionalCodePackage_code')) {
  3608.                 $promotionalCodePackage $em->getRepository(\Aviatur\PackageBundle\Entity\PromotionalCodePackage::class)->findOneByCode($session->get('promotionalCodePackage_code'));
  3609.                 if ($promotionalCodePackage) {
  3610.                     $promotionalCodePackage->setOrderproductid($orderProduct->getId());
  3611.                 }
  3612.             }
  3613.             if ('dev' != $environment && isset($infopackage->TPA_Extensions->ProductInfo->Email) && !empty($infopackage->TPA_Extensions->ProductInfo->Email)) {
  3614.                 foreach (explode(';'$infopackage->TPA_Extensions->ProductInfo->Email) as $emails) {
  3615.                     $toMails[] = $emails;
  3616.                 }
  3617.             }
  3618.          
  3619.             $bccMails = [$emailNotification];
  3620.             if ($session->has('whitemark')) {
  3621.                 if ('' != $session->get('whitemarkMail')) {
  3622.                     $bccMails[] = $session->get('whitemarkMail');
  3623.                     $bccMails[] = 'agenciasenlinea@aviatur.com';
  3624.                     $bccMails[] = 'sebastian.huertas@aviatur.com';
  3625.                 }
  3626.             } else {
  3627.                 $bccMails[] = $agency->getMailcontact();
  3628.                 $bccMails[] = 'soptepagelectronic@aviatur.com';
  3629.             }
  3630.             if ('ERROR' == $estado || $soapFault) {
  3631.                 $status 'waiting';
  3632.                 if ('true' == (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta) {
  3633.                     $status 'approved';
  3634.                 }
  3635.                 $toMails $bccMails;
  3636.                 $mailInfo print_r($descriptionErrortrue) . '<br>' print_r($objectTemplatetrue);
  3637.                 $messageEmail = (new \Swift_Message())
  3638.                     ->setContentType('text/html')
  3639.                     ->setFrom($session->get('emailNoReply'))
  3640.                     ->setTo($toMails)
  3641.                     ->setBcc([$emailNotification'sebastian.huertas@aviatur.com'])
  3642.                     ->setSubject('Error al Crear Paquete ' $orderProductCode)
  3643.                     ->setBody($mailInfo);
  3644.                 $mailer->send($messageEmail);
  3645.                 $OrderIdAviatur 'ErrorToCreate';
  3646.                 $Productidaviatur $OrderIdAviatur;
  3647.             } else {
  3648.                 if ($session->has($transactionId '[mpt][order]') && !empty($orderProductCode)) {
  3649.                     $emailData['resumeView']['message'] = $emailData['resumeView']['message'] . ' - ' json_decode($orderProductCode)->products;
  3650.                 }
  3651.                 /**
  3652.                  * Agente Octopus
  3653.                  * Cambiar logo Correo Gracias por tu compra.
  3654.                  */
  3655.                 $isAgent false;
  3656.                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
  3657.                     $user $this->getUser();
  3658.                     $agent $user->getAgent();
  3659.                     $agency $this->agency;
  3660.                     if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
  3661.                         $planSepare $request->get('PS');
  3662.                         if (isset($planSepare['slPlanSepare']) && 'on' == $planSepare['slPlanSepare']) {
  3663.                             $emailData['planSepare'] = true;
  3664.                         }
  3665.                         $isAgent true;
  3666.                         $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  3667.                         $idAgentLogo $agent->getId();
  3668.                         $folderImg 'assets/octopus_assets/img/custom/logoAgent/' $idAgentLogo '.png';
  3669.                         $domain 'https://' $agency->getDomain();
  3670.                         $folderLogoAgent $domain '/' $folderImg;
  3671.                         if (file_exists($folderImg)) {
  3672.                             $emailData['imgLogoAgent'] = $folderLogoAgent;
  3673.                         }
  3674.                     }
  3675.                 }
  3676.                 $emissionData['emission'] = $respuesta;
  3677.                 $this->CallAPI($session$aviaturLogSave$registry'CONT'$transactionId);
  3678.                 $status 'approved_package';
  3679.                 if ('true' == (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta) {
  3680.                     $status 'approved';
  3681.                 }
  3682.                 $packageFile $projectDir '/app/serviceLogs/packageReservation/' $respuesta '.pdf';
  3683.                 $pdf->generateFromHtml($this->renderView($urlResume$emailData), $packageFile, ['encoding' => 'utf-8']);
  3684.                 $mailInfo print_r($descriptionErrortrue) . '<br>' print_r($objectTemplatetrue);
  3685.                 $subject $orderProduct->getOrder()->getAgency()->getName();
  3686.                 if ($session->has('whitemark')) {
  3687.                     $subject 'Marca Blanca ' $session->get('whitemarkName');
  3688.                 }
  3689.             
  3690.                 $messageEmail = (new \Swift_Message())
  3691.                     ->setContentType('text/html')
  3692.                     ->setFrom($session->get('emailNoReply'))
  3693.                     ->setTo($cliente['email'])
  3694.                     ->setCC($toMails)
  3695.                     ->setBcc($bccMails)
  3696.                     ->attach(\Swift_Attachment::fromPath($packageFile))
  3697.                     ->setSubject($subject ' Reserva de Paquete Creada ' $respuesta)
  3698.                     ->setBody($this->renderView($urlResume$emailData));
  3699.                 $mailer->send($messageEmail);
  3700.                 unlink($packageFile);
  3701.                 $respuestas explode('-'$respuesta);
  3702.                 $OrderIdAviatur = isset($respuestas[0]) ? trim($respuestas[0]) : '';
  3703.                 $Productidaviatur = isset($respuestas[1]) ? trim($respuestas[1]) : '';
  3704.                 /*
  3705.                  * Agente Octopus
  3706.                  * Email de la reserva del agente hijo enviado al agente Padre Octopus.
  3707.                  */
  3708.                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
  3709.                     $user $this->getUser();
  3710.                     $agent $user->getAgent();
  3711.                     $agency $this->agency;
  3712.                     if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
  3713.                         $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  3714.                         $request $request;
  3715.                         $parent $agent->getparentAgent();
  3716.                         if (!= $parent) {
  3717.                             $myParent $em->createQuery('SELECT a,b FROM AviaturAgentBundle:Agent a  JOIN a.customer b WHERE a.id= :idAgent');
  3718.                             $myParent $myParent->setParameter('idAgent'$parent);
  3719.                             $parentInfo $myParent->getResult();
  3720.                             $emailParent $parentInfo[0]->getCustomer()->getEmail();
  3721.                             $emailData['infoSubAgent'] = ['nameSubAgent' => strtoupper($agent->getCustomer()->__toString()), 'emailSubAgent' => strtoupper($agent->getCustomer()->getEmail())];
  3722.                             $messageAgent = (new \Swift_Message())
  3723.                                 ->setContentType('text/html')
  3724.                                 ->setFrom($session->get('emailNoReply'))
  3725.                                 ->setTo([$agent->getCustomer()->getEmail(), $emailParent])
  3726.                                 ->setBcc($bccMails)
  3727.                                 ->setSubject($subject ' - Reserva de Paquete Creada - ' $respuesta ' ' $customer->getFirstname() . ' ' $customer->getLastname() . ' Vendedor - ' $agent->getCustomer()->getFirstName() . ' ' $agent->getCustomer()->getLastName())
  3728.                                 ->setBody($this->renderView($urlResume$emailData));
  3729.                             $mailer->send($messageAgent);
  3730.                         } else {
  3731.                             $messageAgent = (new \Swift_Message())
  3732.                                 ->setContentType('text/html')
  3733.                                 ->setFrom($session->get('emailNoReply'))
  3734.                                 ->setTo($agent->getCustomer()->getEmail())
  3735.                                 ->setBcc($bccMails)
  3736.                                 ->setSubject($subject ' - Reserva de Paquete Creada - ' $respuesta ' ' $customer->getFirstname() . ' ' $customer->getLastname() . ' Vendedor - ' $agent->getCustomer()->getFirstName() . ' ' $agent->getCustomer()->getLastName())
  3737.                                 ->setBody($this->renderView($urlResume$emailData));
  3738.                             $mailer->send($messageAgent);
  3739.                         }
  3740.                     }
  3741.                 }
  3742.             }
  3743.             $orderProduct->setEmissiondata(json_encode($emissionData));
  3744.             $orderProduct->getOrder()->setStatus($status);
  3745.             $orderProduct->setStatus($status);
  3746.             $orderProduct->setUpdatingdate(new \DateTime());
  3747.             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  3748.             $orderProduct->getOrder()->setOrderIdAviatur($OrderIdAviatur);
  3749.             $orderProduct->setProductidaviatur($Productidaviatur);
  3750.             $em->persist($orderProduct);
  3751.             $em->flush();
  3752.         }
  3753.         return $response;
  3754.     }
  3755.     public function createOrderPackageErrorAction(Request $requestTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerSessionInterface $sessionParameterBagInterface $parameterBag)
  3756.     {
  3757.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3758.         $server $request->server;
  3759.         if (true === $session->has($transactionIdSessionName)) {
  3760.             $transactionId $session->get($transactionIdSessionName);
  3761.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  3762.             if (true === $session->has($transactionId '[availability_url]')) {
  3763.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId '[availability_url]'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  3764.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  3765.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtelo nuevamente'));
  3766.             } else {
  3767.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  3768.             }
  3769.         } else {
  3770.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puede acceder al detalle sin disponibilidad'));
  3771.         }
  3772.     }
  3773.     public function resumeAction(TwigFolder $twigFolderManagerRegistry $registryParameterBagInterface $parameterBagAviaturLogSave $aviaturLogSave)
  3774.     {
  3775.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  3776.         header('Content-Type: text/html;charset=utf-8');
  3777.         $em $this->managerRegistry;
  3778.         $session $this->session;
  3779.         $agency $this->agency;
  3780.         $transactionId $session->get($transactionIdSessionName);
  3781.         $agencyFolder $twigFolder->twigFlux();
  3782.         $resumeTrans json_decode($session->get($transactionId '[mpt]' '[resumeView]'));
  3783.         $ProductInfo json_decode($session->get($transactionId '[mpt]' '[ProductInfo]'));
  3784.         $infoClient json_decode($session->get($transactionId '[mpt]' '[infoClient]'));
  3785.         $infoSelection json_decode($session->get($transactionId '[mpt]' '[infoSelection]'));
  3786.         $infoOptionals json_decode($session->get($transactionId '[mpt]' '[optionalSelection]'));
  3787.         $orderProductCode json_decode($session->get($transactionId '[mpt]' '[order]'));
  3788.         if ('jetset_semana' === $agency->getAssetsFolder()) {
  3789.             $urlReturn $this->CallAPI($session$aviaturLogSave$registry'GET'$transactionId);
  3790.         }
  3791.         $productId str_replace('PN'''$orderProductCode->products);
  3792.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  3793.         $infoEmissiondata json_decode($orderProduct->getEmissiondata());
  3794.         $passangersData = [];
  3795.         // Información adultos
  3796.         $infoPassengerADT = (array) $infoEmissiondata->emailData->passengerADT;
  3797.         if(count($infoPassengerADT) > 0){
  3798.             foreach($infoPassengerADT as $adult){
  3799.                 $passangersData[] = [
  3800.                     "first_name" => $adult->First_name,
  3801.                     "last_name" => $adult->First_last_name,
  3802.                     "passanger_type" => "ADT"
  3803.                 ];
  3804.             }
  3805.         }
  3806.         // Información niños
  3807.         $infoPassengerCHD = (array) $infoEmissiondata->emailData->passengerCHD;
  3808.         if(count($infoPassengerCHD) > 0){
  3809.             $typePassanger "CHD";
  3810.             foreach($infoPassengerCHD as $child){
  3811.                 $passangersData[] = [
  3812.                     "first_name" => $child->First_name,
  3813.                     "last_name" => $child->First_last_name,
  3814.                     "passanger_type" => "CHD"
  3815.                 ];
  3816.             }
  3817.         }
  3818.         // Url de la primera imagen del paquete
  3819.         $infopackage simplexml_load_string($session->get($transactionId '[mpt][infoPackage]'));
  3820.         $urlImageString = (string) $infopackage->TPA_Extensions->ProductInfo->Multimedia->ImageItems->ImageItem->Url;
  3821.         
  3822.         // Precio total del paquete
  3823.         $priceTotalPackage = [
  3824.             "totalAmount" => $infoEmissiondata->emailData->AmountTotal,
  3825.             "currency" => $infoEmissiondata->emailData->ProductInfo->CodeIATA
  3826.         ];
  3827.         // Información del hotel
  3828.         $InfoHotel simplexml_load_string($session->get($transactionId '[mpt]' '[InfoHotel]'));
  3829.         foreach ($infoSelection->IdPrestador as $idprestador) {
  3830.             foreach ($InfoHotel->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $hotelInfo) {
  3831.                 if ($idprestador == $hotelInfo->Identity['HotelCode']) {
  3832.                     $infoSelection->nameHotel[] = $hotelInfo->Identity['HotelName'];
  3833.                     $infoSelection->categoria[] = $hotelInfo->TPA_Extensions->HotelInfo->Category->CodeDetail;
  3834.                     $infoSelection->Latitude[] = $hotelInfo->TPA_Extensions->HotelInfo->Latitude;
  3835.                     $infoSelection->Longitude[] = $hotelInfo->TPA_Extensions->HotelInfo->Longitude;
  3836.                     $infoSelection->Zone[] = $hotelInfo->TPA_Extensions->HotelInfo->Zone;
  3837.                     $infoSelection->Multimedia[] = $hotelInfo->TPA_Extensions->HotelInfo->Multimedia->ImageItems->ImageItem;
  3838.                 }
  3839.             }
  3840.         }
  3841.         // Agrupando por hoteles y mapeando habitaciones respecto al hotel
  3842.         $groupedHotels = [];
  3843.         $count count($infoSelection->IdHotelCode);
  3844.         for ($i 0$i $count$i++) {
  3845.             $hotelId $infoSelection->IdHotelCode[$i];
  3846.             $roomData = [
  3847.                 'IdPrestador'         => $infoSelection->IdPrestador[$i],
  3848.                 'IdBrandName'         => $infoSelection->IdBrandName[$i],
  3849.                 'IdPrestadorNew'      => $infoSelection->IdPrestadorNew[$i],
  3850.                 'TipoHabitacion'      => $infoSelection->TipoHabitacion[$i],
  3851.                 'CategoriaHabitacion' => $infoSelection->CategoriaHabitacion[$i],
  3852.                 'CantidadAdultos'     => $infoSelection->CantidadAdultos[$i],
  3853.                 'CantidadNiños'       => $infoSelection->CantidadNiños[$i],
  3854.                 'AditionalRoom'       => $infoSelection->AditionalRoom[$i],
  3855.                 'personTotal'         => $infoSelection->personTotal[$i],
  3856.                 'ValorTotal'          => $infoSelection->ValorTotal[$i],
  3857.                 'personAditional'      => $infoSelection->personAditional[$i],
  3858.                 'codeBooking'         => $infoSelection->codeBooking[$i],
  3859.                 'totalTarifas'        => $infoSelection->totalTarifas[$i],
  3860.                 'tarifaReal'          => $infoSelection->tarifaReal[$i]
  3861.             ];
  3862.             // Inicializar el hotel si no existe
  3863.             if (!isset($groupedHotels[$hotelId])) {
  3864.                 $groupedHotels[$hotelId] = [
  3865.                     'idHotel'         => $infoSelection->IdHotelCode[$i],
  3866.                     'nameHotel'       => $infoSelection->nameHotel[$i],
  3867.                     'categoryHotel'   => $infoSelection->categoria[$i],
  3868.                     'latitudeHotel'   => $infoSelection->Latitude[$i],
  3869.                     'longitudeHotel'  => $infoSelection->Longitude[$i],
  3870.                     'zoneHotel'       => $infoSelection->Zone[$i],
  3871.                     'multimediaHotel' => $infoSelection->Multimedia[$i],
  3872.                     'rooms'           => [],
  3873.                     'optionals'       => $infoSelection->optionals[$i] ?? $infoSelection->optionals
  3874.                 ];
  3875.             }
  3876.             // Agregar la habitación al hotel correspondiente
  3877.             $groupedHotels[$hotelId]['rooms'][] = $roomData;
  3878.         }
  3879.         // Condiciones
  3880.         $cautions = [
  3881.             'included' => [],
  3882.             'notIncluded' => [],
  3883.             'itinerary' => [],
  3884.             'paymentPolicy' => [],
  3885.             'restrictionPolicy' => [],
  3886.             'conditions' => [],
  3887.             'infoTraveler' => [],
  3888.             'childPolicy' => 'De acuerdo con la Aerocivil y lo estipulado por la Registraduría Nacional del Estado Civil para fortalecer las medidas de identificación de los colombianos, entre ellos las de los menores de edad, las aerolíneas exigirán fotocopia autenticada del Registro Civil a los padres o adultos encargados de viajar, vía aérea, con menores entre 0 y 7 años. Es necesario que quienes viajen con niños entre estas edades tengan esta documentación exigida, de lo contrario los menores no podrán viajar a destinos nacionales e internacionales donde tendrán que presentar adicionalmente el pasaporte. Para obtener la autenticación del documento, los padres deberán realizar el trámite respectivo ante notaria donde fue registrado el menor.',
  3889.             'responsibilityPolicy' => (string) $infopackage->TPA_Extensions->ProductInfo->ResponsibilityPolicy
  3890.         ];
  3891.         foreach ($infopackage->Cautions->Caution as $caution) {
  3892.             if (\strlen((string) $caution)) {
  3893.                 switch ((string) $caution['ID'][0]) {
  3894.                         // map cautions to an array limited to six items
  3895.                     case 'ContentInclude':
  3896.                         $cautions['included'][] = (string) $caution;
  3897.                         break;
  3898.                     case 'ContentNoInclude':
  3899.                         $cautions['notIncluded'][] = (string) $caution;
  3900.                         break;
  3901.                     case 'Itinerary':
  3902.                         $cautions['itinerary'][] = (string) $caution;
  3903.                         break;
  3904.                     case 'PaymentPolicy':
  3905.                         $cautions['paymentPolicy'][] = (string) $caution;
  3906.                         break;
  3907.                     case 'CancellationRestrictionPolicy':
  3908.                         $cautions['restrictionPolicy'][] = (string) $caution;
  3909.                         break;
  3910.                     case 'Conditions':
  3911.                         $cautions['conditions'][] = (string) $caution;
  3912.                         break;
  3913.                     case 'TravelerInformation':
  3914.                     case 'Observations':
  3915.                         $cautions['infoTraveler'][] = (string) $caution;
  3916.                         break;
  3917.                 }
  3918.             }
  3919.         }
  3920.         // Añadiendo pais de destino para condiciones
  3921.         $infoProduct simplexml_load_string(html_entity_decode($ProductInfo));
  3922.         $infoProduct->PaisDestino $infopackage->TPA_Extensions->ProductInfo->CodePais;
  3923.         $resumeView = [
  3924.             'Estado' => $resumeTrans->Estado,
  3925.             'Description' => $resumeTrans->Description,
  3926.             'urlImagePackage' => $urlImageString,
  3927.             'priceTotalPackage' => $priceTotalPackage,
  3928.             'message' => (!empty($resumeTrans->message) ? $resumeTrans->message $orderProductCode->order ) . ' - ' $orderProductCode->products,
  3929.             'ProductInfo' => $infoProduct,
  3930.             'infoClient' => $infoClient,
  3931.             'passangersData' => $passangersData,
  3932.             'infoOptionals' => $infoOptionals,
  3933.             'infoSelection' => $infoSelection,
  3934.             'infoPackage' => $groupedHotels,
  3935.             'agencyData' => $agency,
  3936.             'urlReturn' => $urlReturn ?? null,
  3937.             'cautions' => $cautions
  3938.         ];
  3939.         $urlResume $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Package/Default/resume_content.html.twig');
  3940.         $setResume $this->render($urlResume$resumeView);
  3941.         $orderProduct->setEmail(json_encode($resumeView));
  3942.         $orderProduct->setResume($setResume);
  3943.         $bookinData json_decode($session->get($transactionId '[mpt][resumeView]'), true);
  3944.         if (isset($bookinData['Estado'][0]) && 'OK' == mb_strtoupper($bookinData['Estado'][0])) {
  3945.             $emissionData json_decode($orderProduct->getEmissionData(), true);
  3946.             $emissionData['emission'] = $bookinData['message'][0];
  3947.             $orderProduct->setEmissionData(json_encode($emissionData));
  3948.         }
  3949.         $em->persist($orderProduct);
  3950.         $em->flush();
  3951.         return $setResume;
  3952.     }
  3953.     /* Funcion que calcula el numero de Festivos entre dos fechas */
  3954.     public function CountFestivos($fecha1$fecha2$weekDay)
  3955.     {
  3956.         $fecha1 strtotime($fecha1);
  3957.         $fecha2 strtotime($fecha2);
  3958.         $DayWeek explode('-'$weekDay);
  3959.         $countFestivos 0;
  3960.         for ($fecha1$fecha1 $fecha2$fecha1 strtotime('+1 day ' date('Y-m-d'$fecha1))) {
  3961.             for ($i 0$i sizeof($DayWeek); ++$i) {
  3962.                 if (== $DayWeek[$i]) {
  3963.                     $DayWeek[$i] = 0;
  3964.                 }
  3965.                 if (date('w'$fecha1) == $DayWeek[$i]) {
  3966.                     ++$countFestivos;
  3967.                 }
  3968.             }
  3969.         }
  3970.         return $countFestivos;
  3971.     }
  3972.     /* Funcion que calcula el tipo de días entre dos fechas respecto a weekDay*/
  3973.     public function countDaysByWeekDays($fechaStart$fechaEnd$weekDay$packageNights)
  3974.     {
  3975.         $start strtotime($fechaStart);
  3976.         $end strtotime($fechaEnd);
  3977.         // Convertimos $weekDay a array, cambiando 7 por 0 para domingo
  3978.         $DayWeek array_map(function($day) {
  3979.             return ($day == 7) ? : (int)$day;
  3980.         }, array_filter(explode('-'$weekDay), fn($d) => $d !== ''));
  3981.         $DayWeek array_unique($DayWeek);
  3982.         $totalNights = ($end $start) / 86400;
  3983.         $packageCount 0;
  3984.         $extraCount 0;
  3985.         for ($i 0$i $totalNights$i++) {
  3986.             $currentDay strtotime("+$i day"$start);
  3987.             $dayOfWeek = (int)date('w'$currentDay);
  3988.             if (in_array($dayOfWeek$DayWeektrue)) {
  3989.                 if ($i $packageNights) {
  3990.                     $packageCount++;
  3991.                 } else {
  3992.                     $extraCount++;
  3993.                 }
  3994.             }
  3995.         }
  3996.         return [
  3997.             'packageNights' => $packageCount,
  3998.             'extraNights' => $extraCount,
  3999.         ];
  4000.     }
  4001.     public function viewConditionsAction(Request $requestTwigFolder $twigFolderSessionInterface $session)
  4002.     {
  4003.         $fullRequest $request;
  4004.         $request $fullRequest->request;
  4005.         $transactionID $request->get('transactionId');
  4006.         $response simplexml_load_string($session->get($transactionID '[mpt]' '[InfoHotel]'));
  4007.         $agencyFolder $twigFolder->twigFlux();
  4008.         foreach ($response->OTA_PkgAvailRS->Package as $information) {
  4009.             foreach ($information->Cautions as $travelerInformation) {
  4010.                 foreach ($travelerInformation as $caution) {
  4011.                     $info explode('</Caution>'str_replace($caution['ID'] . '">''</Caution>'$caution->asXml()));
  4012.                     $caution['Info'] = isset($info[1]) ? htmlspecialchars_decode($info[1]) : '';
  4013.                     $infoHtml $travelerInformation;
  4014.                     $travelerInformation $infoHtml;
  4015.                 }
  4016.             }
  4017.         }
  4018.         $urlDetail $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Package/Includes/package_conditions.html.twig');
  4019.         return $this->render($urlDetail, ['ProductsDetail' => $response'conditions' => true]);
  4020.     }
  4021.     public function viewConditionsErrorAction(Request $requestTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandlerRouterInterface $routerSessionInterface $sessionParameterBagInterface $parameterBag)
  4022.     {
  4023.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  4024.         $server $request->server;
  4025.         if (true === $session->has($transactionIdSessionName)) {
  4026.             $transactionId $session->get($transactionIdSessionName);
  4027.             $referer $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
  4028.             if (true === $session->has($transactionId '[availability_url]')) {
  4029.                 return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId '[availability_url]'), 'Página no accesible''No puedes acceder al detalle sin disponibilidad'));
  4030.             } elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
  4031.                 return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '''Error en la respuesta de nuestro proveedor de servicios, inténtalo nuevamente'));
  4032.             } else {
  4033.                 return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puedes acceder al detalle sin disponibilidad'));
  4034.             }
  4035.         } else {
  4036.             return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible''No puedes acceder al detalle sin disponibilidad'));
  4037.         }
  4038.     }
  4039.     /* Función que calcula el valor que factura los niños segun la edad */
  4040.     public function AmountCHD($AmountBaby$selectValue$ageMin$ageMax$AmountADT$CHDValue)
  4041.     {
  4042.         $AmountChdTotal 0;
  4043.         $newCHDValue 0;
  4044.         if ($selectValue !== null) {
  4045.             for ($i 0$i sizeof($selectValue); ++$i) {
  4046.                 if (null != $ageMin || null != $ageMax) {
  4047.                     if ($selectValue[$i] < min($ageMin)) {
  4048.                         //echo $selectValue[$i] . "***fuera por rango minimo***0****" . "2.1<br>";
  4049.                         $AmountChdTotal $AmountChdTotal $AmountBaby;
  4050.                     } elseif ($selectValue[$i] > max($ageMax)) {
  4051.                         //echo $selectValue[$i] . "***fuera por rango maximo****" . $AmountADT . "****" . "2.2<br>";
  4052.                         $AmountChdTotal $AmountChdTotal $AmountADT;
  4053.                     } else {
  4054.                         for ($j 0$j sizeof($ageMin); ++$j) {
  4055.                             if ($selectValue[$i] >= $ageMin[$j] && $selectValue[$i] <= $ageMax[$j]) {
  4056.                                 if ((is_countable($CHDValue) ? count($CHDValue) : 0) > 1) {
  4057.                                     $newCHDValue $CHDValue[$j];
  4058.                                 } else {
  4059.                                     $newCHDValue $CHDValue[0];
  4060.                                 }
  4061.                                 $newCHDValue str_replace(',''.'$newCHDValue);
  4062.                                 $newCHDValue floatval($newCHDValue);
  4063.                                 $newCHDValue intval($newCHDValue);
  4064.                                 $AmountChdTotal $AmountChdTotal $newCHDValue;
  4065.                                 //echo $selectValue[$i] . "En el rango***" . $ageMin[$j] . "***" . $ageMax[$j] . "****" . $AmountChdTotal . "****" .$CHDValue[$j]. "<br>";
  4066.                                 break;
  4067.                             }
  4068.                         }
  4069.                     }
  4070.                 }
  4071.             }
  4072.         }
  4073.         return $AmountChdTotal;
  4074.     }
  4075.     /* Función que calcula el valor total de la tarifa */
  4076.     public function calculoTarifa($subTotal$TotalDays$tarifas$roomAditional$personAditional$ADTotal$CHDTotal$nights)
  4077.     {
  4078.         $tarifaReal = [];
  4079.         $TotalADN 0;
  4080.         $TotalADD 0;
  4081.         $TotalAAN 0;
  4082.         $AmountChn 0;
  4083.         $tarifaReal['CantADT'] = $ADTotal;
  4084.         $tarifaReal['CantCHD'] = $CHDTotal;
  4085.         $tarifaReal['CantNights'] = $TotalDays;
  4086.         $tarifaReal['aditionalRoom'] = $roomAditional;
  4087.         $tarifaReal['aditionalPerson'] = $personAditional;
  4088.         $tarifaReal['ADT'] = ($TotalDays 1) ? (int) ($tarifas['AmountADT']) : (int) ($tarifas['AmountADT']) / $nights;
  4089.         $tarifaReal['DAYS_ADT'] = $nights;
  4090.         if ($CHDTotal 0) {
  4091.             $tarifaReal['CHD'] = ($TotalDays 1) ? (int) ($tarifas['AmountCHD']) : (int) ($tarifas['AmountCHD']) / $nights;
  4092.             $tarifaReal['DAYS_CHD'] = $nights;
  4093.         }
  4094.         if ($roomAditional && $personAditional 0) {
  4095.             $TotalADN $tarifas['AmountADN'] * $roomAditional $ADTotal;
  4096.             $tarifaReal['ADN'] = $tarifas['AmountADN'];
  4097.             $tarifaReal['DAYS_ADN'] = $roomAditional;
  4098.             $TotalADD $tarifas['AmountADD'] * $TotalDays;
  4099.             $tarifaReal['ADD'] = $tarifas['AmountADD'];
  4100.             $tarifaReal['DAYS_ADD'] = $TotalDays;
  4101.             $TotalAAN $tarifas['AmountAAN'] * $roomAditional;
  4102.             $tarifaReal['AAN'] = $tarifas['AmountAAN'];
  4103.             $tarifaReal['DAYS_AAN'] = $roomAditional;
  4104.             $subTotal $subTotal $TotalADN $TotalADD $TotalAAN;
  4105.             if ($CHDTotal 0) {
  4106.                 $AmountChn $tarifas['AmountCHN'] * $roomAditional 1;
  4107.                 $tarifaReal['CHN'] = $tarifas['AmountCHN'];
  4108.                 $tarifaReal['DAYS_CHN'] = $roomAditional;
  4109.                 $subTotal $subTotal $AmountChn;
  4110.             }
  4111.         } elseif ($roomAditional && == $personAditional) {
  4112.             $TotalADN $tarifas['AmountADN'] * $roomAditional $ADTotal;
  4113.             $tarifaReal['ADN'] = $tarifas['AmountADN'];
  4114.             $tarifaReal['DAYS_ADN'] = $roomAditional;
  4115.             $subTotal $subTotal $TotalADN;
  4116.             if ($CHDTotal 0) {
  4117.                 $AmountChn $tarifas['AmountCHN'] * $roomAditional 1;
  4118.                 $tarifaReal['CHN'] = $tarifas['AmountCHN'];
  4119.                 $tarifaReal['DAYS_CHN'] = $roomAditional;
  4120.                 $subTotal $subTotal $AmountChn;
  4121.             }
  4122.         } elseif (== $roomAditional && $personAditional 0) {
  4123.             $TotalADD $tarifas['AmountADD'] * $TotalDays;
  4124.             $tarifaReal['ADD'] = $tarifas['AmountADD'];
  4125.             $tarifaReal['DAYS_ADD'] = $TotalDays;
  4126.             $subTotal $subTotal $TotalADD;
  4127.         }
  4128.         $result = ['SubTotal' => $subTotal'tarifas' => $tarifas'tarifaReal' => $tarifaReal];
  4129.         return $result;
  4130.     }
  4131.     public function calculoValor($cantidad$tarifa$dayType$UnitCostValue$nights)
  4132.     {
  4133.         $total 0;
  4134.         $total $cantidad $tarifa $dayType;
  4135.         if (== $UnitCostValue) {
  4136.             $total $total $nights;
  4137.         }
  4138.         return $total;
  4139.     }
  4140.     public function calculoTarifaFinDeSemana($roomAditional$personAditional$fecha1$fecha2$CantADT$CHDTotal$tarifas$WeekDay$ageMinCHD$ageMaxCHD$ChdValues$selectValue$ageMinCHN$ageMaxCHN$ChnValues$ageMinCHF$ageMaxCHF$ChfValues$ageMinCFN$ageMaxCFN$CfnValues$UnitCostValue$nights)
  4141.     {
  4142.         $tarifaReal = [];
  4143.         $AmountBaby 0;
  4144.         // Quitar de ADF los días que ya están en ADT
  4145.         $arrayADT array_unique(explode('-'$WeekDay['ADT']));
  4146.         $arrayADF array_unique(explode('-'$WeekDay['ADF']));
  4147.         $filteredADF array_diff($arrayADF$arrayADT);
  4148.         $WeekDay['ADF'] = implode('-'$filteredADF);
  4149.         // Calcula la cantidad de noches entre semana y fines de semana
  4150.         $countWeekDaysADT $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['ADT'], $nights);
  4151.         $countFdsDaysADT $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['ADF'], $nights);
  4152.         $countHabiles $countWeekDaysADT["packageNights"];
  4153.         $countFestivos =  $countFdsDaysADT["packageNights"];
  4154.         // Calcula la tarifa de noches entre semana y fines de semana
  4155.         $tarifaADT $this->calculoValor($CantADT$tarifas['AmountADT'], $countHabiles$UnitCostValue$nights);
  4156.         $tarifaReal['ADT'] = ($tarifaADT $CantADT) / ((== $countHabiles) ? $countHabiles);
  4157.         $tarifaReal['DAYS_ADT'] = $countHabiles;
  4158.         $tarifaADF $this->calculoValor($CantADT$tarifas['AmountADF'], $countFestivos$UnitCostValue$nights);
  4159.         $tarifaReal['ADF'] = ($tarifaADF $CantADT) / ((== $countFestivos) ? $countFestivos);
  4160.         $tarifaReal['DAYS_ADF'] = $countFestivos;
  4161.         $SubTotal $tarifaADT $tarifaADF;
  4162.         // Si hay noches adicionales entre semana, calcula cuantas noches y agrega la tarifa correspondiente
  4163.         $countWeekDaysAditional null;
  4164.         if ($countWeekDaysADT["extraNights"] > 0) {
  4165.             $countWeekDaysAditional $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['ADN'], $nights);
  4166.             $tarifaADN =  $this->calculoValor($CantADT$tarifas['AmountADN'], $countWeekDaysAditional["extraNights"], $UnitCostValue$nights);
  4167.             $tarifaReal['ADN'] = ($tarifaADT $CantADT) / ((== $countWeekDaysAditional["extraNights"]) ? $countWeekDaysAditional["extraNights"]);
  4168.             $tarifaReal['DAYS_ADN'] = $countWeekDaysAditional["extraNights"];
  4169.             $SubTotal $SubTotal intval($tarifaADN);
  4170.         }
  4171.         // Si hay noches adicionales de fin de semana, calcula cuantas noches y agrega la tarifa correspondiente
  4172.         $countFdsDaysAditional null;
  4173.         if ($countFdsDaysADT["extraNights"] > 0) {
  4174.             // Quitar de ADF los días que ya están en ADN
  4175.             $arrayADN array_unique(explode('-'$WeekDay['ADN']));
  4176.             $arrayANF array_unique(explode('-'$WeekDay['ANF']));
  4177.             $filteredANF array_diff($arrayANF$arrayADN);
  4178.             $WeekDay['ANF'] = implode('-'$filteredANF);
  4179.             $countFdsDaysAditional $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['ANF'], $nights);
  4180.             $tarifaANF $this->calculoValor($CantADT$tarifas['AmountANF'], $countFdsDaysAditional["extraNights"], $UnitCostValue$nights);
  4181.             $tarifaReal['ANF'] = ($tarifaANF $CantADT) / ((== $countFdsDaysAditional["extraNights"]) ? $countFdsDaysAditional["extraNights"]);
  4182.             $tarifaReal['DAYS_ANF'] = $countFdsDaysAditional["extraNights"];
  4183.         
  4184.             $SubTotal $SubTotal intval($tarifaANF);
  4185.         }
  4186.         
  4187.         if ($CHDTotal 0) {
  4188.             $AmountCHD $this->AmountCHD($AmountBaby$selectValue$ageMinCHD$ageMaxCHD$tarifas['AmountADT'], $ChdValues);
  4189.             $tarifas['AmountCHD'] = $AmountCHD;
  4190.             $tarifaCHD $this->calculoValor(1$AmountCHD$countHabiles$UnitCostValue$nights);
  4191.             $tarifaReal['CHD'] = ($tarifaCHD $CHDTotal) / ((== $countHabiles) ? $countHabiles);
  4192.             $tarifaReal['DAYS_CHD'] = $countHabiles;
  4193.             $AmountCHF $this->AmountCHD($AmountBaby$selectValue$ageMinCHF$ageMaxCHF$tarifas['AmountADT'], $ChfValues);
  4194.             $tarifaCHF $this->calculoValor(1$AmountCHF$countFestivos$UnitCostValue$nights);
  4195.             $tarifaReal['CHF'] = ($tarifaCHF $CHDTotal) / ((== $countFestivos) ? $countFestivos);
  4196.             $tarifaReal['DAYS_CHF'] = $countFestivos;
  4197.             $TotalCHD $tarifaCHD $tarifaCHF;
  4198.             $tarifas['AmountCHF'] = $AmountCHF;
  4199.             $SubTotal $SubTotal $TotalCHD;
  4200.             // Si hay noches adicionales entre semana para niños, agrega la tarifa correspondiente
  4201.             if ($countWeekDaysADT["extraNights"] > 0) {
  4202.                 $tarifaCHN $this->calculoValor(1$tarifas['AmountCHN'], $countWeekDaysADT["extraNights"], $UnitCostValue$nights);
  4203.                 $tarifaReal['CHN'] = ($tarifaCHN $CHDTotal) / ((== $countWeekDaysADT["extraNights"]) ? $countWeekDaysADT["extraNights"]);
  4204.                 $tarifaReal['DAYS_CHN'] = $countWeekDaysADT["extraNights"];
  4205.                 $SubTotal $SubTotal intval($tarifaCHN);
  4206.             }
  4207.             // Si hay noches adicionales de fin de semana para niños, agrega la tarifa correspondiente
  4208.             if ($countFdsDaysADT["extraNights"] > 0) {
  4209.                 $tarifaCFN $this->calculoValor(1$tarifas['AmountCFN'], $countFdsDaysADT["extraNights"], $UnitCostValue$nights);
  4210.                 $tarifaReal['CFN'] = ($tarifaCFN $CHDTotal) / ((== $countFdsDaysADT["extraNights"]) ? $countFdsDaysADT["extraNights"]);
  4211.                 $tarifaReal['DAYS_CFN'] = $countFdsDaysADT["extraNights"];
  4212.                 $SubTotal $SubTotal intval($tarifaCFN);
  4213.             }
  4214.         }
  4215.         
  4216.         $AditionalPerson 1;
  4217.         if ($roomAditional 0) {
  4218.             $HabilesAditional $countWeekDaysAditional["extraNights"];
  4219.             $FestivosAditional $countFdsDaysAditional["extraNights"];
  4220.             $tarifaADN $this->calculoValor($CantADT$tarifas['AmountADN'], $HabilesAditional1$roomAditional);
  4221.             $tarifaReal['ADN'] = ($tarifaADN $CantADT) / ((== $HabilesAditional) ? $HabilesAditional);
  4222.             $tarifaReal['DAYS_ADN'] = $HabilesAditional;
  4223.             $tarifaANF $this->calculoValor($CantADT$tarifas['AmountANF'], $FestivosAditional1$roomAditional);
  4224.             $tarifaReal['ANF'] = ($tarifaANF $CantADT) / ((== $FestivosAditional) ? $FestivosAditional);
  4225.             $tarifaReal['DAYS_ANF'] = $FestivosAditional;
  4226.             $SubTotal $SubTotal $tarifaADN $tarifaANF;
  4227.             if ($CHDTotal 0) {
  4228.                 $AmountCHN $this->AmountCHD($AmountBaby$selectValue$ageMinCHN$ageMaxCHN$tarifas['AmountADN'], $ChnValues);
  4229.                 $tarifas['AmountCHN'] = $AmountCHN;
  4230.                 $tarifaCHN $this->calculoValor(1$AmountCHN$HabilesAditional1$roomAditional);
  4231.                 $tarifaReal['CHN'] = ($tarifaCHN $CHDTotal) / ((== $HabilesAditional) ? $HabilesAditional);
  4232.                 $tarifaReal['DAYS_CHN'] = $HabilesAditional;
  4233.                 $AmountCFN $this->AmountCHD($AmountBaby$selectValue$ageMinCFN$ageMaxCFN$tarifas['AmountADN'], $CfnValues);
  4234.                 $tarifas['AmountCFN'] = $AmountCFN;
  4235.                 $tarifaCFN $this->calculoValor(1$AmountCFN$FestivosAditional1$roomAditional);
  4236.                 $tarifaReal['CFN'] = ($tarifaCFN $CHDTotal) / ((== $FestivosAditional) ? $FestivosAditional);
  4237.                 $tarifaReal['DAYS_CFN'] = $FestivosAditional;
  4238.                 $TotalCHN $tarifaCHN $tarifaCFN;
  4239.                 $SubTotal $SubTotal $TotalCHN;
  4240.             }
  4241.         } 
  4242.         
  4243.         if ($personAditional 0) {
  4244.             // verifica si no hay habitaciones adicionales y hay personas adicionales
  4245.             $countDaysPersonAdd $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['ADD'], $nights);
  4246.             $tarifaADD $AditionalPerson $tarifas['AmountADD'] * $countDaysPersonAdd["packageNights"];
  4247.             $tarifaReal['ADD'] = ($tarifaADD $personAditional) / ((== $countDaysPersonAdd["packageNights"]) ? $countDaysPersonAdd["packageNights"]);
  4248.             $tarifaReal['DAYS_ADD'] = $countDaysPersonAdd["packageNights"];
  4249.             $SubTotal $SubTotal $tarifaADD;
  4250.             // Si trae fines de semana
  4251.             if ($tarifas['AmountAFN'] > 0) {
  4252.                 // Quitar de AFN los días que ya están en AAN
  4253.                 $arrayAAN array_unique(explode('-'$WeekDay['AAN']));
  4254.                 $arrayAFN array_unique(explode('-'$WeekDay['AFN']));
  4255.                 $filteredAFN array_diff($arrayAFN$arrayAAN);
  4256.                 $WeekDay['AFN'] = implode('-'$filteredAFN);
  4257.                 $countDaysAFN $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['AFN'], $nights);
  4258.                 $countDaysAFNTotal $countDaysAFN["packageNights"] + $countDaysAFN["extraNights"];
  4259.                 $tarifaAFN $AditionalPerson $tarifas['AmountAFN'] * $countDaysAFNTotal;
  4260.                 $tarifaReal['AFN'] = ($tarifaAFN $personAditional) / ((== $countDaysAFNTotal) ? $countDaysAFNTotal);
  4261.                 $tarifaReal['DAYS_AFN'] = $countDaysAFNTotal;
  4262.                 $SubTotal $SubTotal $tarifaAFN;
  4263.             }
  4264.             // Si trae dias adicionales 
  4265.             if($countDaysPersonAdd["extraNights"] > 0){
  4266.                 $countDaysAAN $this->countDaysByWeekDays($fecha1$fecha2$WeekDay['AAN'], $nights);
  4267.                 $tarifaAAN $AditionalPerson $tarifas['AmountAAN'] * $countDaysAAN["extraNights"];
  4268.                 $tarifaReal['AAN'] = ($tarifaAAN $personAditional) / ((== $countDaysAAN["extraNights"]) ? $countDaysAAN["extraNights"]);
  4269.                 $tarifaReal['DAYS_AAN'] = $countDaysAAN["extraNights"];
  4270.                 $SubTotal $SubTotal $tarifaAAN;
  4271.             }
  4272.         }
  4273.         $result = ['SubTotal' => $SubTotal'tarifas' => $tarifas'tarifaReal' => $tarifaReal];
  4274.         return $result;
  4275.     }
  4276.     public function processLegalPersonalities(ManagerRegistry $registry$customer)
  4277.     {
  4278.         $em $this->managerRegistry;
  4279.         $documentNumber = (string) $customer->getDocumentNumber();
  4280.         $documentType = (string) $customer->getDocumentType()->getId();
  4281.         $personType = (string) $customer->getPersonType();
  4282.         if (('8' === $documentNumber[0] || '9' === $documentNumber[0]) && 10 === strlen($documentNumber)) {
  4283.             if ('3' !== $documentType || '7' !== $personType) {
  4284.                 $customer->setDocumentType($em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->find(3));
  4285.                 $customer->setPersonType(7);
  4286.                 $em->flush();
  4287.                 return true;
  4288.             }
  4289.         }
  4290.         return false;
  4291.     }
  4292.     public function createCustomer(ParameterBagInterface $parameterBagAviaturWebService $aviaturWebService, \Swift_Mailer $mailerSessionInterface $sessionManagerRegistry $registry$customer)
  4293.     {
  4294.         $providerService $parameterBag->get('provider_service');
  4295.         $webmasterEmail $parameterBag->get('webmaster_email');
  4296.         $output null;
  4297.         $em $this->managerRegistry;
  4298.         $docType $customer->getDocumentType()->getExternalcode();
  4299.         $docNumber $customer->getDocumentNumber();
  4300.         $customerModel = new CustomerModel();
  4301.         $xmlRequest $customerModel->getXmlFindUser($docType$docNumber'0926EB''BOGVU2900');
  4302.         $responseCustomer $aviaturWebService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  4303.         if (empty($responseCustomer) || ($responseCustomer->RESULTADO ?? '') === 'FALLO') {
  4304.             $emailTo $webmasterEmail;
  4305.             $xmlRequest $customerModel->getXmlRegister($customer1);
  4306.             $responseCustomer $aviaturWebService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  4307.             if (empty($responseCustomer) || ($responseCustomer->RESULTADO ?? '') === 'FALLO') {
  4308.                 if (!$this->processLegalPersonalities($registry$customer)) {
  4309.                     $emailContent 'id customer new DB:' $customer->getId() . '</b> Email customer new DB: <b>' $customer->getEmail() . '</b> Service Response: ' print_r($responseCustomertrue);
  4310.                     $message = (new \Swift_Message())
  4311.                         ->setContentType('text/html')
  4312.                         ->setFrom($session->get('emailNoReply'))
  4313.                         ->setSubject('updateCustomerCommand Error 1')
  4314.                         ->setTo($emailTo)
  4315.                         ->setBody($emailContent);
  4316.                     $mailer->send($message);
  4317.                 } else {
  4318.                     $output->writeln('Customer id[' $customer->getId() . '] updated: documentType=3 - personType=7');
  4319.                 }
  4320.             } elseif (isset($responseCustomer->SALIDAS->ELEMENTO_SALIDA_B2C->ID_CLIENTE)) {
  4321.                 $responseId = (string) $responseCustomer->SALIDAS->ELEMENTO_SALIDA_B2C->ID_CLIENTE;
  4322.             }
  4323.             if (isset($responseId) && (null != (string) $responseId)) {
  4324.                 $customer->setAviaturClientId((string) $responseId);
  4325.                 $em->persist($customer);
  4326.                 $em->flush();
  4327.             } else {
  4328.                 $emailContent 'id customer new DB:' $customer->getId() . '</b> Email customer new DB: <b>'
  4329.                     $customer->getEmail() . '</b> Service Response: ' print_r($responseCustomertrue)
  4330.                     . '<br><pre>' htmlspecialchars(print_r($xmlRequesttrue)) . '</pre>';
  4331.                 $message = (new \Swift_Message())
  4332.                     ->setContentType('text/html')
  4333.                     ->setFrom($session->get('emailNoReply'))
  4334.                     ->setSubject('updateCustomerCommand Error 2')
  4335.                     ->setTo($emailTo)
  4336.                     ->setBody($emailContent);
  4337.                 $mailer->send($message);
  4338.             }
  4339.         }
  4340.     }
  4341.     public function CallAPI(SessionInterface $sessionAviaturLogSave $aviaturLogSaveManagerRegistry $registry$method$transactionId)
  4342.     {
  4343.         $data null;
  4344.         $response = [];
  4345.         $em $this->managerRegistry;
  4346.         $session $this->session;
  4347.         $agency $this->agency;
  4348.         $infopackage simplexml_load_string((string) $session->get($transactionId '[mpt][infoPackage]'));
  4349.         if (isset($infopackage->TPA_Extensions->ProductInfo->CargosYServicios->CargoYServicio['ThirdPartyId']) && '607' == (string) $infopackage->TPA_Extensions->ProductInfo->CargosYServicios->CargoYServicio['ThirdPartyId'] && $session->has($transactionId '[mpt]' '[detail_data_package]')) {
  4350.             $detail_data_package json_decode($session->get($transactionId '[mpt]' '[detail_data_package]'), true);
  4351.             $infoDates json_decode($session->get($transactionId '[mpt][infoDates]'), true);
  4352.             if (false !== strpos($detail_data_package['PI']['first_name_1_1'], '***')) {
  4353.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['documentnumber' => $detail_data_package['PI']['doc_num_1_1']]);
  4354.                 $detail_data_package['PI']['first_name_1_1'] = $customer->getFirstname();
  4355.                 $detail_data_package['PI']['last_name_1_1'] = $customer->getLastname();
  4356.                 $detail_data_package['PI']['address_1_1'] = $customer->getAddress();
  4357.                 $detail_data_package['PI']['email_1_1'] = $customer->getEmail();
  4358.             }
  4359.             $users = [];
  4360.             for ($i 0$i $detail_data_package['PI']['person_count_1']; ++$i) {
  4361.                 $users[$i]['name'] = $detail_data_package['PI']['first_name_1_' . ($i 1)] . ' ' $detail_data_package['PI']['last_name_1_' . ($i 1)];
  4362.                 if (isset($detail_data_package['PI']['email_1_' . ($i 1)])) {
  4363.                     $users[$i]['email'] = $detail_data_package['PI']['email_1_' . ($i 1)];
  4364.                 }
  4365.             }
  4366.             $aviatur_payment_jet_set_api $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('jet_set_url');
  4367.             $urls json_decode($aviatur_payment_jet_set_api->getDescription(), true);
  4368.             $url $urls[$aviatur_payment_jet_set_api->getValue()][$method];
  4369.             $curl curl_init();
  4370.             switch ($method) {
  4371.                 case 'POST':
  4372.                     curl_setopt($curlCURLOPT_POST1);
  4373.                     $data json_encode([
  4374.                         'idProducto' => (int) $infopackage['ID'],
  4375.                         'ProductName' => (string) $infopackage->TPA_Extensions->ProductInfo->ProductName,
  4376.                         'Description' => (string) $infopackage->TPA_Extensions->ProductInfo->Description,
  4377.                         'total' => $infoDates['AmountTotal'],
  4378.                         'cantidad' => $detail_data_package['PI']['person_count_1'],
  4379.                         'usuarios' => $users,
  4380.                     ]);
  4381.                     if ($data) {
  4382.                         $aviaturLogSave->logSave(print_r($datatrue), $agency->getAssetsFolder(), $method ' RQ');
  4383.                     }
  4384.                     curl_setopt($curlCURLOPT_POSTFIELDS$data);
  4385.                     curl_setopt($curlCURLOPT_HTTPHEADER, ['Content-Type:application/json']);
  4386.                     break;
  4387.                 case 'PUT':
  4388.                     curl_setopt($curlCURLOPT_PUT1);
  4389.                     break;
  4390.                 case 'GET':
  4391.                     $data base64_encode(json_encode([
  4392.                         'idProducto' => (int) $infopackage['ID'],
  4393.                         'ProductName' => (string) $infopackage->TPA_Extensions->ProductInfo->ProductName,
  4394.                         'Description' => (string) $infopackage->TPA_Extensions->ProductInfo->Description,
  4395.                         'total' => $infoDates['AmountTotal'],
  4396.                         'cantidad' => $detail_data_package['PI']['person_count_1'],
  4397.                         'usuarios' => $users,
  4398.                     ]));
  4399.                     return $url '?ProductInfo=' $data;
  4400.                 case 'CONT':
  4401.                     curl_setopt($curlCURLOPT_POST1);
  4402.                     $data json_encode([
  4403.                         'idProducto' => (int) $infopackage['ID'],
  4404.                     ]);
  4405.                     if ($data) {
  4406.                         $aviaturLogSave->logSave(print_r($datatrue), $agency->getAssetsFolder(), $method ' RQ');
  4407.                     }
  4408.                     curl_setopt($curlCURLOPT_POSTFIELDS$data);
  4409.                     curl_setopt($curlCURLOPT_HTTPHEADER, ['Content-Type:application/json']);
  4410.                     break;
  4411.                 default:
  4412.                     if ($data) {
  4413.                         $url sprintf('%s?%s'$urlhttp_build_query($data));
  4414.                     }
  4415.             }
  4416.             curl_setopt($curlCURLOPT_HTTPAUTHCURLAUTH_BASIC);
  4417.             curl_setopt($curlCURLOPT_URL$url);
  4418.             curl_setopt($curlCURLOPT_RETURNTRANSFER1);
  4419.             curl_setopt($curlCURLOPT_SSL_VERIFYPEERfalse);
  4420.             if (false === curl_exec($curl)) {
  4421.                 $response['error'] = curl_error($curl);
  4422.             } else {
  4423.                 $response curl_exec($curl);
  4424.             }
  4425.             curl_close($curl);
  4426.             $aviaturLogSave->logSave(print_r($responsetrue), $agency->getAssetsFolder(), $method ' RS');
  4427.         }
  4428.         return $response ?? false;
  4429.     }
  4430.     public function consultPromoCodeAction(Request $requestSessionInterface $sessionManagerRegistry $registry)
  4431.     {
  4432.         $em $this->managerRegistry;
  4433.         $fullRequest $request;
  4434.         $code $fullRequest->request->get('code');
  4435.         $promotionalCodePackage $em->getRepository(\Aviatur\PackageBundle\Entity\PromotionalCodePackage::class)->findOneBy([
  4436.             'code' => $code,
  4437.             'orderproductid' => null,
  4438.         ]);
  4439.         if (!($promotionalCodePackage)) {
  4440.             $session->remove('promotionalCodePackage_code');
  4441.             return $this->json(['response' => '0''text' => 'nonExistentCode']);
  4442.         } else {
  4443.             $session->set('promotionalCodePackage_code'$code);
  4444.             return $this->json(['response' => '2''text' => 'availableCode''packageCode' => $promotionalCodePackage->getPackagecode()]);
  4445.         }
  4446.     }
  4447. }