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

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