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

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