src/Aviatur/InsuranceBundle/Controller/DefaultController.php line 45

Open in your IDE?
  1. <?php
  2. namespace Aviatur\InsuranceBundle\Controller;
  3. use Aviatur\AgentBundle\Entity\AgentTransaction;
  4. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  5. use Aviatur\InsuranceBundle\Models\InsuranceModel;
  6. use FOS\UserBundle\Model\UserInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  9. use Symfony\Component\HttpFoundation\Cookie;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  13. use Doctrine\Persistence\ManagerRegistry;
  14. use Symfony\Component\Routing\RouterInterface;
  15. use Aviatur\TwigBundle\Services\TwigFolder;
  16. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  17. use Aviatur\GeneralBundle\Services\ExceptionLog;
  18. use Aviatur\GeneralBundle\Services\AviaturWebService;
  19. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  20. use Aviatur\GeneralBundle\Controller\OrderController;
  21. use Aviatur\PaymentBundle\Controller\P2PController;
  22. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  23. use Aviatur\PaymentBundle\Services\TokenizerService;
  24. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  25. use Aviatur\GeneralBundle\Services\AviaturPixeles;
  26. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  27. use Knp\Snappy\Pdf;
  28. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  29. use Aviatur\InsuranceBundle\Services\InsuranceService;
  30. use Aviatur\InsuranceBundle\Services\SearchInsuranceCookie;
  31. use Aviatur\PaymentBundle\Controller\WorldPayController;
  32. use Aviatur\PaymentBundle\Controller\PSEController;
  33. use Aviatur\GeneralBundle\Services\AviaturMailer;
  34. use Aviatur\CustomerBundle\Services\ValidateSanctions;
  35. use Aviatur\PaymentBundle\Controller\SafetypayController;
  36. use Aviatur\PaymentBundle\Controller\CashController;
  37. use FOS\UserBundle\Security\LoginManagerInterface;
  38. use Aviatur\GeneralBundle\Services\QuotationUtils;
  39. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  40. class DefaultController extends AbstractController
  41. {
  42.     public function searchAction()
  43.     {
  44.         return $this->redirect(
  45.             $this->generateUrl(
  46.                 'aviatur_search_insurance',
  47.                 []
  48.             )
  49.         );
  50.     }
  51.     public function availabilityAction(Request $fullRequestSearchInsuranceCookie $searchInsuranceCookieInsuranceService $insuranceServiceAviaturPixeles $aviaturPixelesExceptionLog $exceptionLogAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag$destiny$dateEntry$dateEnd$birth1 null$birth2 null$birth3 null$birth4 null$birth5 null$birth6 null$birth7 null$birth8 null$birth9 null$passenger)
  52.     {
  53.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  54.         $projectDir $parameterBag->get('kernel.project_dir');
  55.         $voucherInsuranceFile $projectDir.'/app/quotationLogs/insuranceQuotation/';
  56.     
  57.         // $permisos = substr(sprintf('%o', fileperms($voucherInsuranceFile)), -4);
  58.         // if ($permisos != '0777') {
  59.         //     chmod($voucherInsuranceFile, 0755);
  60.         // }
  61.         
  62.         
  63.         $variable = [];
  64.         $dateBirth = [];
  65.         $calculoEdades = [];
  66.         $passanger_type = [];
  67.         $pixel = [];
  68.         $isAgent false;
  69.         $em $registry->getManager();
  70.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
  71.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  72.         $parameters json_decode($session->get($fullRequest->getHost().'[parameters]'));
  73.         if ($session->has('whitemark')) {
  74.             $domain $agency->getDomain();
  75.         } else {
  76.             $domain str_replace('www.'''$fullRequest->getHost());
  77.         }
  78.         $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findOneByCode('ASSIST');
  79.         $validation $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_crossed_insurance_flight');
  80.         $configsInsuranceAgency $em->createQuery('SELECT cia FROM AviaturInsuranceBundle:ConfigInsuranceAgency cia WHERE cia.agency = :agency ORDER BY cia.id ASC')->setParameters(['agency' => $agency]);
  81.         try {
  82.             $configsInsuranceAgency $configsInsuranceAgency->getResult();
  83.         } catch (\Exception $e) {
  84.             return $configsInsuranceAgency null;
  85.         }
  86.         $isFront $session->has('operatorId');
  87.         $pixelInfo = []; //THIS IS INTENDED FOR STORING ALL DATA CLASIFIED BY PIXEL.'
  88.         if (!isset($configsInsuranceAgency) || null == $configsInsuranceAgency) {
  89.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_search_insurance'), '''Error al Configurar la agencia'));
  90.         }
  91.         $OfficeId explode('-'$configsInsuranceAgency[0]->getOfficeId());
  92.         $routeName $fullRequest->get('_route');
  93.         $findme 'secure';
  94.         $compare strpos($routeName$findme);
  95.         $agencyFolder $twigFolder->twigFlux();
  96.         if (false === $compare) {
  97.             $domain_file $session->get('domain');
  98.             $method 'assist';
  99.             $login true;
  100.         } else {
  101.             $domain_file $session->get('domainsecure');
  102.             $method 'flight';
  103.             $login false;
  104.         }
  105.         $infoBirth null;
  106.         if ('flight' == $method) {
  107.             $transactionId $session->get($transactionIdSessionName);
  108.             $infoBirth json_decode($session->get($transactionId.'[crossed][infoBirth]'), true);
  109.             $variable['transactionId'] = $transactionId;
  110.         }
  111.         $diffDays = ((strtotime($dateEnd) - strtotime($dateEntry)) / 86400) + 1;
  112.         $providers = [];
  113.         if ($configsInsuranceAgency) {
  114.             foreach ($configsInsuranceAgency as $configInsuranceAgency) {
  115.                 $provider $configInsuranceAgency->getProvider()->getProvideridentifier();
  116.                 if (!(in_array($provider$providers))) {
  117.                     $providers[] = $provider;
  118.                 }
  119.             }
  120.         } else {
  121.             $exceptionLog->log('Error Fatal''No se encontró la agencia segun el dominio: '.$domainnullfalse);
  122.             return new Response('no se encontró agencias para consultar disponibilidad.');
  123.         }
  124.         $providersAgency implode(';'$providers);
  125.         $variable['ProviderId'] = $providersAgency;
  126.         $variable['MaximumTripLength'] = 'P'.$diffDays.'D';
  127.         $variable['AreaID'] = $destiny;
  128.         $variable['OfficeId'] = $OfficeId[1];
  129.         $variable['AgencyId'] = substr($OfficeId[0], 1);
  130.         $variable['diffDays'] = $diffDays;
  131.         $variable['CoveredTraveler'] = $this->calcInfoPassenger($insuranceService$passenger$method$infoBirth$fullRequest);
  132.         $variable['EffectiveDate'] = $dateEntry;
  133.         $variable['ExpireDate'] = $dateEnd;
  134.         if ($isFront) {
  135.             $userFront simplexml_load_string($session->get('front_user'));
  136.             $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  137.             $variable['OperatorId'] = (string) $userFront->ID_AGENTE;
  138.             $variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
  139.             $variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE02);
  140.         }
  141.         $InsuranceModel = new InsuranceModel();
  142.         $xmlTemplate $InsuranceModel->getXmlAvailability($variable);
  143.         $echoToken null;
  144.         $ProductInfo null;
  145.         if ($fullRequest->isXmlHttpRequest() || 'aviatur_flight_payment_success_secure' == $routeName) {
  146.             $response $aviaturWebService->callWebServiceAmadeus('Execute''InsuranceQuote''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate$variable$login);
  147.             if ($isAgent) {
  148.                 $commissionPay 0;
  149.             }
  150.             if (isset($response['error'])) {
  151.                 if ('aviatur_flight_payment_success_secure' != $routeName) {
  152.                     return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/General/Templates/dispoError.html.twig'), [
  153.                                 'message' => $response['error'],
  154.                                 'errorCode' => '', ]);
  155.                 } else {
  156.                     $response = new Response($response['error']);
  157.                     $response->headers->set('Content-Type''application/json');
  158.                     return $response;
  159.                 }
  160.             } else {
  161.                 $echoToken = (string) $response->Message->OTA_InsuranceQuoteRS->PlanForQuoteRS[0]->PlanCost->BasePremium['Amount'];
  162.                 $ID = [];
  163.                 foreach ($response->Message->OTA_InsuranceQuoteRS->PlanForQuoteRS as $AssistInfo) {
  164.                     $ID['Amount'][(string) $AssistInfo['PlanID']][] = (int) $AssistInfo->PlanCost['Amount'];
  165.                     $planCharges = isset($AssistInfo->PlanCost->Charges->Charge['Amount']) ? round((float) $AssistInfo->PlanCost->Charges->Charge['Amount']) : 0;
  166.                     $ID['Charges'][(string) $AssistInfo['PlanID']][] = $planCharges;
  167.                     if (in_array($AssistInfo['PlanID'], array_keys($ID))) {
  168.                         //$ID[(string) $AssistInfo['PlanID']] = $ID[(string) $AssistInfo['PlanID']] + (int) $AssistInfo->PlanCost['Amount'];
  169.                         $ID[(string) $AssistInfo['PlanID']]['Amount'] += (int) $AssistInfo->PlanCost['Amount'];
  170.                         $ID[(string) $AssistInfo['PlanID']]['Charges'] += $planCharges;
  171.                     } else {
  172.                         //$ID[(string) $AssistInfo['PlanID']] = (int) $AssistInfo->PlanCost['Amount'];
  173.                         $ID[(string) $AssistInfo['PlanID']] = [
  174.                             'Amount' => (int) $AssistInfo->PlanCost['Amount'],
  175.                             'Charges' => $planCharges,
  176.                             'ChargesSingle' => $planCharges,
  177.                         ];
  178.                     }
  179.                 }
  180.                 $transactionId = (string) $response->Message->OTA_InsuranceQuoteRS['TransactionIdentifier'];
  181.                 // dd($response->Message->OTA_InsuranceQuoteRS);
  182.                 $nameProduct 'insurance';
  183.                 $productCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
  184.                 $productCommission2 = (array)$productCommission;
  185.                 $session->set($transactionId.'_isActiveQse', ((is_countable($productCommission2) ? count($productCommission2) : 0) > 0) ? true false);
  186.                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  187.                     $agencyId $session->get('agencyId'); 
  188.                 
  189.                     if ((== $agency->getId() || 217 == $agency->getId() || 216 == $agency->getId() || 56 == $agency->getId())) {  //agentes octopus
  190.                         $user $this->getUser();
  191.                         $emailuser $user->getemail();
  192.                         $agent $user->getAgent();
  193.                         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
  194.                         if (!empty($agent)) {
  195.                             $idagent $agent[0]->getid();
  196.                             $nombreagente $user->getFirstname().' '.$user->getLastname();
  197.                             $agencyFolder $twigFolder->twigFlux();
  198.                             $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
  199.                             $infoQse json_decode($agentCommission->getQseproduct());
  200.                             $infoQseNameProduct = empty($infoQse->$nameProduct) ? false $infoQse->$nameProduct;
  201.                             $infoQse = empty($infoQse) ? false $infoQseNameProduct;
  202.                             $agentQseAmount = ($infoQse) ? (int) $infoQse->commission_money 0;
  203.                             $agentQseAmountMax $productCommission->getQsecommissionmax();
  204.                             $productpercentage = ($infoQse) ? (float) $infoQse->commission_percentage 0;
  205.                             $productpercentagemax $productCommission->getPercentageCommissionMax();
  206.                             $productActive = ($infoQse) ? (int) $infoQse->active 0;
  207.                             $qseCommissionPercentage $productCommission->getQsecommissionpercentage();
  208.                             $tarifaCommissionPercentage $productCommission->getTacommissionpercentage();
  209.                             $activeDetail $agentCommission->getActiveDetail();
  210.                             $isAgent true;
  211.                         } else {
  212.                             $session->set($transactionId.'_isActiveQse'false);
  213.                         }
  214.                     }
  215.                 }
  216.                 $uniqueID = [];
  217.                 $count 0;
  218.                 $ProductInfoUnsort = [];
  219.                 $productPrices = [];
  220.                 $imgBlob $parameters->blob_azure_assets;
  221.                 $uriAssistCard $imgBlob.'assets/common_assets/img/insurance/logo-assit-card.png';
  222.                 $uriUniversalAssistance $imgBlob.'assets/common_assets/img/insurance/logo-ua.svg';
  223.                 $uriAxaAssistance $imgBlob.'assets/common_assets/img/insurance/logo-axa.svg';
  224.                 // stores the plan restriction of the universal assistance.
  225.                 $arrPlanRestrictions = [];
  226.                 $arrDataExtra = [];
  227.                 $arrAttributesPlanRestrictions = [];
  228.                 foreach ($response->Message->OTA_InsuranceQuoteRS->PlanForQuoteRS as $Info) {
  229.                     switch ((string) $Info['Name']) {
  230.                         case 'AC CORP 60 D'// este producto no debe mostrarse
  231.                             break;
  232.                         default:
  233.                             if (!in_array($Info['PlanID'], $uniqueID)) {
  234.                                 $uniqueID[] = (string) $Info['PlanID'];
  235.                                 if (empty($Info->QuoteDetail->ProviderCompany['Division'])) {
  236.                                     $name explode(' '$Info['Name']);
  237.                                     $Info->QuoteDetail->ProviderCompany['Division'] = ucwords(mb_strtolower($name[0].'.pdf'));
  238.                                 }
  239.                                 $company = (string) $Info->QuoteDetail->ProviderCompany['CompanyShortName'];
  240.                                 $InsuranceInfo $em->getRepository(\Aviatur\InsuranceBundle\Entity\InsuranceInformation::class)->findBy(['name' => $Info->QuoteDetail->ProviderCompany['Division']]);
  241.                                 $ProductInfoUnsort[$count]['Description'] = isset($InsuranceInfo[0]) ? $InsuranceInfo[0]->getDescription() : null;
  242.                                 $ProductInfoUnsort[$count]['isFront'] = $isFront;
  243.                                 if ('Assist Card' == $company) {
  244.                                     $PlanRestrictions = [];
  245.                                     $PlanRestrictionString = [];
  246.                                     $ProductInfoUnsort[$count]['uriLogo'] = $uriAssistCard;
  247.                                     if ((== $agency->getId() || == $agency->getId() || 152 == $agency->getId()) && !$isFront) { // cambios solo para .com
  248.                                         $InsuranceInfo $em->getRepository(\Aviatur\InsuranceBundle\Entity\InsuranceInformation::class)->findBy(['name' => $Info->QuoteDetail->ProviderCompany['Division'], 'title' => null]);
  249.                                         if (null != $InsuranceInfo) {
  250.                                             $InsuranceInfo json_decode($InsuranceInfo[0]->getDescription(), true);
  251.                                             $PlanRestrictions[] = $InsuranceInfo['amount'];
  252.                                             foreach ($InsuranceInfo['PlanRestrictions'] as $PlanRestriction) {
  253.                                                 $PlanRestrictions[] = $PlanRestriction;
  254.                                                 $PlanRestrictionString[] = $PlanRestriction[2].'--'.$PlanRestriction[0].'--'.$PlanRestriction[1].'--';
  255.                                             }
  256.                                             $ProductInfoUnsort[$count]['PlanRestrictions'] = $PlanRestrictions;
  257.                                             $ProductInfoUnsort[$count]['PlanRestrictionString'] = $PlanRestrictionString;
  258.                                         }
  259.                                     } else {
  260.                                         if ('NACIONAL.pdf' == $Info->QuoteDetail->ProviderCompany['Division'] || 'Nacional.pdf' == $Info->QuoteDetail->ProviderCompany['Division']) {
  261.                                             $ProductInfoUnsort[$count]['Description'] = null;
  262.                                         }
  263.                                     }
  264.                                 } elseif ('Universal Assistance' == $company) {
  265.                                     $ProductInfoUnsort[$count]['uriLogo'] = $uriUniversalAssistance;
  266.                                     foreach ($Info->QuoteDetail->PlanRestrictions as $PlanInfo) {
  267.                                         $length $PlanInfo->PlanRestriction->count(); // count for each card the details of the plan restriction
  268.                                         for ($i 0$i $length; ++$i) {
  269.                                             $attributes $PlanInfo->PlanRestriction[$i]->attributes();
  270.                                             if ($attributes->count() > 0) {
  271.                                                 $ProductInfoUnsort[$count]['attributtes'] = $attributes['Name'].'--'.$attributes['Code'].'--'.$attributes['CodeContext'].'--';
  272.                                                 $arrAttributesPlanRestrictions[] = $ProductInfoUnsort[$count]['attributtes'];
  273.                                                 $arrPlanRestrictions[] = $attributes;
  274.                                             } else {
  275.                                                 // elementos sin atributos.
  276.                                                 $data $PlanInfo->PlanRestriction[$i];
  277.                                                 $key substr($data0strrpos($data':'));
  278.                                                 $value substr($datastrrpos($data':') + 1);
  279.                                                 $arrDataExtra[$key] = $value;
  280.                                             }
  281.                                         }
  282.                                         // generate dynamically key - value -> elementos sin atributos
  283.                                         if (sizeof($arrDataExtra) > 0) {
  284.                                             foreach ($arrDataExtra as $key => $value) {
  285.                                                 $ProductInfoUnsort[$count][$key] = $value;
  286.                                             }
  287.                                         }
  288.                                         $ProductInfoUnsort[$count]['PlanRestrictions'] = $arrPlanRestrictions;
  289.                                         $ProductInfoUnsort[$count]['CountPlanRestrictions'] = sizeof($arrPlanRestrictions);
  290.                                         $arrPlanRestrictions = [];
  291.                                         $arrDataExtra = [];
  292.                                     }
  293.                                 }elseif ('Axa Assistance' == $company) {
  294.                                     $ProductInfoUnsort[$count]['uriLogo'] = $uriAxaAssistance;
  295.                                     $ProductInfoUnsort[$count]['PlanRestrictions'] = [];
  296.                                     $ProductInfoUnsort[$count]['PlanRestrictionString'] = [];
  297.                                 }
  298.                                 $ProductInfoUnsort[$count]['PlanID'] = (string) $Info['PlanID'];
  299.                                 $ProductInfoUnsort[$count]['Name'] = (string) $Info['Name'];
  300.                                 $ProductInfoUnsort[$count]['TypeID'] = (string) $Info['TypeID'];
  301.                                 $ProductInfoUnsort[$count]['TypeProduct'] = (string) $Info['Type'];
  302.                                 $ProductInfoUnsort[$count]['agencyId'] = (string) $agency->getId();
  303.                                 $ProductInfoUnsort[$count]['correlationId'] = '';
  304.                                 if ('Universal Assistance' == $company) {
  305.                                     $ProductInfoUnsort[$count]['Name'] = (string) $ProductInfoUnsort[$count]['headline'];
  306.                                     /*
  307.                                       Nota:
  308.                                       Es necesario el correlationId para la emision en universal assitance.
  309.                                       Normalmente deberia llegar en el atributo CorrelationId del rq en InsuranceQuote,
  310.                                       como no llega, se opto por mandarlo en el atributo TypeID ya que no se estaba usando en UniversalAssitance.
  311.                                       Se mantiene la misma estrutura del XML por estandar OTA.
  312.                                      */
  313.                                     $ProductInfoUnsort[$count]['TypeID'] = '';
  314.                                     $ProductInfoUnsort[$count]['correlationId'] = (string) $Info['TypeID'];
  315.                                 }
  316.                                 for ($i 0$i sizeof($providers); ++$i) {
  317.                                     if ((130 == $providers[$i] || 90 == $providers[$i]) && ('Universal Assistance' == $company)) {
  318.                                         $ProductInfoUnsort[$count]['providerId'] = $providers[$i];
  319.                                     } elseif ((69 == $providers[$i] || 44 == $providers[$i]) && ('Assist Card' == $company)) {
  320.                                         $ProductInfoUnsort[$count]['providerId'] = $providers[$i];
  321.                                     } elseif ((162 == $providers[$i] || 122 == $providers[$i]) && ('Axa Assistance' == $company)) {
  322.                                         $ProductInfoUnsort[$count]['providerId'] = $providers[$i];
  323.                                     }
  324.                                 }
  325.                                 $ProductInfoUnsort[$count]['RPH'] = (string) $Info['RPH'];
  326.                                 $ProductInfoUnsort[$count]['CompanyShortName'] = (string) $Info->QuoteDetail->ProviderCompany['CompanyShortName'];
  327.                                 $ProductInfoUnsort[$count]['Division'] = (string) $Info->QuoteDetail->ProviderCompany['Division'];
  328.                                 if ('$' == (string) $Info->PlanCost['CurrencyCode']) {
  329.                                     $ProductInfoUnsort[$count]['CurrencyCode'] = 'COP';
  330.                                 } else {
  331.                                     $ProductInfoUnsort[$count]['CurrencyCode'] = 'USD';
  332.                                 }
  333.                                 $baseAmount $ID[(string) $Info['PlanID']]['Amount'];
  334.                                 $chargesAmount $ID[(string) $Info['PlanID']]['Charges'];
  335.                                 $totalAmount $baseAmount $chargesAmount;
  336.                                 $ProductInfoUnsort[$count]['baseAmount'] = $baseAmount;
  337.                                 $ProductInfoUnsort[$count]['chargesAmount'] = $chargesAmount;
  338.                                 $ProductInfoUnsort[$count]['totalAmount'] = $totalAmount;
  339.                                 /*                                 * ************************ Commission Agent QSE or Percentage **************** */
  340.                                 if ($isAgent) {
  341.                                     $commissionFare number_format((float) $Info->PlanCost->Charges->Charge['Percent'] * (float) $tarifaCommissionPercentage2'.'''); //round((float) $Info->PlanCost->Charges->Charge['Percent'] * $tarifaCommissionPercentage);
  342.                                     $commissionFareAll round($baseAmount * ((float) $Info->PlanCost->Charges->Charge['Percent'] / 100));
  343.                                     $commissionFare round($baseAmount * ($commissionFare 100));
  344.                                     $ProductInfoUnsort[$count]['AmountTaAgent'] = $commissionFareAll;
  345.                                     $ProductInfoUnsort[$count]['CommissionTaAgent'] = $commissionFare;
  346.                                     $ProductInfoUnsort[$count]['CommissionActive'] = $productActive;
  347.                                     $ProductInfoUnsort[$count]['PercentageTarifa'] = (float) $Info->PlanCost->Charges->Charge['Percent'];
  348.                                     if ('0' == $productActive) {
  349.                                         $ProductInfoUnsort[$count]['CommissionAgent'] = $agentQseAmount;
  350.                                         $commissionPay round(($agentQseAmount 1.19) * $qseCommissionPercentage);
  351.                                         $ProductInfoUnsort[$count]['CommissionPay'] = $commissionPay;
  352.                                         $ProductInfoUnsort[$count]['AmountPay'] = $commissionPay $commissionFare;
  353.                                     } elseif ('1' == $productActive) {
  354.                                         $totalValue $ProductInfoUnsort[$count]['totalAmount'];
  355.                                         $valueCommissionPercentage round($totalValue $productpercentage);
  356.                                         $ProductInfoUnsort[$count]['CommissionAgent'] = $valueCommissionPercentage;
  357.                                         $commissionPay round(($valueCommissionPercentage 1.19) * $qseCommissionPercentage);
  358.                                         $ProductInfoUnsort[$count]['CommissionPay'] = $commissionPay;
  359.                                         $ProductInfoUnsort[$count]['AmountPay'] = $commissionPay $commissionFare;
  360.                                     }
  361.                                     $ProductInfoUnsort[$count]['totalAmount'] += round($ProductInfoUnsort[$count]['CommissionAgent']);
  362.                                     $ProductInfoUnsort[$count]['activeDetail'] = $activeDetail;
  363.                                 }
  364.                                 $ProductInfoUnsort[$count]['Amount'] = $ID['Amount'][(string) $Info['PlanID']];
  365.                                 //$ProductInfoUnsort[$count]['Information'] = base64_encode($ProductInfoUnsort[$count]['TypeID'] . '*' . $ProductInfoUnsort[$count]['Name'] . '*' . $ProductInfoUnsort[$count]['CurrencyCode'] . '*' . $ProductInfoUnsort[$count]['totalAmount'] . '*' . json_encode($ProductInfoUnsort[$count]['Amount']) . '*' . $ID[(string) $Info['PlanID']]["ChargesSingle"] . '*' . (string) $Info->PlanCost->Charges->Charge["Percent"]);
  366.                                 $ProductInfoUnsort[$count]['Information'] = $ProductInfoUnsort[$count]['TypeID'].'*'.$ProductInfoUnsort[$count]['Name'].'*'.$ProductInfoUnsort[$count]['CurrencyCode'].'*'.$ProductInfoUnsort[$count]['totalAmount'].'*'.json_encode($ProductInfoUnsort[$count]['Amount']).'*'.$ID[(string) $Info['PlanID']]['ChargesSingle'].'*'.(string) $Info->PlanCost->Charges->Charge['Percent'];
  367.                                 if ($isAgent) {
  368.                                     $ProductInfoUnsort[$count]['Information'] .= '*'.$ProductInfoUnsort[$count]['CommissionAgent'].'*'.$ProductInfoUnsort[$count]['CommissionActive'].'*'.$ProductInfoUnsort[$count]['CommissionPay'].'*'.$ProductInfoUnsort[$count]['activeDetail'].'*'.$ProductInfoUnsort[$count]['AmountTaAgent'].'*'.$ProductInfoUnsort[$count]['CommissionTaAgent'].'*'.$ProductInfoUnsort[$count]['AmountPay'].'*'.$ProductInfoUnsort[$count]['PercentageTarifa'];
  369.                                 }
  370.                                 if ('Universal Assistance' == $company || 'Assist Card' == $company || 'Axa Assistance' == $company) {
  371.                                     $ProductInfoUnsort[$count]['InformationCard'] = $ProductInfoUnsort[$count]['uriLogo'].'*'.$ProductInfoUnsort[$count]['CompanyShortName'].'*'.$ProductInfoUnsort[$count]['Division'].'*'.$diffDays;
  372.                                     if ('Universal Assistance' == $company) {
  373.                                         $result implode($arrAttributesPlanRestrictions);
  374.                                         $ProductInfoUnsort[$count]['InformationCard'] .= '*'.$result.'*'.$ProductInfoUnsort[$count]['bodyCopy'].'*'.$ProductInfoUnsort[$count]['CountPlanRestrictions'];
  375.                                     } elseif ('Assist Card' == $company) {
  376.                                         if (isset($ProductInfoUnsort[$count]['PlanRestrictionString'])) {
  377.                                             $result implode($ProductInfoUnsort[$count]['PlanRestrictionString']);
  378.                                             $ProductInfoUnsort[$count]['InformationCard'] .= '*'.$result.'*'.(string) $agency->getId().'*'.(string) $isFront;
  379.                                         } elseif (isset($InsuranceInfo[0])) {
  380.                                             $ProductInfoUnsort[$count]['InformationCard'] .= '*'.$ProductInfoUnsort[$count]['Description'].'*'.(string) $agency->getId().'*'.(string) $isFront;
  381.                                         } else {
  382.                                             $ProductInfoUnsort[$count]['InformationCard'] .= '*'.''.'*'.(string) $agency->getId().'*'.(string) $isFront;
  383.                                         }
  384.                                     }elseif ('Axa Assistance' == $company) {
  385.                                         $ProductInfoUnsort[$count]['InformationCard'] .= '*'.''.'*'.(string) $agency->getId().'*'.(string) $isFront;
  386.                                     }
  387.                                     $arrAttributesPlanRestrictions = [];
  388.                                 }
  389.                                 
  390.                                 $ProductInfoUnsort[$count]['Information'] = base64_encode($ProductInfoUnsort[$count]['Information']);
  391.                                 $ProductInfoUnsort[$count]['InformationCard'] = base64_encode($ProductInfoUnsort[$count]['InformationCard']);
  392.                                 $productPrices[$count] = $ProductInfoUnsort[$count]['Amount'];
  393.                                 ++$count;
  394.                             }
  395.                     }
  396.                 }
  397.             }
  398.             $ProductInfo = [];
  399.             if ($productPrices) {
  400.                 asort($productPrices);
  401.                 foreach ($productPrices as $count => $price) {
  402.                     $ProductInfo[] = $ProductInfoUnsort[$count];
  403.                 }
  404.             } else {
  405.                 $ProductInfo $ProductInfoUnsort;
  406.             }
  407.             unset($ProductInfoUnsort);
  408.             $infoInsurance $response->Message->asXml();
  409.             if ('flight' == $method) {
  410.                 $session->set($transactionId.'[assist]'.'[infoInsurance]'$infoInsurance);
  411.                 $session->set($transactionId.'[assist]'.'[infoInsuranceFlight]'json_encode($variable));
  412.                 $session->set($transactionId.'[assist]'.'[infoInsuranceAvaibility]'$infoInsurance);
  413.                 $session->set($transactionId.'[availability_url_insurance]'$requestUrl);
  414.                 $variable['transactionId'] = $transactionId;
  415.             } else {
  416.                 $transactionId = (string) $response->Message->OTA_InsuranceQuoteRS['TransactionIdentifier'];
  417.                 $session->set($transactionId.'[assist]'.'[infoInsurance]'$infoInsurance);
  418.                 $variable['transactionId'] = $transactionId;
  419.             }
  420.             $variable['passenger'] = $passenger;
  421.             $variable['domain_file'] = $domain_file;
  422.             $variable['method'] = $method;
  423.             $variable['OfficeId'] = $OfficeId[1];
  424.             $variable['AgencyId'] = substr($OfficeId[0], 1);
  425.             $variable['echoToken'] = $echoToken;
  426.             if ($session->has('operatorId')) {
  427.                 $userFront simplexml_load_string($session->get('front_user'));
  428.                 $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  429.                 $variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
  430.                 $variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE02);
  431.             }
  432.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/AjaxAvailability.html.twig');
  433.             if (false == $compare) {
  434.                 return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo'variable' => $variable]);
  435.             } else {
  436.                 $dispo_ajax $fullRequest->get('dispo_ajax');
  437.                 if ($response['error'] || == $validation->getValue()) {
  438.                     if (isset($dispo_ajax)) {
  439.                         $avaibility 0;
  440.                         $response = new Response($avaibility);
  441.                         $response->headers->set('Content-Type''application/json');
  442.                         return $response;
  443.                     } else {
  444.                         if (== $validation->getValue()) {
  445.                             $avaibility 0;
  446.                             $response = new Response($avaibility);
  447.                             $response->headers->set('Content-Type''application/json');
  448.                             return $response;
  449.                         } else {
  450.                             return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo'variable' => $variable]);
  451.                         }
  452.                     }
  453.                 } else {
  454.                     return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo'variable' => $variable]);
  455.                 }
  456.             }
  457.         } else {
  458.             $cookieArray = [
  459.                 'destination' => $destiny,
  460.                 'date1' => $dateEntry,
  461.                 'date2' => $dateEnd,
  462.                 'passenger' => $passenger,
  463.                 'providerId' => $providersAgency,
  464.                 'echoToken' => $echoToken,
  465.             ];
  466.             $Birthdate '';
  467.             for ($i 1$i <= $passenger; ++$i) {
  468.                 if ('flight' == $method) {
  469.                     if (== $passenger) {
  470.                         $dateBirth[] = $infoBirth[0]['BirthDate'];
  471.                         $Birthdate $infoBirth[0]['BirthDate'];
  472.                         $cookieArray['birthDate'] = $Birthdate;
  473.                     } else {
  474.                         $dateBirth[] = $infoBirth[($i 1)]['BirthDate'];
  475.                         $Birthdate .= $infoBirth[($i 1)]['BirthDate'].'*';
  476.                         $cookieArray['birthDate'] = substr($Birthdate0, -1);
  477.                     }
  478.                 } else {
  479.                     if (== $passenger) {
  480.                         $dateBirth[] = $fullRequest->attributes->get('birth1');
  481.                         $Birthdate $fullRequest->attributes->get('birth1');
  482.                         $cookieArray['birthDate'] = $Birthdate;
  483.                     } else {
  484.                         $dateBirth[] = $fullRequest->attributes->get('birth'.$i);
  485.                         $Birthdate .= $fullRequest->attributes->get('birth'.$i).'*';
  486.                         $cookieArray['birthDate'] = substr($Birthdate0, -1);
  487.                     }
  488.                 }
  489.                 $calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i 1)]);
  490.                 if ($calculoEdades[($i 1)] >= && $calculoEdades[($i 1)] < 2) {
  491.                     $passanger_type[] = 1//INF
  492.                 } elseif ($calculoEdades[($i 1)] >= && $calculoEdades[($i 1)] < 12) {
  493.                     $passanger_type[] = 2//CHD
  494.                 } else {
  495.                     $passanger_type[] = 3//ADT
  496.                 }
  497.             }
  498.             $cookieArray['Age'] = $calculoEdades;
  499.             $cookieArray['passanger_type'] = $passanger_type;
  500.             $cookieArray['birth'] = $dateBirth;
  501.             $cookieArray['domain_file'] = $domain_file;
  502.             $cookieArray['method'] = $method;
  503.             $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/availability.html.twig');
  504.             if ($agency->getDomainsecure() == $agency->getDomain() && '443' !== $agency->getCustomport()) {
  505.                 $safeUrl 'https://'.$agency->getDomain();
  506.             } else {
  507.                 $safeUrl 'https://'.$agency->getDomainsecure();
  508.             }
  509.             $cookieLastSearch $searchInsuranceCookie->searchInsuranceCookie(['insurance' => base64_encode(json_encode($cookieArray))]);
  510.             $regionMap = [
  511.                 '1' => 'Norte America',
  512.                 '2' => 'Europa - Medio Oriente',
  513.                 '3' => 'Centro America & Caribe',
  514.                 '4' => 'Sur America',
  515.                 '5' => 'Africa',
  516.                 '6' => 'Asia',
  517.                 '7' => 'Oceania',
  518.                 '8' => 'Colombia',
  519.             ];
  520.             $availableArray array_merge($cookieArray, ['destinationLabel' => $regionMap[$destiny]]);
  521.             if (!$isFront) {
  522.                 // PIXELES INFORMATION
  523.                 $pixel['partner_datalayer'] = [
  524.                     'enabled' => true,
  525.                     'event' => 'seguros_search',
  526.                     'dimension1' => $destiny,
  527.                     'dimension3' => $dateEntry,
  528.                     'dimension4' => $dateEnd,
  529.                     'dimension5' => 'Seguro de Viaje',
  530.                     'dimension10' => $passenger,
  531.                     'dimension12' => 'busqueda-seguro',
  532.                     'ecommerce' => [
  533.                         'currencyCode' => 'COP',
  534.                     ],
  535.                 ];
  536. //                $pixel['dataxpand'] = true;
  537.                 $pixelInfo $aviaturPixeles->verifyPixeles($pixel'insurance''availability'$agency->getAssetsFolder(), false);
  538.             }
  539.             $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  540.             if (null != $pointRedemption) {
  541.                 $points 0;
  542.                 if ($fullRequest->request->has('pointRedemptionValue')) {
  543.                     $points $fullRequest->request->get('pointRedemptionValue');
  544.                     $session->set('point_redemption_value'$points);
  545.                 } elseif ($fullRequest->query->has('pointRedeem')) {
  546.                     $points $fullRequest->query->get('pointRedeem');
  547.                     $session->set('point_redemption_value'$points);
  548.                 } elseif ($session->has('point_redemption_value')) {
  549.                     $points $session->get('point_redemption_value');
  550.                 }
  551.                 $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  552.             }
  553.             $response $this->render($urlAvailability, [
  554.                 'ajaxUrl' => $requestUrl,
  555.                 'availableArrayInsurance' => $availableArray,
  556.                 'inlineEngine' => true,
  557.                 'safeUrl' => $safeUrl,
  558.                 'cookieLastSearch' => $cookieLastSearch,
  559.                 'pixel_info' => $pixelInfo,
  560.                 'pointRedemption' => $pointRedemption,
  561.             ]);
  562.             $response->headers->setCookie(new Cookie('_availability_array[insurance]'base64_encode(json_encode($cookieArray)), (time() + 3600 24 7), '/'));
  563.             return $response;
  564.         }
  565.         return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo'variable' => $variable]);
  566.     }
  567.     public function formularioAction(Request $fullRequestAviaturPixeles $aviaturPixelesAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBagLoginManagerInterface $loginManagerAviaturWebService $aviaturWebService)
  568.     {
  569.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  570.         
  571.         $transactionId null;
  572.         $typePerson = [];
  573.         $pixel = [];
  574.         $server $fullRequest->server;
  575.         $isAgent false;
  576.         $em $registry->getManager();
  577.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  578.         $request $fullRequest->request;
  579.         $agencyFolder $twigFolder->twigFlux();
  580.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  581.         $paymentOptions = [];
  582.         if (true === $request->has('whitemarkDataInfo')) {
  583.             $session->set('whitemarkDataInfo'json_decode($request->get('whitemarkDataInfo'), true));
  584.         }
  585.         if (true === $request->has('userLogin') && '' != $request->get('userLogin') && null != $request->get('userLogin')) {
  586.             $user $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($request->get('userLogin'));
  587.             $this->authenticateUser($user$loginManager);
  588.         }
  589.         foreach ($paymentMethodAgency as $payMethod) {
  590.             $paymentCode $payMethod->getPaymentMethod()->getCode();
  591.             if (!in_array($paymentCode$paymentOptions) && 'davivienda' != $paymentCode) {
  592.                 $paymentOptions[] = $paymentCode;
  593.             }
  594.         }
  595.         $cybersource = [];
  596.         if (in_array('cybersource'$paymentOptions)) {
  597.             $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  598.             $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  599.         }
  600.         foreach ($paymentOptions as $key => $paymentOption) {
  601.             if ('cybersource' == $paymentOption) {
  602.                 unset($paymentOptions[$key]); // strip from other renderizable payment methods
  603.             }
  604.         }
  605.         $banks = [];
  606.         if (in_array('pse'$paymentOptions)) {
  607.             $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  608.         }
  609.         $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_insurance');
  610.         $typeGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  611.         $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  612.         $publicKey $aviaturEncoder->aviaturRandomKey();
  613.         $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($request), $publicKey);
  614.         $formUserInfo = new FormUserInfo();
  615.         $formUserInfo->setInfo($encodedInfo);
  616.         $formUserInfo->setPublicKey($publicKey);
  617.         $em->persist($formUserInfo);
  618.         $em->flush();
  619.         $routeName $fullRequest->get('_route');
  620.         $fromCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('USD');
  621.         $toCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('COP');
  622.         $TRM $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->findOneBy(['fromCurrency' => $fromCurrency'toCurrency' => $toCurrency], ['id' => 'DESC']);
  623.         $adt 0;
  624.         $chd 0;
  625.         $inf 0;
  626.         if (true === $request->has('transactionId')) {
  627.             $transactionId $request->get('transactionId');
  628.             $session->set($transactionIdSessionName$transactionId);
  629.         } elseif (true === $session->has($transactionIdSessionName)) {
  630.             $transactionId $session->get($transactionIdSessionName);
  631.         }
  632.         /* Aplica cuando una asistencia es internacional, para no realizar discriminación de los impuestos en update_payment_data */
  633.         $typeId base64_decode($request->get('TypeID'));
  634.         $arrayTypeId explode('*'$typeId);
  635.         $assistName strtolower((string)$arrayTypeId[1]);
  636.         if(strpos($assistName'nacional') === false) {
  637.             $session->set($transactionId.'[assist][avoiding_taxes]'1);
  638.         }
  639.         $session->set($transactionId.'[assist][request]'$request);
  640.         //$session->set($transactionId.'[assist][fullrequest]', $fullRequest);
  641.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  642.             $user $this->getUser();
  643.             $emailuser $user->getemail();
  644.             $agent $user->getAgent();
  645.             if (!empty($agent[0])) {
  646.                 $idagent $agent[0]->getid();
  647.                 $nombreagente $user->getFirstname().' '.$user->getLastname();
  648.                 $agencyFolder $twigFolder->twigFlux();
  649.                 $isAgent true;
  650.             }
  651.         }
  652.         if ('aviatur_insurance_form_secure' == $routeName) {
  653.             $twig_readonly false;
  654.             $session->set($transactionId.'[assist][user_info]'$formUserInfo->getId());
  655.             $session->set($transactionId.'[assist][provider]'$request->get('providerId'));
  656.             $session->set($transactionId.'[assist][detail]'$request);
  657.             $TypeID explode('*'base64_decode($request->get('TypeID')));
  658.             $x_total_amount $TypeID[3];
  659.             // $x_base_amount = str_replace(array('[',']'),'',$TypeID[4]);
  660.             $x_base_amount $x_total_amount;
  661.             if ($isAgent) {
  662.                 $x_base_amount -= (float) $TypeID[7];
  663.                 $commissionAgent $TypeID[7];
  664.                 $commissionActive $TypeID[8];
  665.                 $commissionPay $TypeID[9];
  666.                 $activeDetail $TypeID[10];
  667.                 $amountTa $TypeID[11];
  668.                 $commissionTa $TypeID[12];
  669.                 $amountPay $TypeID[13];
  670.                 $percentageTarifa $TypeID[14];
  671.             }
  672.             $method $request->get('method');
  673.             if ('flight' == $method) {
  674.                 $passanger json_decode($session->get($transactionId.'[assist]'.'[infoInsuranceFlight]'), true);
  675.                 $infoDataFlight json_decode($session->get($transactionId.'[crossed]'.'[infoDataFlight]'), true);
  676.                 $postData json_decode($session->get($transactionId.'[flight][detail_data_flight]'));
  677. //                $passangerInfo = $postData->PI;
  678. //                $billingData = $postData->BD;
  679. //                $contactData = $postData->CD;
  680.                 $passanger_type $passanger['CoveredTraveler'];
  681.                 for ($i 0$i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
  682.                     if (== $passanger_type[$i]['passanger_type']) {
  683.                         ++$inf;
  684.                     } elseif (== $passanger_type[$i]['passanger_type']) {
  685.                         ++$chd;
  686.                     } else {
  687.                         ++$adt;
  688.                     }
  689.                 }
  690.             } else {
  691.                 $passanger_type json_decode($request->get('passanger_type'));
  692.                 for ($i 0$i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
  693.                     if (== $passanger_type[$i]) {
  694.                         ++$inf;
  695.                     } elseif (== $passanger_type[$i]) {
  696.                         ++$chd;
  697.                     } else {
  698.                         ++$adt;
  699.                     }
  700.                 }
  701.             }
  702.             $variables = [
  703.                 'transactionId' => base64_encode($transactionId),
  704.                 'destiny' => $request->get('destiny'),
  705.                 'dateEntry' => $request->get('dateEntry'),
  706.                 'dateEnd' => $request->get('dateEnd'),
  707.                 'passenger' => $request->get('passenger'),
  708.                 'birth' => $request->get('birth'),
  709.                 'id' => $request->get('id'),
  710.                 'TypeID' => base64_decode($request->get('TypeID')),
  711.                 'informationCard' => base64_decode($request->get('informationCard')),
  712.                 'providerId' => $request->get('providerId'),
  713.                 'method' => $request->get('method'),
  714.                 'passanger_type' => $passanger_type,
  715.                 'Age' => json_decode($request->get('Age')),
  716.                 'x_total_amount' => $x_total_amount,
  717.                 'x_base_amount' => $x_base_amount,
  718.                 'reintento' => false,
  719.                 'payment_type_form_name' => 'paymentForm',
  720.                 'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  721.                 'echoToken' => $request->get('echoToken'),
  722.             ];
  723.             if ($isAgent) {
  724.                 $variables['commissionAgent'] = $commissionAgent;
  725.                 $variables['commissionActive'] = $commissionActive;
  726.                 $variables['commissionPay'] = $commissionPay;
  727.                 $variables['commissionTa'] = $commissionTa;
  728.                 $variables['amountTa'] = $amountTa;
  729.                 $variables['activeDetail'] = $activeDetail;
  730.                 $variables['amountPay'] = $amountPay;
  731.                 $info_product = ['amountQse' => (float) $commissionAgent,
  732.                     'commissionQse' => (float) $commissionPay,
  733.                     'amountTa' => (float) $amountTa,
  734.                     'commissionTa' => (float) $commissionTa,
  735.                     'amountPay' => (float) $amountPay,
  736.                     'amountProduct' => $x_base_amount,
  737.                     'percentageTarifa' => isset($percentageTarifa) ? (float) $percentageTarifa 0, ];
  738.                 $session->set($transactionId.'_agentInfoTransaction'$info_product);
  739.             }
  740.         } else {
  741.             $twig_readonly true;
  742.             $detail $session->get($transactionId.'[assist]'.'[detail]');
  743.             $detail_data_insurance json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
  744.             $infoclient $session->get($transactionId.'[assist]'.'[infoclient]');
  745.             $TypeID explode('*'base64_decode($detail->get('TypeID')));
  746.             $x_total_amount $TypeID[3];
  747.             $method $detail->get('method');
  748.             if ('flight' == $method) {
  749.                 $passanger json_decode($session->get($transactionId.'[assist]'.'[infoInsuranceFlight]'), true);
  750.                 $passanger_type $passanger['CoveredTraveler'];
  751.                 for ($i 0$i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
  752.                     if (== $passanger_type[$i]['passanger_type']) {
  753.                         ++$inf;
  754.                     } elseif (== $passanger_type[$i]['passanger_type']) {
  755.                         ++$chd;
  756.                     } else {
  757.                         ++$adt;
  758.                     }
  759.                 }
  760.             } else {
  761.                 $passanger_type json_decode($detail->get('passanger_type'));
  762.                 for ($i 0$i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
  763.                     if (== $passanger_type[$i]) {
  764.                         ++$inf;
  765.                     } elseif (== $passanger_type[$i]) {
  766.                         ++$chd;
  767.                     } else {
  768.                         ++$adt;
  769.                     }
  770.                 }
  771.             }
  772.             $billingData $detail_data_insurance->BD;
  773.             $variables = [
  774.                 'transactionId' => base64_encode($transactionId),
  775.                 'destiny' => $detail->get('destiny'),
  776.                 'dateEntry' => $detail->get('dateEntry'),
  777.                 'dateEnd' => $detail->get('dateEnd'),
  778.                 'passenger' => $detail->get('passenger'),
  779.                 'birth' => $detail->get('birth'),
  780.                 'id' => $detail->get('id'),
  781.                 'TypeID' => base64_decode($detail->get('TypeID')),
  782.                 'informationCard' => base64_decode($detail->get('informationCard')),
  783.                 'providerId' => $detail->get('providerId'),
  784.                 'method' => $detail->get('method'),
  785.                 'passanger_type' => json_decode($detail->get('passanger_type')),
  786.                 'Age' => json_decode($detail->get('Age')),
  787.                 'x_total_amount' => $x_total_amount,
  788.                 'reintento' => true,
  789.                 'infoPassengers' => $detail_data_insurance->PI,
  790.                 'infoclient' => $detail_data_insurance->BD,
  791.                 'payment_type_form_name' => 'paymentForm',
  792.                 'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  793.                 'echoToken' => $request->get('echoToken'),
  794.             ];
  795.         }
  796.         $typePerson[1] = [
  797.             'ADT' => $adt,
  798.             'CHD' => $chd,
  799.             'INF' => $inf,
  800.         ];
  801.         if ('flight' == $method) {
  802.             $information $session->get($transactionId.'[crossed]'.'[infoDataFlight]');
  803.             $objectInfo json_decode($information);
  804.             $variables['travelers'] = (array) $objectInfo->travelers;
  805.             $variables['facturation'] = $objectInfo->facturationResume;
  806.             if ('' == $variables['birth']) {
  807.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_insurance_prueba_secure'), '''No hay información'));
  808.             }
  809.         }
  810.         $session->set($transactionId.'[availability_url]'$server->get('HTTP_REFERER'));
  811.         $infoInsurance simplexml_load_string($session->get($transactionId.'[assist]'.'[infoInsurance]'));
  812.         $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/detail_form.html.twig');
  813.         $pixelInfo = [];
  814.         if (!$session->has('operatorId')) {
  815.             $pixel['partner_datalayer'] = [
  816.                 'event' => 'seguros_checkout',
  817.                 'dimension1' => $variables['destiny'],
  818.                 'dimension3' => $variables['dateEntry'],
  819.                 'dimension4' => $variables['dateEnd'],
  820.                 'dimension5' => 'Seguro de Viaje',
  821.                 'dimension10' => $variables['passenger'],
  822.                 'dimension12' => 'checkout-seguro',
  823.                 'ecommerce' => [
  824.                     'checkout' => [
  825.                         'products' => [
  826.                             'actionField' => "{'step': 1}",
  827.                             'name' => $TypeID[1],
  828.                             'price' => $x_total_amount,
  829.                             'brand' => 'assist card',
  830.                             'category' => 'Seguros',
  831.                             'variant' => $TypeID[1],
  832.                             'quantity' => $variables['passenger'],
  833.                         ],
  834.                     ],
  835.                 ],
  836.             ];
  837. //            $pixel['dataxpand'] = true;
  838.             $pixelInfo $aviaturPixeles->verifyPixeles($pixel'insurance''detail'$agency->getAssetsFolder(), $transactionId);
  839.             $variables['pixel_info'] = $pixelInfo;
  840.         }
  841.         $pointRedemption $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
  842.         if (null != $pointRedemption) {
  843.             $points 0;
  844.             if ($fullRequest->request->has('pointRedemptionValue')) {
  845.                 $points $fullRequest->request->get('pointRedemptionValue');
  846.                 $session->set('point_redemption_value'$points);
  847.             } elseif ($fullRequest->query->has('pointRedeem')) {
  848.                 $points $fullRequest->query->get('pointRedeem');
  849.                 $session->set('point_redemption_value'$points);
  850.             } elseif ($session->has('point_redemption_value')) {
  851.                 $points $session->get('point_redemption_value');
  852.             }
  853.             $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  854.         }
  855.         // dd($infoTravel);
  856.         /* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
  857.         /* Necesitamos crear un arreglo que tenga todos los rangos de IIN asociados a su franquicia y a sus límites de número de tarjeta */
  858.         $iinRecordsArray $aviaturWebService->getIINRanges($em);
  859.         $returnInfo = [
  860.             'billingData' => $billingData ?? null,
  861.             'services' => $typePerson,
  862.             'gender' => $typeGender,
  863.             'banks' => $banks,
  864.             'cybersource' => $cybersource,
  865.             'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
  866.             'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
  867.             'twig_readonly' => $twig_readonly,
  868.             'doc_type' => $typeDocument,
  869.             'variables' => $variables,
  870.             'conditions' => $conditions,
  871.             'paymentOptions' => $paymentOptions,
  872.             'pointRedemption' => $pointRedemption,
  873.             'pse' => in_array('pse'$paymentOptions) ? true false,
  874.             'safety' => in_array('safety'$paymentOptions) ? true false,
  875.             'ccranges' => $iinRecordsArray["ccranges"],
  876.             'ccfranchises' => $iinRecordsArray["ccfranchises"],
  877.         ];
  878.         return $this->render($urlAvailability$returnInfo);
  879.     }
  880.     public function prePaymentStep1Action(Request $requestTokenizerService $tokenizerServiceCustomerMethodPaymentService $customerMethodPaymentTokenStorageInterface $tokenStorageAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  881.     {
  882.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  883.         if ($request->isXmlHttpRequest()) {
  884.             $request $request->request;
  885.             $selectionData $request->get('SD');
  886.             $transactionId base64_decode($selectionData['selection']);
  887.             $billingData $request->get('BD');
  888.             $em $registry->getManager();
  889.             $postData $request->all();
  890.             $publicKey $aviaturEncoder->aviaturRandomKey();
  891.             if (isset($postData['PD']['card_num'])) {
  892.                 $postDataInfo $postData;
  893.                 if (isset($postDataInfo['PD']['cusPOptSelected'])) {
  894.                     $customerLogin $tokenStorage->getToken()->getUser();
  895.                     $infoMethodPaymentByClient $customerMethodPayment->getMethodsByCustomer($customerLogintrue);
  896.                     $cardToken $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
  897.                     $postDataInfo['PD']['card_num'] = $cardToken;
  898.                     $postData['PD']['card_num'] = $cardToken;
  899.                 } else {
  900.                     $postDataInfo['PD']['card_num'] = $tokenizerService->getToken($postData['PD']['card_num']);
  901.                 }
  902.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  903.             }
  904.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
  905.             $formUserInfo = new FormUserInfo();
  906.             $formUserInfo->setInfo($encodedInfo);
  907.             $formUserInfo->setPublicKey($publicKey);
  908.             $em->persist($formUserInfo);
  909.             $em->flush();
  910.             $session->set($transactionId.'[assist][user_info]'$formUserInfo->getId());
  911.             if ((true !== $session->has($transactionId.'[assist][retry]')) || (true !== $session->has($transactionId.'[assist][prepayment_check]'))) {
  912.                 if (true === $session->has($transactionId.'[assist][detail]')) {
  913.                     //$postData = $request->all();
  914.                     $session->set($transactionId.'[assist][detail_data_assist]'json_encode($postData));
  915.                     $passangersData $request->get('PI');
  916.                     $passangerNames = [];
  917.                     for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  918.                         $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  919.                         $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  920.                     }
  921.                     $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  922.                     if (== sizeof($nameWhitelist)) {
  923.                         $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  924.                         if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  925.                                 (sizeof($nameBlacklist)) ||
  926.                                 (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  927.                             return $this->json(['error' => 'error''message' => 'nombre inválido']);
  928.                         }
  929.                     }
  930.                     $isFront $session->has('operatorId');
  931.                     $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  932.                     if (false !== strpos($postData['PI']['first_name_1_1'], '***')) {
  933.                         $postData['PI']['first_name_1_1'] = $customer->getFirstname();
  934.                         $postData['PI']['last_name_1_1'] = $customer->getLastname();
  935.                         $postData['PI']['phone_1_1'] = $customer->getPhone();
  936.                         $postData['PI']['email_1_1'] = $customer->getEmail();
  937.                         $postData['PI']['address_1_1'] = $customer->getAddress();
  938.                         $postData['PI']['doc_num_1_1'] = $customer->getDocumentnumber();
  939.                     }
  940.                     if ($isFront) {
  941.                         $session->set($transactionId.'[assist][customer_email]'$postData['PI']['email_1_1']);
  942.                         $customer null;
  943.                         $ordersProduct null;
  944.                     } else {
  945.                         $ordersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
  946.                     }
  947.                     if (null == $ordersProduct) {
  948.                         $documentTypes $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  949.                         $arrayDocumentTypes = [];
  950.                         foreach ($documentTypes as $documentType) {
  951.                             $arrayDocumentTypes[$documentType->getExternalCode()] = $documentType->getId();
  952.                         }
  953.                         $genders $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  954.                         $arrayGenders = [];
  955.                         foreach ($genders as $gender) {
  956.                             $arrayGenders[$gender->getCode()] = $gender->getExternalCode();
  957.                         }
  958.                         $session->set($transactionId.'[assist][retry]'$aviaturPaymentRetryTimes);
  959.                         $detail $session->get($transactionId.'[assist][detail]');
  960.                         $cancelPenalties = (string) '';
  961.                         $ajaxUrl $this->generateUrl('aviatur_insurance_prepayment_step_2_secure');
  962.                         return $this->json(['cancelPenalties' => $cancelPenalties'ajax_url' => $ajaxUrl]);
  963.                     } else {
  964.                         $booking = [];
  965.                         $cus = [];
  966.                         foreach ($ordersProduct as $orderProduct) {
  967.                             $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  968.                             $paymentResponse json_decode($productResponse);
  969.                             array_push($booking'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
  970.                             if (isset($paymentResponse->x_approval_code)) {
  971.                                 array_push($cus$paymentResponse->x_approval_code);
  972.                             } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  973.                                 array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  974.                             }
  975.                         }
  976.                         return $this->json([
  977.                                     'error' => 'pending payments',
  978.                                     'message' => 'pending_payments',
  979.                                     'booking' => $booking,
  980.                                     'cus' => $cus,
  981.                         ]);
  982.                     }
  983.                 } else {
  984.                     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 inténtalo nuevamente')]);
  985.                 }
  986.             } else {
  987.                 $paymentData $request->get('PD');
  988.                 $paymentData json_decode(json_encode($paymentData));
  989.                 $json json_decode($session->get($transactionId.'[assist][order]'));
  990.                 if (!is_null($json)) {
  991.                     $json->ajax_url $this->generateUrl('aviatur_insurance_prepayment_step_2_secure');
  992.                     // reemplazar datos de pago por los nuevos.
  993.                     $oldPostData json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
  994.                     if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
  995.                         if (isset($paymentData->cusPOptSelected)) {
  996.                             $customerLogin $tokenStorage->getToken()->getUser();
  997.                             $infoMethodPaymentByClient $customerMethodPayment->getMethodsByCustomer($customerLogintrue);
  998.                             $card_num_token $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  999.                         } else {
  1000.                             $card_num_token $tokenizerService->getToken($paymentData->card_num);
  1001.                         }
  1002.                         $card_values = ['card_num_token' => $card_num_token'card_num' => $paymentData->card_num];
  1003.                     }
  1004.                     unset($oldPostData->PD);
  1005.                     $oldPostData->PD $paymentData;
  1006.                     if (isset($card_num_token)) {
  1007.                         $oldPostData->PD->card_values $card_values;
  1008.                     }
  1009.                     $session->set($transactionId.'[assist][detail_data_assist]'json_encode($oldPostData));
  1010.                     $response = new Response(json_encode($json));
  1011.                     $response->headers->set('Content-Type''application/json');
  1012.                     return $response;
  1013.                 } else {
  1014.                     return $this->json(['error' => 'fatal''message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
  1015.                 }
  1016.             }
  1017.         } else {
  1018.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''Acceso no autorizado'));
  1019.         }
  1020.     }
  1021.     public function prePaymentStep2Action(
  1022.         Request $request,
  1023.         OrderController $orderController,
  1024.         AuthorizationCheckerInterface $authorizationChecker,
  1025.         AviaturErrorHandler $aviaturErrorHandler,
  1026.         SessionInterface $session,
  1027.         ManagerRegistry $registry,
  1028.         InsuranceService $insuranceService,
  1029.         AviaturWebService $aviaturWebService,
  1030.         ParameterBagInterface $parameterBag,
  1031.         \Swift_Mailer $mailer
  1032.         )
  1033.     {
  1034.         $order = [];
  1035.         if ($request->isXmlHttpRequest()) {
  1036.             $em $registry->getManager();
  1037.             // $request = $request->request;
  1038.             $selectionData $request->get('SD');
  1039.             $transactionId base64_decode($selectionData['selection']);
  1040.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1041.             $billingData $request->get('BD');
  1042.             if (empty($billingData)) {
  1043.                 $detail_data_assist json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
  1044.                 $billingData = (array) $detail_data_assist->BD;
  1045.             }
  1046.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  1047.             if (false !== strpos($billingData['first_name'], '***')) {
  1048.                 $billingData['first_name'] = $customer->getFirstname();
  1049.                 $billingData['last_name'] = $customer->getLastname();
  1050.                 $billingData['phone'] = $customer->getPhone();
  1051.                 $billingData['email'] = $customer->getEmail();
  1052.                 $billingData['address'] = $customer->getAddress();
  1053.                 $billingData['doc_num'] = $customer->getDocumentnumber();
  1054.                 $billingData['id'] = $customer->getAviaturclientid();
  1055.             }
  1056.             $session->set($transactionId.'[assist][prepayment_check]'true);
  1057.             if (true !== $session->has($transactionId.'[assist][order]')) {
  1058.                 if (true === $session->has($transactionId.'[assist][detail]')) {
  1059.                     $isFront $session->has('operatorId');
  1060.                     if ($isFront) {
  1061.                         $customer $billingData;
  1062.                         $customer['isFront'] = true;
  1063.                         $status 'B2T';
  1064.                     } else {
  1065.                         $status 'waiting';
  1066.                     }
  1067.                     if (isset($agency)) {
  1068.                         $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('ASSIST');
  1069.                         if ($isFront) {
  1070.                             $orderIdentifier '{order_product_reservation}';
  1071.                         } else {
  1072.                             $orderIdentifier '{order_product_num}';
  1073.                         }
  1074.                         $order $orderController->createAction($agency$customer$productType$orderIdentifier$status);
  1075.                         $orderId str_replace('ON'''$order['order']);
  1076.                         $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  1077.                         $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[assist][user_info]'));
  1078.                         $formUserInfo->setOrder($orderEntity);
  1079.                         $em->persist($formUserInfo);
  1080.                         $em->flush();
  1081.                         // Agent Transaction, Save commission QSE or Percentage
  1082.                         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  1083.                             $orderInfo json_decode($session->get($transactionId.'[assist][order]'));
  1084.                             $productId str_replace('PN'''$orderInfo->products);
  1085.                             $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1086.                             $agentId $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  1087.                             $agentCommission $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agentId);
  1088.                             $arrayInfo $session->get($transactionId.'_agentInfoTransaction');
  1089.                             // $commissionPay = $selectionData['commissionPay'];
  1090.                             $agentTransaction = new AgentTransaction();
  1091.                             $agentTransaction->setAgent($agentId);
  1092.                             $agentTransaction->setAgentCommission($agentCommission);
  1093.                             $agentTransaction->setOrderProduct($orderProduct);
  1094.                             $agentTransaction->setCommissionvalue($arrayInfo['amountPay']);
  1095.                             $agentTransaction->setAmountQse($arrayInfo['amountQse']);
  1096.                             $agentTransaction->setCommissionQse($arrayInfo['commissionQse']);
  1097.                             $agentTransaction->setPercentageTarifa($arrayInfo['percentageTarifa']);
  1098.                             $agentTransaction->setAmountTarifa($arrayInfo['amountTa']);
  1099.                             $agentTransaction->setCommissionTarifa($arrayInfo['commissionTa']);
  1100.                             $agentTransaction->setAmountProduct($arrayInfo['amountProduct']);
  1101.                             $em->persist($agentTransaction);
  1102.                             $em->flush();
  1103.                         }
  1104.                         if ($isFront) {
  1105.                             $order['Transaction'] = $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
  1106.                             $order['Transaction']['resumeView']['Estado'] = 'OK';
  1107.                             if ('Error' == $order['Transaction']['resumeView']['Estado']) {
  1108.                                 $order['url'] = $this->generateUrl('aviatur_insurance_payment_error_front_secure');
  1109.                             } else {
  1110.                                 $order['url'] = $this->generateUrl('aviatur_insurance_payment_front_secure');
  1111.                             }
  1112.                         } else {
  1113.                             $order['url'] = $this->generateUrl('aviatur_insurance_payment_secure');
  1114.                         }
  1115.                         return $this->json($order);
  1116.                     } else {
  1117.                         return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''No se encontró la agencia con el dominio: '.$request->getHost()));
  1118.                     }
  1119.                 } else {
  1120.                     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 inténtalo nuevamente')]);
  1121.                 }
  1122.             } else {
  1123.                 $order['url'] = $this->generateUrl('aviatur_insurance_payment_secure');
  1124.                 return $this->json($order);
  1125.             }
  1126.         } else {
  1127.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''Acceso no autorizado'));
  1128.         }
  1129.     }
  1130.     public function paymentAction(Request $requestCashController $cashPaymentControllerSafetypayController $safetyPayControllerPSEController $aviaturPsePaymentControllerRouterInterface $routerWorldPayController $worldPaymentControllerP2PController $p2pPaymentControllerInsuranceService $insuranceServiceAviaturLogSave $aviaturLogSaveCustomerMethodPaymentService $customerMethodPaymentTokenStorageInterface $tokenStorageAuthorizationCheckerInterface $authorizationCheckerAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag, \Swift_Mailer $mailer,TokenizerService $tokenizerServiceOrderController $orderController)
  1131.     {
  1132.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1133.         $emailNotification $parameterBag->get('email_notification');
  1134.         $orderProduct = [];
  1135.         $dateBirth = [];
  1136.         $GivenName = [];
  1137.         $Surname = [];
  1138.         $Email = [];
  1139.         $StateCode = [];
  1140.         $Telephone = [];
  1141.         $Document = [];
  1142.         $CityName = [];
  1143.         $GivenName_contact = [];
  1144.         $Surname_contact = [];
  1145.         $Telephone_contact = [];
  1146.         $calculoEdades = [];
  1147.         $paymentResponse null;
  1148.         $return null;
  1149.         $response null;
  1150.         $array = [];
  1151.         $isAgent false;
  1152.         $em $registry->getManager();
  1153.         $transactionId $session->get($transactionIdSessionName);
  1154.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  1155.             $isAgent true;
  1156.         }
  1157.         $postData json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
  1158.         $infoInsurance $session->get($transactionId.'[assist][infoInsurance]');
  1159.         $detail $session->get($transactionId.'[assist][detail]');
  1160.         $aviaturLogSave->logSave(print_r($detailtrue), 'InsuranceOrder''RS');
  1161.         $orderInfo json_decode($session->get($transactionId.'[assist][order]'));
  1162.         @$productId str_replace('PN'''$orderInfo->products);
  1163.         $orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1164.         $startDate $detail->get('dateEntry');
  1165.         $endDate $detail->get('dateEnd');
  1166.         $passenger $detail->get('passenger');
  1167.         $method $detail->get('method');
  1168.         $destiny $detail->get('destiny');
  1169.         $echoToken $detail->get('echoToken');
  1170.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  1171.         $aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
  1172.         $TypeID explode('*'base64_decode($detail->get('TypeID')));
  1173.         $paymentData $postData->PD;
  1174.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1175.         $configInsuranceAgency $em->getRepository(\Aviatur\InsuranceBundle\Entity\ConfigInsuranceAgency::class)->findOneByAgency($agency);
  1176.         $OfficeId explode('-'$configInsuranceAgency->getOfficeId());
  1177.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  1178.         $fromCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('USD');
  1179.         $toCurrency $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('COP');
  1180.         $TRM $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->findOneBy(['fromCurrency' => $fromCurrency'toCurrency' => $toCurrency], ['id' => 'DESC']);
  1181.         $x_total_amount = (int) $TypeID[3];
  1182.         if ('COP' != $TypeID[2]) {
  1183.             $x_total_amount = (int) $TypeID[3] * $TRM->getRate()->getFinantialrate();
  1184.         }
  1185.         $x_amount_base $x_total_amount / ($aviaturPaymentIva);
  1186.         $x_amount_iva $x_amount_base $aviaturPaymentIva;
  1187.         $description 'Tarjeta Asistencia - '.$TypeID[1].' - ('.$startDate.' - '.$endDate.')';
  1188.         $diffDays = ((strtotime($endDate) - strtotime($startDate)) / 86400) + 1;
  1189.         $PI = (array) $postData->PI;
  1190.         if (false !== strpos($PI['first_name_1_1'], '***')) {
  1191.             $PI['first_name_1_1'] = $customer->getFirstname();
  1192.             $PI['last_name_1_1'] = $customer->getLastname();
  1193.             $PI['phone_1_1'] = $customer->getPhone();
  1194.             $PI['email_1_1'] = $customer->getEmail();
  1195.             $PI['address_1_1'] = $customer->getAddress();
  1196.             $PI['doc_num_1_1'] = $customer->getDocumentnumber();
  1197.         }
  1198.         $variable = [
  1199.             'echoToken' => $echoToken,
  1200.             'PlanID' => $detail->get('id'),
  1201.             'TypeID' => $TypeID[0],
  1202.             'OfficeId' => $OfficeId[1],
  1203.             'AgencyId' => substr($OfficeId[0], 1),
  1204.             'transactionId' => $transactionId,
  1205.             'correlationId' => $detail->get('correlationId'),
  1206.             'EffectiveDate' => $startDate,
  1207.             'ExpireDate' => $endDate,
  1208.             'MaximumTripLength' => 'P'.$diffDays.'D',
  1209.             'AreaID' => $destiny,
  1210.             'ProviderId' => $detail->get('providerId'),
  1211.             'method' => $method,
  1212.         ];
  1213.         $emailUser $PI['email_1_1'];
  1214.         $isFront false;
  1215.         if ($session->has('operatorId')) {
  1216.             $isFront true;
  1217.             $userFront simplexml_load_string($session->get('front_user'));
  1218.             $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  1219.             $variable['OperatorId'] = (string) $userFront->ID_AGENTE;
  1220.             $variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
  1221.             $variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE02);
  1222.             $emailUser = (string) $userFront->CORREO_ELECTRONICO;
  1223.         }
  1224.         for ($i 1$i <= $passenger; ++$i) {
  1225.             if (== $passenger) {
  1226.                 $dateBirth[] = $PI['birthday_1_1'];
  1227.                 $GivenName[] = $PI['first_name_1_1'];
  1228.                 $Surname[] = $PI['last_name_1_1'];
  1229.                 $Email[] = $emailUser;
  1230.                 $StateCode[] = $PI['origin_1_1'];
  1231.                 $Telephone[] = $PI['phone_contact_1_1'];
  1232.                 $Document[] = $PI['doc_num_1_1'];
  1233.                 $originValidate explode(','$PI['origin_1_1Validate']);
  1234.                 $CityName[] = $originValidate[0];
  1235.                 $GivenName_contact[] = $PI['first_name_contact_1_1'];
  1236.                 $Surname_contact[] = $PI['last_name_contact_1_1'];
  1237.                 $Telephone_contact[] = $PI['phone_contact_1_1'];
  1238.             } else {
  1239.                 $dateBirth[] = $PI['birthday_1_'.$i];
  1240.                 $GivenName[] = $PI['first_name_1_'.$i];
  1241.                 $Surname[] = $PI['last_name_1_'.$i];
  1242.                 $Email[] = $emailUser;
  1243.                 $StateCode[] = $PI['origin_1_'.$i];
  1244.                 $Telephone[] = $PI['phone_contact_1_'.$i];
  1245.                 $Document[] = $PI['doc_num_1_'.$i];
  1246.                 $originValidate explode(','$PI['origin_1_'.$i.'Validate']);
  1247.                 $CityName[] = $originValidate[0];
  1248.                 $GivenName_contact[] = $PI['first_name_contact_1_'.$i];
  1249.                 $Surname_contact[] = $PI['last_name_contact_1_'.$i];
  1250.                 $Telephone_contact[] = $PI['phone_contact_1_'.$i];
  1251.             }
  1252.             $calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i 1)]);
  1253.             $variable['CoveredTraveler'][] = [
  1254.                 'BirthDate' => $dateBirth[($i 1)],
  1255.                 'Age' => $calculoEdades[($i 1)],
  1256.                 'GivenName' => $GivenName[($i 1)],
  1257.                 'Surname' => $Surname[($i 1)],
  1258.                 'Email' => $Email[($i 1)],
  1259.                 'StateCode' => $StateCode[($i 1)],
  1260.                 'CityName' => $CityName[($i 1)],
  1261.                 'Telephone' => $Telephone[($i 1)],
  1262.                 'Document' => $Document[($i 1)],
  1263.                 'GivenName_contact' => $GivenName_contact[($i 1)],
  1264.                 'Surname_contact' => $Surname_contact[($i 1)],
  1265.                 'Telephone_contact' => $Telephone_contact[($i 1)],
  1266.             ];
  1267.         }
  1268.         $InsuranceModel = new InsuranceModel();
  1269.         $searchInsurance = ['{EchoToken}''{PlanID}''{TypeID}''{OfficeId}''{AgencyId}''{transactionId}''{correlationId}''{EffectiveDate}''{ExpireDate}''{MaximumTripLength}''{AreaID}'];
  1270.         $xmlTemplate $InsuranceModel->getXmlCreateOrder($variable$isFront);
  1271.         $xmlCreateOrder str_replace($searchInsurance$variable$xmlTemplate);
  1272.         if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
  1273.             if (isset($paymentData->cusPOptSelected)) {
  1274.                 $customerLogin $tokenStorage->getToken()->getUser();
  1275.                 $infoMethodPaymentByClient $customerMethodPayment->getMethodsByCustomer($customerLogintrue);
  1276.                 $cardToken $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  1277.                 $paymentData->card_num $cardToken;
  1278.                 $paymentData->card_values->card_num_token $cardToken;
  1279.             }
  1280.             if (!empty($paymentData)) {
  1281.                 if (false !== strpos($paymentData->address'***')) {
  1282.                     $paymentData->address $customer->getAddress();
  1283.                 }
  1284.                 if (false !== strpos($paymentData->phone'***')) {
  1285.                     $paymentData->phone $customer->getPhone();
  1286.                 }
  1287.                 if (false !== strpos($paymentData->email'***')) {
  1288.                     $paymentData->email $customer->getEmail();
  1289.                 }
  1290.             }
  1291.             $array = [
  1292.                 'x_currency_code' => (string) 'COP',
  1293.                 'x_amount' => number_format(round((float) ($x_total_amount)), 0'.'''),
  1294.                 'x_tax' => number_format(round((float) ($x_amount_iva)), 2'.'''),
  1295.                 'x_amount_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  1296.                 'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  1297.                 'x_first_name' => $paymentData->first_name,
  1298.                 'x_last_name' => $paymentData->last_name,
  1299.                 'x_description' => $description,
  1300.                 'x_city' => $customer->getCity()->getIatacode(),
  1301.                 'x_country_id' => $customer->getCountry()->getIatacode(),
  1302.                 'x_cust_id' => $paymentData->doc_type.' '.$paymentData->doc_num,
  1303.                 'x_address' => $paymentData->address,
  1304.                 'x_phone' => $paymentData->phone,
  1305.                 'x_email' => $paymentData->email,
  1306.                 'x_card_num' => $paymentData->card_num,
  1307.                 'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
  1308.                 'x_card_code' => $paymentData->card_code,
  1309.                 'x_differed' => $paymentData->differed,
  1310.                 'x_client_id' => $postData->BD->id,
  1311.                 'product_type' => 'assist',
  1312.                 'x_cant_passenger' => $passenger,
  1313.                 'franchise' => $paymentData->franquise,
  1314.                 'worldpay_validate' => true,
  1315.             ];
  1316.             if (isset($paymentData->card_values)) {
  1317.                 $array['card_values'] = (array) $paymentData->card_values;
  1318.             }
  1319.             if ('p2p' == $paymentData->type) {
  1320.                 if (isset($paymentData->cusPOptSelected)) {
  1321.                     $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  1322.                 }
  1323.                 if (isset($postData->PD->savePaymProc)) {
  1324.                     $array['x_provider_id'] = 1;
  1325.                 } elseif (isset($paymentData->cusPOptSelected)) {
  1326.                     if (isset($paymentData->cusPOptSelectedStatus)) {
  1327.                         if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
  1328.                             $array['x_provider_id'] = 1;
  1329.                         } else {
  1330.                             $array['x_provider_id'] = 2;
  1331.                         }
  1332.                     } else {
  1333.                         $array['x_provider_id'] = 2;
  1334.                     }
  1335.                 }
  1336.             }
  1337.             if ('p2p' == $paymentData->type) {
  1338.                 $paymentResponse $p2pPaymentController->placetopayAction($parameterBag,$tokenizerService,$customerMethodPayment,$mailer,$aviaturLogSave,$array);
  1339.                 $return 'aviatur_insurance_payment_p2p_return_url_secure';
  1340.             } elseif ('world' == $paymentData->type) {
  1341.                 $array['city'] = $customer->getCity()->getIatacode();
  1342.                 $array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
  1343.                 $paymentResponse $worldPaymentController->worldAction($request$mailer$aviaturLogSave$customerMethodPayment$parameterBag$array);
  1344.                 $return 'aviatur_insurance_payment_world_return_url_secure';
  1345.             }
  1346.             $emissionData $insuranceService->xmlInsuranceExtra($transactionIdfalse);
  1347.             unset($array['x_client_id']);
  1348.             if (null != $paymentResponse) {
  1349.                 return $this->redirect($this->generateUrl($return, [], true));
  1350.             } else {
  1351.                 $orderProduct[0]->setStatus('pending');
  1352.                 $em->persist($orderProduct[0]);
  1353.                 $em->flush();
  1354.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '''No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  1355.             }
  1356.         } elseif ('pse' == $paymentData->type) {
  1357.             $array = ['x_doc_num' => $customer->getDocumentnumber(),
  1358.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  1359.                 'x_first_name' => $customer->getFirstname(),
  1360.                 'x_last_name' => $customer->getLastname(),
  1361.                 'x_company' => 'Aviatur',
  1362.                 'x_email' => $customer->getEmail(),
  1363.                 'x_address' => $customer->getAddress(),
  1364.                 'x_city' => $customer->getCity()->getDescription(),
  1365.                 'x_province' => $customer->getCity()->getDescription(),
  1366.                 'x_country' => $customer->getCountry()->getDescription(),
  1367.                 'x_phone' => $customer->getPhone(),
  1368.                 'x_mobile' => $customer->getCellphone(),
  1369.                 'x_bank' => $paymentData->pse_bank,
  1370.                 'x_type' => $paymentData->pse_type,
  1371.                 'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  1372.                 'x_description' => $TypeID[1],
  1373.                 'x_currency' => (string) 'COP',
  1374.                 'x_total_amount' => number_format(round((float) ($x_total_amount)), 0'.'''),
  1375.                 'x_tax_amount' => number_format(round((float) ($x_amount_iva)), 2'.'''),
  1376.                 'x_devolution_base' => number_format(round((float) ($x_amount_base)), 2'.'''),
  1377.                 'x_tax' => number_format(round((float) (0)), 2'.'''),
  1378.                 'x_tip_amount' => number_format(round((float) (0)), 2'.'''),
  1379.                 'x_cant_passenger' => $passenger,
  1380.                 'product_type' => 'assist',
  1381.             ];
  1382.             $route $router->match(str_replace($request->getSchemeAndHttpHost(), ''$request->getUri()));
  1383.             $isMulti false !== strpos($route['_route'], 'multi') ? true false;
  1384.             if ($isMulti) {
  1385.                 return $this->json($array);
  1386.             }
  1387.             $paymentResponse $aviaturPsePaymentController->sendPaymentAction($request,$session,$router,$parameterBag,$mailer,$orderController,$array$orderProduct);
  1388.             $emissionData $insuranceService->xmlInsuranceExtra($transactionIdfalse);
  1389.             if (!isset($paymentResponse->error)) {
  1390.                 switch ($paymentResponse->createTransactionResult->returnCode) {
  1391.                     case 'SUCCESS':
  1392.                         return $this->redirect($paymentResponse->createTransactionResult->bankURL);
  1393.                     case 'FAIL_EXCEEDEDLIMIT':
  1394.                         return $this->redirect($this->generateUrl('homepage'), '');
  1395.                     case 'FAIL_BANKUNREACHEABLE':
  1396.                         return $this->redirect($this->generateUrl('aviatur_insurance_retry_secure'), '');
  1397.                     default:
  1398.                         return $this->redirect($this->generateUrl('aviatur_insurance_retry_secure'), '');
  1399.                 }
  1400.             } else {
  1401.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), 'Error al procesar el pago''Ocurrió un problema al intentar crear tu transacción, '.$paymentResponse->error));
  1402.             }
  1403.         } elseif ('safety' == $paymentData->type) {
  1404.             $transactionUrl $this->generateUrl('aviatur_payment_safetypay', [], true);
  1405.             $array = ['x_doc_num' => $customer->getDocumentnumber(),
  1406.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  1407.                 'x_first_name' => $customer->getFirstname(),
  1408.                 'x_last_name' => $customer->getLastname(),
  1409.                 'x_company' => 'Aviatur',
  1410.                 'x_email' => $customer->getEmail(),
  1411.                 'x_address' => $customer->getAddress(),
  1412.                 'x_city' => $customer->getCity()->getDescription(),
  1413.                 'x_province' => $customer->getCity()->getDescription(),
  1414.                 'x_country' => $customer->getCountry()->getDescription(),
  1415.                 'x_phone' => $customer->getPhone(),
  1416.                 'x_mobile' => $customer->getCellphone(),
  1417.                 'x_reference' => $orderInfo->products,
  1418.                 'x_booking' => $request->get('PlanID'),
  1419.                 'x_description' => $TypeID[1],
  1420.                 'x_currency' => 'COP',
  1421.                 'x_total_amount' => number_format(round((float) ($x_total_amount)), 2'.'''),
  1422.                 'x_tax_amount' => number_format(round((float) (0)), 2'.'''),
  1423.                 'x_devolution_base' => number_format(round((float) (0)), 2'.'''),
  1424.                 'x_tip_amount' => number_format(round(0), 2'.'''),
  1425.                 'x_payment_data' => $paymentData->type,
  1426.                 'x_type_description' => 'assist',
  1427.                 'x_cant_passenger' => $passenger,
  1428.                 'product_type' => 'assist',
  1429.                 'xmlCreateOrder' => $xmlCreateOrder,
  1430.             ];
  1431.             $parametMerchant = [
  1432.                 'MerchantSalesID' => $array['x_reference'],
  1433.                 'Amount' => $array['x_total_amount'],
  1434.                 'transactionUrl' => $transactionUrl,
  1435.                 'dataTrans' => $array,
  1436.             ];
  1437.             $safeTyPay $safetyPayController->safetyAction($router$parameterBag$mailer$parametMerchant$array);
  1438.             $emissionData $insuranceService->xmlInsuranceExtra($transactionIdfalse);
  1439.             if ('ok' == $safeTyPay['status']) {
  1440.                 if ('baloto' == $paymentData->type) {
  1441.                     $cash '&CountryId=COL&ChannelId=CASH';
  1442.                     $session->set($transactionId.'[assist][retry]'0);
  1443.                     return $this->redirect($safeTyPay['response'].$cash);
  1444.                 } else {
  1445.                     return $this->redirect($safeTyPay['response']);
  1446.                 }
  1447.             } else {
  1448.                 $emissionData->x_booking $array['x_booking'];
  1449.                 $emissionData->x_first_name $array['x_first_name'];
  1450.                 $emissionData->x_last_name $array['x_last_name'];
  1451.                 $emissionData->x_doc_num $array['x_doc_num'];
  1452.                 $emissionData->x_reference $array['x_reference'];
  1453.                 $emissionData->x_description $array['x_description'];
  1454.                 $emissionData->x_total_amount $array['x_total_amount'];
  1455.                 $emissionData->x_email $array['x_email'];
  1456.                 $emissionData->x_address $array['x_address'];
  1457.                 $emissionData->x_phone $array['x_phone'];
  1458.                 $emissionData->x_type_description $array['x_type_description'];
  1459.                 $emissionData->x_resultSafetyPay $safeTyPay;
  1460.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($responsetrue);
  1461.                 $message = (new \Swift_Message())
  1462.                         ->setContentType('text/html')
  1463.                         ->setFrom($session->get('emailNoReply'))
  1464.                         ->setTo($emailNotification)
  1465.                         ->setSubject('Error Creación Token SafetyPay AssistCard'.$emissionData->x_reference)
  1466.                         ->setBody($mailInfo);
  1467.                 $mailer->send($message);
  1468.                 return $this->redirect($this->generateUrl('aviatur_insurance_payment_rejected_secure'));
  1469.             }
  1470.         } elseif ('cash' == $paymentData->type) {
  1471.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  1472.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1473.             $agencyName $agency->getOfficeId();
  1474.             $array['x_officeId'] = $agencyName;
  1475.             $array['x_doc_num'] = $customer->getDocumentnumber();
  1476.             $array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
  1477.             $array['x_first_name'] = $customer->getFirstname();
  1478.             $array['x_last_name'] = $customer->getLastname();
  1479.             $array['x_company'] = 'Aviatur';
  1480.             $array['x_email'] = $customer->getEmail();
  1481.             $array['x_address'] = $customer->getAddress();
  1482.             $array['x_city'] = $customer->getCity()->getDescription();
  1483.             $array['x_province'] = $customer->getCity()->getDescription();
  1484.             $array['x_country'] = $customer->getCountry()->getDescription();
  1485.             $array['x_phone'] = $customer->getPhone();
  1486.             $array['x_mobile'] = $customer->getCellphone();
  1487.             $array['x_payment_data'] = $paymentData->type;
  1488.             $array['x_type_description'] = $orderProduct[0]->getDescription();
  1489.             $array['x_reference'] = $orderInfo->products;
  1490.             $array['x_total_amount'] = number_format(round((float) ($x_total_amount)), 0'.''');
  1491.             $array['x_currency'] = 'COP';
  1492.             $array['x_description'] = $description;
  1493.             $array['x_cant_passenger'] = $passenger;
  1494.             $array['x_booking'] = $orderProduct[0]->getBooking();
  1495.             $array['product_type'] = 'assist';
  1496.             $fecha $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
  1497.             $fechalimite $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
  1498.             $nuevafecha strtotime('+2 hour'strtotime($fecha));
  1499.             $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  1500.             if (strcmp($fechavigencia$fechalimite) > 0) {
  1501.                 $fechavigencia $fechalimite;
  1502.             }
  1503.             $array['x_fechavigencia'] = $fechavigencia;
  1504.             $array['x_transactionId'] = $transactionId;
  1505.             $retryCount = (int) $session->get($transactionId.'[assist][retry]');
  1506.             if ($session->has($transactionId.'[assist][detail_cash]')) {
  1507.                 $detail_cash json_decode($session->get($transactionId.'[assist][detail_cash]'));
  1508.                 if ('error' == $detail_cash->status) {
  1509.                     $cashPay $cashPaymentController->cashAction($array);
  1510.                 } else {
  1511.                     $cashPay json_decode($session->get($transactionId.'[assist][detail_cash]'));
  1512.                 }
  1513.             } else {
  1514.                 $cashPay $cashPaymentController->cashAction($aviaturLogSave$array);
  1515.                 $session->set($transactionId.'[assist][detail_cash]'json_encode($cashPay));
  1516.             }
  1517.             $emissionData $insuranceService->xmlInsuranceExtra($transactionIdfalse);
  1518.             if ('ok' == $cashPay->status) {
  1519.                 $session->set($transactionId.'[assist][cash_result]'json_encode($cashPay));
  1520.                 return $this->redirect($this->generateUrl('aviatur_insurance_confirmation_success_secure'));
  1521.             } else {
  1522.                 $emissionData['x_first_name'] = $array['x_first_name'];
  1523.                 $emissionData['x_last_name'] = $array['x_last_name'];
  1524.                 $emissionData['x_doc_num'] = $array['x_doc_num'];
  1525.                 $emissionData['x_reference'] = $array['x_reference'];
  1526.                 $emissionData['x_description'] = $array['x_description'];
  1527.                 $emissionData['x_total_amount'] = $array['x_total_amount'];
  1528.                 $emissionData['x_email'] = $array['x_email'];
  1529.                 $emissionData['x_address'] = $array['x_address'];
  1530.                 $emissionData['x_phone'] = $array['x_phone'];
  1531.                 $emissionData['x_type_description'] = $array['x_type_description'];
  1532.                 $emissionData['x_error'] = $cashPay->status;
  1533.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($cashPaytrue);
  1534.                 $message = (new \Swift_Message())
  1535.                         ->setContentType('text/html')
  1536.                         ->setFrom($session->get('emailNoReply'))
  1537.                         // ->setTo('soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', $emailNotification)
  1538.                         ->setSubject('Error Creación Transacción Efectivo'.$emissionData['x_reference'])
  1539.                         ->setBody($mailInfo);
  1540.                 $mailer->send($message);
  1541.                 $session->set($transactionId.'[assist][retry]'$retryCount 1);
  1542.                 return $this->redirect($this->generateUrl('aviatur_insurance_payment_rejected_secure'));
  1543.             }
  1544.         } else {
  1545.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '''El tipo de pago es inválido'));
  1546.         }
  1547.     }
  1548.     public function p2pCallbackAction(
  1549.         Request $request,
  1550.         InsuranceService $insuranceService,
  1551.         AviaturWebService $aviaturWebService,
  1552.         SessionInterface $session,
  1553.         ValidateSanctions $validateSanctions,
  1554.         AviaturMailer $aviaturMailer,
  1555.         OrderController $orderController,
  1556.         CustomerMethodPaymentService $customerMethodPayment,
  1557.         TokenStorageInterface $tokenStorage,
  1558.         AviaturEncoder $aviaturEncoder,
  1559.         AviaturErrorHandler $aviaturErrorHandler,
  1560.         ManagerRegistry $registry,
  1561.         ParameterBagInterface $parameterBag,
  1562.         \Swift_Mailer $mailer
  1563.         )
  1564.     {
  1565.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1566.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1567.         $agency null;
  1568.         $session $session;
  1569.         $em $registry->getManager();
  1570.         $transactionId $session->get($transactionIdSessionName);
  1571.         $orderProductCode $session->get($transactionId.'[assist][order]');
  1572.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1573.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1574.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1575.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1576.         $jsonSendEmail $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
  1577.         if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
  1578.             $email json_decode($jsonSendEmail->getDescription())->email->CallBack;
  1579.         }
  1580.         $reference str_replace('{"order":"'''$orderProductCode);
  1581.         $reference str_replace('","products":"''-'$reference);
  1582.         $reference str_replace('"}'''$reference);
  1583.         $references $reference;
  1584.         $bookings $orderProduct->getBooking();
  1585.         if (null != $decodedResponse) {
  1586.             //$prepaymentInfo = \simplexml_load_string($session->get($transactionId . '[hotel][prepayment]'));
  1587.             $twig '';
  1588.             $additionalQS '';
  1589.             if (!isset($decodedResponse->x_response_code)) {
  1590.                 $twig '' != $twig $twig 'aviatur_insurance_payment_rejected_secure';
  1591.                 $retryCount 1;
  1592.             } else {
  1593.                 $retryCount = (int) $session->get($transactionId.'[assist][retry]');
  1594.                 if (isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber)) {
  1595.                     $decodedResponse->x_response_code_case 99;
  1596.                 } else {
  1597.                     $decodedResponse->x_response_code_case $decodedResponse->x_response_code;
  1598.                 }
  1599.                 switch ($decodedResponse->x_response_code_case) {
  1600.                     case 99:
  1601.                         //rechazado cybersource
  1602.                         $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  1603.                         if ($parameters) {
  1604.                             if (== $parameters->getValue()) {
  1605.                                 if (== $decodedResponse->x_response_code) {
  1606.                                     $postData json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
  1607.                                     if (isset($postData->PD->cusPOptSelected)) {
  1608.                                         if (isset($postData->PD->cusPOptSelectedStatus)) {
  1609.                                             if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  1610.                                                 $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  1611.                                                 $customerLogin $tokenStorage->getToken()->getUser();
  1612.                                                 $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1613.                                             }
  1614.                                         }
  1615.                                     }
  1616.                                     if (isset($postData->PD->savePaymProc)) {
  1617.                                         $customerLogin $tokenStorage->getToken()->getUser();
  1618.                                         $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1619.                                     }
  1620.                                 }
  1621.                             }
  1622.                         }
  1623.                         $twig 'aviatur_insurance_payment_rejected_secure';
  1624.                         // no break
  1625.                     case 3:// pendiente p2p
  1626.                         $twig '' != $twig $twig 'aviatur_insurance_payment_pending_secure';
  1627.                         $retryCount 1;
  1628.                         break;
  1629.                     case 0:// error p2p
  1630.                         $twig 'aviatur_insurance_payment_error_secure';
  1631.                         if (isset($email)) {
  1632.                             $from $session->get('emailNoReply');
  1633.                             $error $twig;
  1634.                             $subject $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
  1635.                             $body '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  1636.                             $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  1637.                         }
  1638.                         // no break
  1639.                     case 2:// rechazada p2p
  1640.                         $twig '' != $twig $twig 'aviatur_insurance_payment_rejected_secure';
  1641.                         if (isset($email)) {
  1642.                             $from $session->get('emailNoReply');
  1643.                             $error $twig;
  1644.                             $subject $orderProduct->getDescription().':Transacción rechazada';
  1645.                             $body '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  1646.                             $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  1647.                         }
  1648.                         break;
  1649.                     case 1:// aprobado p2p
  1650.                         $postData json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
  1651.                         if (isset($postData->PD->cusPOptSelected)) {
  1652.                             if (isset($postData->PD->cusPOptSelectedStatus)) {
  1653.                                 if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  1654.                                     $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  1655.                                     $customerLogin $tokenStorage->getToken()->getUser();
  1656.                                     $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1657.                                 }
  1658.                             }
  1659.                         }
  1660.                         if (isset($postData->PD->savePaymProc)) {
  1661.                             $customerLogin $tokenStorage->getToken()->getUser();
  1662.                             $customerMethodPayment->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1663.                         }
  1664.                         $twig 'aviatur_insurance_payment_success_secure';
  1665.                         if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
  1666.                             $additionalQS '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
  1667.                         }
  1668.                         //Reemplazar por consumo de reserva!!!!
  1669.                         $updateOrder $orderController->updatePaymentAction($orderProductfalsenull);
  1670.                         $session->set($transactionId.'[assist][retry]'$aviaturPaymentRetryTimes);
  1671.                         $response $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
  1672.                         if ('Error' == $response['resumeView']['Estado']) {
  1673.                             $session->set($transactionId.'[emission][error]'true);
  1674.                             return $this->redirect($this->generateUrl('aviatur_insurance_payment_success_secure'));
  1675.                         }
  1676.                         break;
  1677.                 }
  1678.                 $session->set($transactionId.'[assist][retry]'$retryCount 1);
  1679.             }
  1680.             $urlResume $this->generateUrl($twig);
  1681.             $urlResume .= $additionalQS;
  1682.             //////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
  1683.             if ($session->has('Marked_name') && $session->has('Marked_document')) {
  1684.                 $product 'Vuelo';
  1685.                 $validateSanctions->sendMarkedEmail($orderProductCode$session$agency$orderProduct$transactionId$product);
  1686.             }
  1687.             ////////////////////////////////////////////////////////////////////////////////////
  1688.             return $this->redirect($urlResume);
  1689.         } else {
  1690.             $orderProduct->setStatus('pending');
  1691.             $em->persist($orderProduct);
  1692.             $em->flush();
  1693.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  1694.         }
  1695.     }
  1696.     public function pseCallbackAction(Request $requestSessionInterface $sessionPSEController $aviaturPsePaymentControllerOrderController $orderControllerTwigFolder $twigFolderAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registryInsuranceService $insuranceServiceAviaturWebService $aviaturWebServiceParameterBagInterface $parameterBag$transaction, \Swift_Mailer $mailer)
  1697.     {
  1698.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1699.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1700.         $decodedRequest null;
  1701.         $status null;
  1702.         $twig null;
  1703.         $session $session;
  1704.         $em $registry->getManager();
  1705.         if ($session->has('agencyId')) {
  1706.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1707.         } else {
  1708.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1);
  1709.         }
  1710.         $paymentMethod $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pse');
  1711.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findOneBy(['agency' => $agency'paymentMethod' => $paymentMethod]);
  1712.         $tranKey $paymentMethodAgency->getTrankey();
  1713.         $decodedUrl json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
  1714.         $transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
  1715.         $orders $decodedUrl['x_orders'];
  1716.         if (isset($orders['assist'])) {
  1717.             $assistOrders explode('+'$orders['assist']);
  1718.             $orderProductCode $assistOrders[0];
  1719.             $productId $assistOrders[0];
  1720.             $retryCount 1;
  1721.         } else {
  1722.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontro identificador de la transacción'));
  1723.         }
  1724.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1725.         if (empty($orderProduct)) {
  1726.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1727.         } else {
  1728.             if ('approved' == $orderProduct->getStatus()) {
  1729.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  1730.             }
  1731.             $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1732.             if (isset($decodedResponse->createTransactionResult)) {
  1733.                 $additionalQS '';
  1734.                 $pseTransactionId $decodedResponse->createTransactionResult->transactionID;
  1735.                 $paymentResponse $aviaturPsePaymentController->pseCallbackAction($orderController,$pseTransactionId);
  1736.                 if (!isset($paymentResponse->error)) {
  1737.                     if (!$session->has($transactionId.'[assist][detail_data_assist]')) {
  1738.                         $message 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
  1739.                         return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra'$message));
  1740.                     }
  1741.                     $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  1742.                     $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1743.                     $orderProduct->setUpdatingdate(new \DateTime());
  1744.                     $em->persist($orderProduct);
  1745.                     $em->flush();
  1746.                     if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
  1747.                         switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
  1748.                             case 'OK':
  1749.                                 $twig 'aviatur_insurance_payment_success_secure';
  1750.                                 $status 'approved';
  1751.                                 if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
  1752.                                     $additionalQS '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->totalAmount;
  1753.                                 }
  1754.                                 break;
  1755.                             case 'PENDING':
  1756.                                 $twig 'aviatur_insurance_payment_pending_secure';
  1757.                                 $status 'pending';
  1758.                                 break;
  1759.                             case 'NOT_AUTHORIZED':
  1760.                                 $twig 'aviatur_insurance_payment_error_secure';
  1761.                                 $status 'rejected';
  1762.                                 break;
  1763.                             case 'FAILED':
  1764.                                 $twig 'aviatur_insurance_payment_error_secure';
  1765.                                 $status 'failed';
  1766.                                 break;
  1767.                         }
  1768.                         $orderProduct->setStatus($status);
  1769.                         $orderProduct->getOrder()->setStatus($status);
  1770.                         $orderProduct->setUpdatingdate(new \DateTime());
  1771.                         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1772.                         $em->persist($orderProduct);
  1773.                         $em->flush();
  1774.                         if ('approved' == $status) {
  1775. //                              //Reemplazar por consumo de reserva!!!!
  1776.                             $orderController->updatePaymentAction($orderProductfalsenull);
  1777.                             $response $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
  1778.                             $session->set($transactionId.'[assist][retry]'$aviaturPaymentRetryTimes);
  1779.                             if ('Error' == $response['resumeView']['Estado']) {
  1780.                                 $session->set($transactionId.'[emission][error]'true);
  1781.                             }
  1782.                         }
  1783.                     } elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
  1784.                         echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1785.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1786.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1787.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1788.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1789.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1790.                             transacción <#CUS> .';
  1791.                         $orderProduct->setEmissiondata('error');
  1792.                         $orderProduct->setUpdatingdate(new \DateTime());
  1793.                         $em->persist($orderProduct);
  1794.                         $em->flush();
  1795.                         $twig 'aviatur_insurance_payment_error_secure';
  1796.                     }
  1797.                     if ($session->has($transactionId.'[assist][retry]')) {
  1798.                         $session->set($transactionId.'[assist][retry]'$retryCount 1);
  1799.                     }
  1800.                     $urlResume $this->generateUrl($twig);
  1801.                     $urlResume .= $additionalQS;
  1802.                     return $this->redirect($urlResume);
  1803.                 } else {
  1804.                     $decodedResponse->getTransactionInformationResult $paymentResponse;
  1805.                     $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1806.                     $orderProduct->setUpdatingdate(new \DateTime());
  1807.                     $em->persist($orderProduct);
  1808.                     $em->flush();
  1809.                     return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  1810.                 }
  1811.             } else {
  1812.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('homepage'), '''No se encontró información de la transacción'));
  1813.             }
  1814.         }
  1815.     }
  1816.     public function safetyCallbackOkAction(
  1817.         Request $request,
  1818.         SessionInterface $session,
  1819.         SafetypayController $safetyPayController,
  1820.         OrderController $orderController,
  1821.         AviaturEncoder $aviaturEncoder,
  1822.         AviaturErrorHandler $aviaturErrorHandler,
  1823.         ManagerRegistry $registry,
  1824.         ParameterBagInterface $parameterBag,
  1825.         InsuranceService $insuranceService,
  1826.         AviaturWebService $aviaturWebService,
  1827.         \Swift_Mailer $mailer)
  1828.     {
  1829.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1830.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1831.         $status null;
  1832.         $twig null;
  1833.         $em $registry->getManager();
  1834.         $safeTyPay $safetyPayController->safetyok();
  1835.         if (true === $session->has($transactionIdSessionName)) {
  1836.             $transactionId $session->get($transactionIdSessionName);
  1837.             if (true === $session->has($transactionId.'[assist][order]')) {
  1838.                 $orderProductCode $session->get($transactionId.'[assist][order]');
  1839.                 $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1840.                 $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1841.                 $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1842.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1843.                 $payError $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
  1844.                 $notifyError $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
  1845.                 if (isset($decodedResponse->payResponse->OperationResponse)) {
  1846.                     if (== $payError) {
  1847.                         $retryCount = (int) $session->get($transactionId.'[assist][retry]');
  1848.                         if (== $notifyError) {
  1849.                             switch ($payError) {
  1850.                                 case 0:
  1851.                                     $twig 'aviatur_insurance_payment_success_secure';
  1852.                                     $status 'approved';
  1853.                                     break;
  1854.                                 case 2:
  1855.                                     $twig 'aviatur_insurance_payment_error_secure';
  1856.                                     $status 'failed';
  1857.                                     break;
  1858.                             }
  1859.                             $orderProduct->setStatus($status);
  1860.                             $orderProduct->getOrder()->setStatus($status);
  1861.                             $orderProduct->setUpdatingdate(new \DateTime());
  1862.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1863.                             $em->persist($orderProduct);
  1864.                             $em->flush();
  1865.                             $orderController->updatePaymentAction($orderProduct);
  1866.                             if (== $payError) {
  1867.                                 if ('approved' == $status) {
  1868.                                     //Reemplazar por consumo de reserva!!!!
  1869.                                     $response $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
  1870.                                     $session->set($transactionId.'[assist][retry]'$aviaturPaymentRetryTimes);
  1871.                                     if ('Error' == $response['resumeView']['Estado']) {
  1872.                                         $session->set($transactionId.'[emission][error]'true);
  1873.                                     }
  1874.                                     return $this->redirect($this->generateUrl('aviatur_insurance_payment_success_secure'));
  1875.                                 }
  1876.                             }
  1877.                         } else {
  1878.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1879.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1880.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1881.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1882.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1883.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1884.                             transacción <#CUS> .';
  1885.                             $orderProduct->setEmissiondata('error');
  1886.                             $orderProduct->setUpdatingdate(new \DateTime());
  1887.                             $em->persist($orderProduct);
  1888.                             $em->flush();
  1889.                             $twig 'aviatur_insurance_payment_error_secure';
  1890.                         }
  1891.                         $session->set($transactionId.'[assist][retry]'$retryCount 1);
  1892.                         return $this->redirect($this->generateUrl($twig));
  1893.                     } else {
  1894.                         $decodedResponse->payResponse->OperationResponse->ListOfOperations $paymentResponse;
  1895.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1896.                         $orderProduct->setUpdatingdate(new \DateTime());
  1897.                         $em->persist($orderProduct);
  1898.                         $em->flush();
  1899.                         return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  1900.                     }
  1901.                 } else {
  1902.                     return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''No se encontró información de la transacción, por favor comuniquese con nosotros'));
  1903.                 }
  1904.             } else {
  1905.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''No se encontró orden asociada a este pago'));
  1906.             }
  1907.         } else {
  1908.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''No se encontró identificador de la transacción'));
  1909.         }
  1910.     }
  1911.     public function safetyCallbackErrorAction(Request $requestAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag)
  1912.     {
  1913.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1914.         $status null;
  1915.         $fullRequest $request;
  1916.         $em $registry->getManager();
  1917.         $transactionId $session->get($transactionIdSessionName);
  1918.         $retryCount = (int) $session->get($transactionId.'[assist][retry]');
  1919.         $orderProductCode json_decode($session->get($transactionId.'[assist][order]'));
  1920.         $productId str_replace('PN'''$orderProductCode->products);
  1921.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1922.         $payResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  1923.         $payRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
  1924.         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
  1925.         if ('baloto' == $payRequest->dataTransf->x_payment_data) {
  1926.             $status 'pending';
  1927.             $payResponse->dataTransf->x_response_code 100;
  1928.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
  1929.         } elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
  1930.             $status 'rejected';
  1931.             $payResponse->dataTransf->x_response_code 100;
  1932.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
  1933.         }
  1934.         $orderProduct->setStatus($status);
  1935.         $orderProduct->setUpdatingdate(new \DateTime());
  1936.         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1937.         $order $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
  1938.         $order->setStatus($status);
  1939.         $em->persist($order);
  1940.         $em->persist($orderProduct);
  1941.         $em->flush();
  1942.         if (true === $session->has($transactionId.'[assist][order]')) {
  1943.             $orderProductCode $session->get($transactionId.'[assist][order]');
  1944.         } else {
  1945.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '''No se encontró orden asociada a este pago'));
  1946.         }
  1947.         $session->set($transactionId.'[assist][retry]'$retryCount 1);
  1948.         return $this->redirect($this->generateUrl('aviatur_insurance_payment_rejected_secure'));
  1949.     }
  1950.     public function worldCallbackAction(
  1951.         Request $request,
  1952.         SessionInterface $session,
  1953.         OrderController $orderController,
  1954.         AviaturEncoder $aviaturEncoder,
  1955.         AviaturErrorHandler $aviaturErrorHandler,
  1956.         ManagerRegistry $registry,
  1957.         InsuranceService $insuranceService,
  1958.         AviaturWebService $aviaturWebService,
  1959.         ParameterBagInterface $parameterBag,
  1960.         \Swift_Mailer $mailer)
  1961.     {
  1962.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1963.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  1964.         $em $registry->getManager();
  1965.         $transactionId $session->get($transactionIdSessionName);
  1966.         $orderProductCode $session->get($transactionId.'[assist][order]');
  1967.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1968.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1969.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1970.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1971.         if (null != $decodedResponse) {
  1972.             $twig 'aviatur_insurance_payment_rejected_secure';
  1973.             $retryCount = (int) $session->get($transactionId.'[assist][retry]');
  1974.             $orderController->updatePaymentAction($orderProductfalsenull);
  1975.             if (isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber)) {
  1976.                 $decodedResponse->x_response_code_case 99;
  1977.             } else {
  1978.                 if (isset($decodedResponse->resultado->reply->orderStatus->payment->lastEvent)) {
  1979.                     $decodedResponse->x_response_code_case = (string) $decodedResponse->resultado->reply->orderStatus->payment->lastEvent;
  1980.                 } elseif (isset($decodedResponse->resultado->reply->orderStatusEvent->payment->lastEvent)) {
  1981.                     $decodedResponse->x_response_code_case 'REFUSED';
  1982.                 } elseif (isset($decodedResponse->resultado->reply->error)) {
  1983.                     $decodedResponse->x_response_code_case 'REFUSED';
  1984.                 }
  1985.             }
  1986.             switch ($decodedResponse->x_response_code_case) {
  1987.                 case 99:
  1988.                     $twig 'aviatur_insurance_payment_rejected_secure';
  1989.                     break;
  1990.                 case 'ERROR':
  1991.                     $twig 'aviatur_insurance_payment_error_secure';
  1992.                     break;
  1993.                 case 'AUTHORISED':
  1994.                     $twig 'aviatur_insurance_payment_success_secure';
  1995.                     $session->set($transactionId.'[assist][retry]'$aviaturPaymentRetryTimes);
  1996.                     $response $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
  1997.                     if ('Error' == $response['resumeView']['Estado']) {
  1998.                         $session->set($transactionId.'[emission][error]'true);
  1999.                         return $this->redirect($this->generateUrl('aviatur_insurance_payment_error_secure'));
  2000.                     }
  2001.                     break;
  2002.                 case 'REFUSED':
  2003.                     $twig 'aviatur_insurance_payment_rejected_secure';
  2004.                     break;
  2005.                 default:
  2006.                     $twig 'aviatur_insurance_payment_pending_secure';
  2007.                     break;
  2008.             }
  2009.             $session->set($transactionId.'[assist][retry]'$retryCount 1);
  2010.             return $this->redirect($this->generateUrl($twig));
  2011.         } else {
  2012.             $orderProduct->setStatus('pending');
  2013.             $em->persist($orderProduct);
  2014.             $em->flush();
  2015.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  2016.         }
  2017.     }
  2018.     public function createOrderAction(Request $requestInsuranceService $insuranceServiceAviaturWebService $aviaturWebServiceSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag, \Swift_Mailer $mailer$transactionId)
  2019.     {
  2020.         $emailNotification $parameterBag->get('email_notification');
  2021.         $postData = [];
  2022.         $GivenName = [];
  2023.         $Surname = [];
  2024.         $Email = [];
  2025.         $StateCode = [];
  2026.         $Telephone = [];
  2027.         $Document = [];
  2028.         $CityName = [];
  2029.         $GivenName_contact = [];
  2030.         $Surname_contact = [];
  2031.         $Telephone_contact = [];
  2032.         $searchPayment = [];
  2033.         $replace = [];
  2034.         $em $registry->getManager();
  2035.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  2036.         $configInsuranceAgency $em->getRepository(\Aviatur\InsuranceBundle\Entity\ConfigInsuranceAgency::class)->findOneByAgency($agency);
  2037.         $OfficeId explode('-'$configInsuranceAgency->getOfficeId());
  2038.         $detail_data json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
  2039.         $orderInfo json_decode($session->get($transactionId.'[assist][order]'));
  2040.         $productId str_replace('PN'''$orderInfo->products);
  2041.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2042.         $detail $session->get($transactionId.'[assist][detail]');
  2043.         $provider $session->get($transactionId.'[assist][provider]');
  2044.         $domain str_replace('www.'''$request->getHost());
  2045.         $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findOneByCode('ASSIST');
  2046.         $dateBirth = [];
  2047.         $calculoEdades = [];
  2048.         $InsuranceModel = new InsuranceModel();
  2049.         $dateEnd $detail->get('dateEnd');
  2050.         $dateEntry $detail->get('dateEntry');
  2051.         $destiny $detail->get('destiny');
  2052.         $passenger $detail->get('passenger');
  2053.         $method $detail->get('method');
  2054.         $echoToken $detail->get('echoToken');
  2055.         $diffDays = ((strtotime($dateEnd) - strtotime($dateEntry)) / 86400) + 1;
  2056.         $PI = (array) $detail_data->PI;
  2057.         $passengerCLI = (array) $detail_data->BD;
  2058.         $TypeID explode('*'base64_decode($detail->get('TypeID')));
  2059.         $informationCard explode('*'base64_decode($detail->get('informationCard')));
  2060.         if (!$session->has('operatorId')) {
  2061.             $postData['PD'] = $detail_data->PD;
  2062.             $PD = (array) $detail_data->PD;
  2063.         }
  2064.         $CD = (array) $detail_data->CD;
  2065.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detail_data->BD->id);
  2066.         if (false !== strpos($PI['first_name_1_1'], '***')) {
  2067.             $PI['first_name_1_1'] = $customer->getFirstname();
  2068.             $PI['last_name_1_1'] = $customer->getLastname();
  2069.             $PI['phone_1_1'] = $customer->getPhone();
  2070.             $PI['email_1_1'] = $customer->getEmail();
  2071.             $PI['address_1_1'] = $customer->getAddress();
  2072.             $PI['doc_num_1_1'] = $customer->getDocumentnumber();
  2073.         }
  2074.         $variable = [
  2075.             'EchoToken' => $echoToken,
  2076.             'MaximumTripLength' => 'P'.$diffDays.'D',
  2077.             'AreaID' => $destiny,
  2078.             'transactionId' => $transactionId,
  2079.             'TypeID' => $TypeID[0],
  2080.             'PlanID' => $detail->get('id'),
  2081.             'ProviderId' => $provider,
  2082.             'correlationId' => $detail->get('correlationId'),
  2083.             'EffectiveDate' => $dateEntry,
  2084.             'ExpireDate' => $dateEnd,
  2085.             'method' => $method,
  2086.             'OfficeId' => $OfficeId[1],
  2087.             'AgencyId' => substr($OfficeId[0], 1),
  2088.         ];
  2089.         $isFront false;
  2090.         $emailUser $PI['email_1_1'];
  2091.         if ($session->has('operatorId')) {
  2092.             $isFront true;
  2093.             $userFront simplexml_load_string($session->get('front_user'));
  2094.             $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  2095.             $variable['OperatorId'] = (string) $userFront->ID_AGENTE.'-'.$userFront->NOMBRE_AGENTE;
  2096.             $variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
  2097.             $variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE02);
  2098.             $emailUser = (string) $userFront->CORREO_ELECTRONICO;
  2099.         }
  2100.         for ($i 1$i <= $passenger; ++$i) {
  2101.             if (== $passenger) {
  2102.                 $dateBirth[] = $PI['birthday_1_1'];
  2103.                 $GivenName[] = $PI['first_name_1_1'];
  2104.                 $Surname[] = $PI['last_name_1_1'];
  2105.                 $Email[] = $emailUser;
  2106.                 $StateCode[] = $PI['origin_1_1'];
  2107.                 $Telephone[] = $PI['phone_contact_1_1'];
  2108.                 $Document[] = $PI['doc_num_1_1'];
  2109.                 $originValidate explode(','$PI['origin_1_1Validate']);
  2110.                 $CityName[] = $originValidate[0];
  2111.                 $GivenName_contact[] = $PI['first_name_contact_1_1'];
  2112.                 $Surname_contact[] = $PI['last_name_contact_1_1'];
  2113.                 $Telephone_contact[] = $PI['phone_contact_1_1'];
  2114.             } else {
  2115.                 $dateBirth[] = $PI['birthday_1_'.$i];
  2116.                 $GivenName[] = $PI['first_name_1_'.$i];
  2117.                 $Surname[] = $PI['last_name_1_'.$i];
  2118.                 $Email[] = $emailUser;
  2119.                 $StateCode[] = $PI['origin_1_'.$i];
  2120.                 $Telephone[] = $PI['phone_contact_1_'.$i];
  2121.                 $Document[] = $PI['doc_num_1_'.$i];
  2122.                 $originValidate explode(','$PI['origin_1_'.$i.'Validate']);
  2123.                 $CityName[] = $originValidate[0];
  2124.                 $GivenName_contact[] = $PI['first_name_contact_1_'.$i];
  2125.                 $Surname_contact[] = $PI['last_name_contact_1_'.$i];
  2126.                 $Telephone_contact[] = $PI['phone_contact_1_'.$i];
  2127.             }
  2128.             $calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i 1)]);
  2129.             $variable['CoveredTraveler'][] = [
  2130.                 'BirthDate' => $dateBirth[($i 1)],
  2131.                 'Age' => $calculoEdades[($i 1)],
  2132.                 'GivenName' => $GivenName[($i 1)],
  2133.                 'Surname' => $Surname[($i 1)],
  2134.                 'Email' => $Email[($i 1)],
  2135.                 'StateCode' => $StateCode[($i 1)],
  2136.                 'CityName' => $CityName[($i 1)],
  2137.                 'Telephone' => $Telephone[($i 1)],
  2138.                 'Document' => $Document[($i 1)],
  2139.                 'GivenName_contact' => $GivenName_contact[($i 1)],
  2140.                 'Surname_contact' => $Surname_contact[($i 1)],
  2141.                 'Telephone_contact' => $Telephone_contact[($i 1)],
  2142.             ];
  2143.         }
  2144.         $cliente null;
  2145.         $data $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBydocumentnumber($passengerCLI['doc_num']);
  2146.         if (null == $data) {
  2147.             if ($isFront) {
  2148.                 $passengerCLI['address'] = '';
  2149.                 $passengerCLI['email'] = '';
  2150.             }
  2151.             $cliente = [
  2152.                 'doc_num' => $passengerCLI['doc_num'],
  2153.                 'Name' => $passengerCLI['first_name'],
  2154.                 'Last_name' => $passengerCLI['last_name'],
  2155.                 'address' => $passengerCLI['address'],
  2156.                 'phone' => $passengerCLI['phone'],
  2157.                 'email' => $passengerCLI['email'],
  2158.             ];
  2159.         } else {
  2160.             $cliente = [
  2161.                 'doc_num' => $data->getDocumentNumber(),
  2162.                 'Name' => $data->getFirstname(),
  2163.                 'Last_name' => $data->getLastname(),
  2164.                 'address' => $data->getAddress(),
  2165.                 'phone' => $data->getPhone(),
  2166.                 'email' => $data->getEmail(),
  2167.             ];
  2168.         }
  2169.         $xmlTemplate $InsuranceModel->getXmlCreateOrder($variable$isFront);
  2170.         if ($session->has($transactionId.'[assist][cash_result]')) {
  2171.             $infoDetail = [
  2172.                 'xmlTemplate' => $xmlTemplate,
  2173.                 'variable' => $variable,
  2174.             ];
  2175.             return $infoDetail;
  2176.         } else {
  2177.             $response $aviaturWebService->callWebServiceAmadeus('Execute''InsuranceBook''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate$variablefalse);
  2178.             if (isset($response['error']) || !isset($response->Message->OTA_InsuranceBookRS)) {
  2179.                 $setTo 'soportepagoelectronico@aviatur.com.co';
  2180.                 if (true == $isFront) {
  2181.                     $setTo $emailUser;
  2182.                 }
  2183.                 $bodyMail $response['error'];
  2184.                 $estado 'Error';
  2185.                 $variable['error'] = $response['error'];
  2186.                 $mailInfo print_r($variabletrue);
  2187.                 $messageEmail = (new \Swift_Message())
  2188.                         ->setContentType('text/html')
  2189.                         ->setFrom($session->get('emailNoReply'))
  2190.                         ->setTo($setTo)
  2191.                         ->setBcc([$emailNotification'sebastian.huertas@aviatur.com''f_villate@aviatur.com'])
  2192.                         ->setSubject('Error Creación Reserva '.$informationCard[1].' '.$orderInfo->products)
  2193.                         ->setBody($mailInfo);
  2194.                 $mailer->send($messageEmail);
  2195.                 $resumeView = [
  2196.                     'Estado' => $estado,
  2197.                     'message' => $bodyMail,
  2198.                     'body' => $response['error'],
  2199.                 ];
  2200.                 $arraydecode json_encode($resumeView);
  2201.                 $result = [
  2202.                     'resumeView' => $resumeView,
  2203.                 ];
  2204.                 $session->set($transactionId.'[assist]'.'[resumeTransaction]'json_encode($response));
  2205.                 $session->set($transactionId.'[assist]'.'[infoclient]'json_encode($cliente));
  2206.                 $session->set($transactionId.'[assist]'.'[resumeOrderCreate]'json_encode($arraydecode));
  2207.                 $emissionData $insuranceService->xmlInsuranceExtra($transactionIdfalse);
  2208.                 $orderProduct->setEmissiondata($emissionData);
  2209.                 $orderProduct->setUpdatingdate(new \DateTime());
  2210.                 $em->persist($orderProduct);
  2211.                 $em->flush();
  2212.             } else {
  2213.                 $PolicyDetail null;
  2214.                 $UpdatePaymentData $orderProduct->getUpdatePaymentData();
  2215.                 $conteo 1;
  2216.                 $reservationId 'PN'.$orderProduct->getId();
  2217.                 $reservationId2 = (string) $response->Message->OTA_InsuranceBookRS->PlanForBookRS['PlanID'];
  2218.                 $reservationId3 = (string) $response->Message->OTA_InsuranceBookRS->PlanForBookRS['TypeID'];
  2219.                 foreach ($response->Message->OTA_InsuranceBookRS->PlanForBookRS as $PlanForBookRS) {
  2220.                     $searchPayment[] = '{policy-booking-'.$conteo.'}';
  2221.                     $searchPayment[] = '{policy-number-'.$conteo.'}';
  2222.                     $replace[] = $reservationId.'-'.$conteo;
  2223.                     $replace[] = (string) rtrim($PlanForBookRS->PolicyDetail->PolicyNumber['ID']);
  2224.                     $PolicyDetail .= rtrim($PlanForBookRS->PolicyDetail->PolicyNumber['ID']).'+';
  2225.                     ++$conteo;
  2226.                 }
  2227.                 $xmlUpdatePaymentData str_replace($searchPayment$replace$UpdatePaymentData);
  2228.                 $bodyMail = [
  2229.                     'PlanID' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['PlanID'],
  2230.                     'Name' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['Name'],
  2231.                     'PolicyDetail' => substr($PolicyDetail0, -1),
  2232.                     'Type' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['Type'],
  2233.                     'TypeID' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['TypeID'],
  2234.                     'PolicyDetail' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->PolicyDetail->PolicyNumber['ID'],
  2235.                     'CoveredTravelerAge' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->CoveredPerson['Age'],
  2236.                     'CoveredTravelerGivenName' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->CoveredPerson->GivenName,
  2237.                     'CoveredTravelerSurname' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->CoveredPerson->Surname,
  2238.                     'CoveredTravelerAddress' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->Address->CityName,
  2239.                     'InsCoverageDetailEffectiveDate' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->InsCoverageDetail['EffectiveDate'],
  2240.                     'InsCoverageDetailExpireDate' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->InsCoverageDetail['ExpireDate'],
  2241.                     'InsCoverageDetailType' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->InsCoverageDetail['Type'],
  2242.                     'PlanCostAmount' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->PlanCost['Amount'],
  2243.                     'PlanCostCurrencyCode' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->PlanCost['CurrencyCode'],
  2244.                     'ContactGivenName' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->Contact->PersonName->GivenName,
  2245.                     'ContactTelephone' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->Contact->PersonName->Telephone,
  2246.                 ];
  2247.                 //$orderProduct->setEmissiondata($reservationId);
  2248.                 $orderProduct->setUpdatingdate(new \DateTime());
  2249.                 $session->set($transactionId.'[assist][reservation]'$response->asXml());
  2250.                 $searchData = ['{order_product_reservation}''{order_product_reservation_2}''{property_name_2}'];
  2251.                 $replaceData = [$reservationId$reservationId2$reservationId3];
  2252.                 $orderXml str_replace($searchData$replaceData$orderProduct->getAddProductData());
  2253.                 $count 1;
  2254.                 $PolicyNumber explode('+'substr($PolicyDetail0, -1));
  2255.                 foreach ($PolicyNumber as $TypeID) {
  2256.                     $orderXml str_replace($reservationId.'-'.$count$TypeID$orderXml);
  2257.                     ++$count;
  2258.                 }
  2259.                 $orderProduct->setAddProductData($orderXml);
  2260.                 $orderProduct->setUpdatePaymentData($xmlUpdatePaymentData);
  2261.                 $orderProduct->setBooking($reservationId);
  2262.                 $em->persist($orderProduct);
  2263.                 $em->flush();
  2264.                 if ($isFront) {
  2265.                     try {
  2266.                         $responseOrder $aviaturWebService->busWebServiceAmadeus(nullnull$orderXml);
  2267.                     } catch (\Exception $e) {
  2268.                     }
  2269.                 }
  2270.                 $estado 'Ok';
  2271.                 $resumeView = [
  2272.                     'Estado' => $estado,
  2273.                     'message' => $bodyMail,
  2274.                 ];
  2275.                 $session->set($transactionId.'[assist]'.'[resumeTransaction]'json_encode($response));
  2276.                 $session->set($transactionId.'[assist]'.'[infoclient]'json_encode($cliente));
  2277.                 $arraydecode json_encode($resumeView);
  2278.                 $session->set($transactionId.'[assist]'.'[resumeOrderCreate]'json_encode($arraydecode));
  2279.                 $result = [
  2280.                     'resumeView' => $resumeView,
  2281.                 ];
  2282.             }
  2283.             return $result;
  2284.         }
  2285.     }
  2286.     public function paymentOutputAction(Request $request, \Swift_Mailer $mailerPdf $pdfAviaturPixeles $aviaturPixelesAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderAviaturEncoder $aviaturEncoderSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBagExceptionLog $exceptionLog)
  2287.     {
  2288.         $projectDir $parameterBag->get('kernel.project_dir');
  2289.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  2290.         $emailNotification $parameterBag->get('email_notification');
  2291.         $clientFranquice = [];
  2292.         $paymentResume = [];
  2293.         $voucherFile null;
  2294.         $em $registry->getManager();
  2295.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  2296.         $transactionId $session->get($transactionIdSessionName);
  2297.         $infoClient json_decode($session->get($transactionId.'[assist]'.'[infoclient]'));
  2298.         $infoInsuranceFlight json_decode($session->get($transactionId.'[assist]'.'[infoInsuranceFlight]'), true);
  2299.         $detail $session->get($transactionId.'[assist]'.'[detail]');
  2300.         $detail_data_insurance json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
  2301.         $orderProductCode json_decode($session->get($transactionId.'[assist]'.'[order]'));
  2302.         $productId str_replace('PN'''$orderProductCode->products);
  2303.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  2304.         $resumeTransaction json_decode($session->get($transactionId.'[assist]'.'[resumeTransaction]'), true);
  2305.         $cliente json_decode($session->get($transactionId.'[assist]'.'[infoclient]'), true);
  2306.         $arraydecode json_decode($session->get($transactionId.'[assist]'.'[resumeOrderCreate]'), true);
  2307.         $opRequestInitial json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  2308.         $opRequest $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
  2309.         $opResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  2310.         if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
  2311.             $franquiceCode str_replace(['CR_''RM_''CDNSA'], ['''''CS'], $opResponse->x_franchise);
  2312.             /* Detectar si se trae una franquicia asociada a Worldpay para que utilice una función acorde */
  2313.             if(strpos($franquiceCode'-SSL') !== false) {
  2314.                 $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByActiveWorldpayCode($franquiceCode);
  2315.             } else {
  2316.                 $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
  2317.             }
  2318.         } else {
  2319.             $clientFranquice['description'] = 'error';
  2320.             if (isset($opRequest->paymentMethod) && 'world' == $opRequest->paymentMethod) {
  2321.                 $clientFranquice['description'] = '----';
  2322.             }
  2323.         }
  2324.         $paymentData $detail_data_insurance->BD;
  2325.         $emailDataJson json_decode($orderProduct->getEmail(), true);
  2326.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
  2327.         if (false !== strpos($paymentData->first_name'***')) {
  2328.             $facturationResume = [
  2329.                 'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  2330.                 'customer_address' => $customer->getAddress(),
  2331.                 'customer_doc_num' => $customer->getDocumentnumber(),
  2332.                 'customer_phone' => $customer->getPhone(),
  2333.                 'customer_email' => $customer->getEmail(),
  2334.             ];
  2335.         } else {
  2336.             $facturationResume = [
  2337.                 'customer_names' => $paymentData->first_name.' '.$paymentData->last_name,
  2338.                 'customer_address' => $paymentData->address ?? null,
  2339.                 'customer_doc_num' => $paymentData->doc_num,
  2340.                 'customer_phone' => $paymentData->phone,
  2341.                 'customer_email' => $paymentData->email ?? null,
  2342.             ];
  2343.         }
  2344.         $info_travelers $detail_data_insurance->PI;
  2345.         if (false !== strpos($detail_data_insurance->PI->first_name_1_1'***')) {
  2346.             $info_travelers->first_name_1_1 $customer->getFirstname();
  2347.             $info_travelers->last_name_1_1 $customer->getLastname();
  2348.             $info_travelers->email_1_1 $customer->getEmail();
  2349.             $info_travelers->address_1_1 $customer->getAddress();
  2350.             $detail_data_insurance->CD->phone $customer->getPhone();
  2351.         }
  2352.         if ((null != $opRequest) && (null != $opResponse)) {
  2353.             if (isset($opResponse->x_description)) {
  2354.                 $paymentResume = [
  2355.                     'transaction_state' => $opResponse->x_response_code,
  2356.                     'ta_transaction_state' => $opResponse->x_ta_response_code,
  2357.                     'id' => $orderProduct->getBooking(),
  2358.                     'id_context' => $opRequest->x_invoice_num,
  2359.                     'total_amount' => $opResponse->x_amount,
  2360.                     'currency' => $opResponse->x_bank_currency,
  2361.                     'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  2362.                     'iva' => $opRequest->x_tax,
  2363.                     'ip_address' => $opRequest->x_customer_ip,
  2364.                     'bank_name' => $opResponse->x_bank_name,
  2365.                     'client_franquice' => ['description' => (is_object($clientFranquice) ? $clientFranquice->getDescription() : $clientFranquice['description'])],
  2366.                     'cuotas' => $opRequest->x_differed,
  2367.                     'card_num' => '************'.substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  2368.                     'reference' => $opResponse->x_transaction_id,
  2369.                     'auth' => $opResponse->x_approval_code,
  2370.                     'transaction_date' => $opResponse->x_transaction_date,
  2371.                     'description' => $opResponse->x_description,
  2372.                     'reason_code' => $opResponse->x_response_reason_code,
  2373.                     'reason_description' => $opResponse->x_response_reason_text,
  2374.                     'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
  2375.                     'client_email' => $opResponse->x_email,
  2376.                 ];
  2377.             } elseif (isset($opRequest->dataTransf)) {
  2378.                 if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
  2379.                     $state $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
  2380.                 if (102 == $state):
  2381.                         $state 1;
  2382.                 $reason_description 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
  2383.                         $state 2;
  2384.                 $reason_description 'Transacción creada';
  2385.                 endif;
  2386.                 $paymentResume = [
  2387.                         'transaction_state' => $state,
  2388.                         'id' => $orderProduct->getBooking(),
  2389.                         'currency' => $opRequest->dataTransf->x_currency,
  2390.                         'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
  2391.                         'amount' => null,
  2392.                         'iva' => null,
  2393.                         'ip_address' => $opRequest->dataTransf->dirIp,
  2394.                         'airport_tax' => null,
  2395.                         'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
  2396.                         'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
  2397.                         'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
  2398.                         'description' => $opRequest->dataTransf->x_description,
  2399.                         'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
  2400.                         'reason_description' => $reason_description,
  2401.                         'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  2402.                         'client_email' => $opRequest->dataTransf->x_email,
  2403.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  2404.                         'client_franquice' => ['description' => 'SafetyPay'],
  2405.                         'id_context' => $orderProductCode->order.'-'.$orderProductCode->products,
  2406.                     ]; else:
  2407.                     $paymentResume = [
  2408.                         'transaction_state' => 2,
  2409.                         'id' => $orderProduct->getBooking(),
  2410.                         'currency' => $opRequest->dataTransf->x_currency,
  2411.                         'total_amount' => $opRequest->dataTransf->x_total_amount,
  2412.                         'amount' => null,
  2413.                         'iva' => null,
  2414.                         'ip_address' => $opRequest->dataTransf->dirIp,
  2415.                         'airport_tax' => null,
  2416.                         'reference' => $opRequest->dataTransf->x_reference,
  2417.                         'auth' => null,
  2418.                         'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
  2419.                         'description' => $opRequest->dataTransf->x_description,
  2420.                         'reason_code' => 101,
  2421.                         'reason_description' => 'Transacción creada',
  2422.                         'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  2423.                         'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
  2424.                         'client_email' => $opRequest->dataTransf->x_email,
  2425.                     ];
  2426.                 endif;
  2427.                 if ('baloto' == $opRequest->dataTransf->x_payment_data) {
  2428.                     $paymentResume['transaction_state'] = 3;
  2429.                 }
  2430.             } elseif (isset($opRequest->infoCash)) {
  2431.                 $paymentResume = [
  2432.                     'transaction_state' => 2,
  2433.                     'id' => $orderProduct->getBooking(),
  2434.                     'id_context' => $opRequest->infoCash->x_reference,
  2435.                     'currency' => $opRequest->infoCash->x_currency,
  2436.                     'total_amount' => $opRequest->infoCash->x_total_amount,
  2437.                     'client_franquice' => ['description' => 'Efectivo'],
  2438.                     'amount' => null,
  2439.                     'iva' => null,
  2440.                     'ip_address' => $opRequest->infoCash->dirIp,
  2441.                     'airport_tax' => null,
  2442.                     'reference' => $opRequest->infoCash->x_reference,
  2443.                     'auth' => null,
  2444.                     'transaction_date' => $opRequest->infoCash->x_fechavigencia,
  2445.                     'description' => $opRequest->infoCash->x_description,
  2446.                     'reason_code' => 101,
  2447.                     'reason_description' => 'Transacción creada',
  2448.                     'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
  2449.                     'client_email' => $opRequest->infoCash->x_email,
  2450.                     'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
  2451.                 ];
  2452.                 $cash_result json_decode($session->get($transactionId.'[assist][cash_result]'));
  2453.                 $paymentResume['transaction_state'] = 3;
  2454.                 if ('' == $cash_result) {
  2455.                     $paymentResume['transaction_state'] = 2;
  2456.                 }
  2457.             } else {
  2458.                 $bank_info $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
  2459.                 $bank_name $bank_info->getName();
  2460.                 $clientFranquice['description'] = 'PSE';
  2461.                 $paymentResume = [
  2462.                     'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
  2463.                     'id' => $orderProduct->getBooking(),
  2464.                     'id_context' => $opRequest->reference,
  2465.                     'currency' => $opRequest->currency,
  2466.                     'total_amount' => $opRequest->totalAmount,
  2467.                     'amount' => $opRequest->devolutionBase,
  2468.                     'iva' => $opRequest->taxAmount,
  2469.                     'ip_address' => $opRequest->ipAddress,
  2470.                     'bank_name' => $bank_name,
  2471.                     'client_franquice' => $clientFranquice,
  2472.                     'reference' => $opResponse->createTransactionResult->transactionID,
  2473.                     'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
  2474.                     'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
  2475.                     'description' => $opRequest->description,
  2476.                     'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
  2477.                     'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
  2478.                     'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
  2479.                     'client_email' => $opRequest->payer->emailAddress,
  2480.                 ];
  2481.             }
  2482.         } else {
  2483.             $paymentResume['id'] = $orderProduct->getBooking();
  2484.             $infoDetail explode('*'base64_decode($detail->get('TypeID')));
  2485.             $paymentResume['transaction_state'] = 1;
  2486.             if (isset($resumeTransaction['error'])) {
  2487.                 $paymentResume['transaction_state'] = 2;
  2488.             }
  2489.             $paymentResume['currency'] = $infoDetail[2];
  2490.             $paymentResume['total_amount'] = $infoDetail[3];
  2491.             if ($session->has('operatorId')) {
  2492.                 $paymentResume['client_names'] = $paymentData->first_name.' '.$paymentData->last_name;
  2493.                 $paymentResume['client_email'] = $paymentData->first_name.' '.$paymentData->last_name;
  2494.                 $paymentResume['customer_address'] = $paymentData->first_name.' '.$paymentData->last_name;
  2495.             } else {
  2496.                 $paymentResume['client_names'] = $customer->getFirstname().' '.$customer->getLastname();
  2497.             }
  2498.             $customer null;
  2499.         }
  2500.         $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  2501.         if ($session->has('operatorId')) {
  2502.             $paymentResume['transaction_state_cyber'] = 1;
  2503.         }
  2504.         $clientFranquice '';
  2505.         $retryCount = (int) $session->get($transactionId.'[assist][retry]');
  2506.         $agencyFolder $twigFolder->twigFlux();
  2507.         $routeName $request->get('_route');
  2508.         $detail $session->get($transactionId.'[assist]'.'[detail]');
  2509.         $detail_data_insurance json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
  2510.         $TypeID explode('*'base64_decode($detail->get('TypeID')));
  2511.         $informationCard explode('*'base64_decode($detail->get('informationCard')));
  2512.         $agencyData = [
  2513.             'agency_name' => $agency->getName(),
  2514.             'agency_nit' => $agency->getNit(),
  2515.             'agency_phone' => $agency->getPhone(),
  2516.             'agency_email' => $agency->getMailContact(),
  2517.         ];
  2518.         $emailData = [
  2519.             'retry_count' => $retryCount,
  2520.             'paymentResume' => $paymentResume,
  2521.             'order' => $orderProductCode->order,
  2522.             'products' => $orderProductCode->products,
  2523.             'method' => $detail->get('method'),
  2524.             'Estado' => 'error',
  2525.             'Name' => $TypeID[1],
  2526.             'TypeID' => $TypeID[0],
  2527.             'companyName' => $informationCard[1],
  2528.             'agencyData' => $agencyData,
  2529.             'info_travelers' => (array) $info_travelers,
  2530.             'transactionID' => $transactionId,
  2531.             'infoClient' => $facturationResume,
  2532.             'dateEntry' => $detail->get('dateEntry'),
  2533.             'dateEnd' => $detail->get('dateEnd'),
  2534.             'dateEntry' => $detail->get('dateEntry'),
  2535.             'total_amount' => $paymentResume['total_amount'],
  2536.         ];
  2537.         $infoDataFlight json_decode($session->get($transactionId.'[crossed]'.'[infoDataFlight]'), true);
  2538.         $resumeTransaction json_decode($session->get($transactionId.'[assist]'.'[resumeTransaction]'), true);
  2539.         $emailData['infoDataFlight'] = $infoDataFlight;
  2540.         $emailData['infoDataInsurance'] = $resumeTransaction;
  2541.         if (('aviatur_insurance_payment_rejected_secure' == $routeName)) {
  2542.             $urlResume '@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resume_insurance.html.twig';
  2543.         } else {
  2544.             $resumeOrderCreate $session->get($transactionId.'[assist]'.'[detail]');
  2545.             if ('assist' == $resumeOrderCreate->get('method')) {
  2546.                 $urlResume '@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resume_insurance.html.twig';
  2547.                 $info_travelers = (array) $detail_data_insurance->PI;
  2548.             } else {
  2549.                 $urlResume '@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resume_insurance_flight.html.twig';
  2550.                 $info_travelers $infoDataFlight['travelers'];
  2551.             }
  2552.         }
  2553.         /*         * *
  2554.          * Agente Octopus
  2555.          * Cambiar logo Correo Gracias por tu compra.
  2556.          */
  2557.         $isAgent false;
  2558.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
  2559.             $user $this->getUser();
  2560.             $agent $user->getAgent();
  2561.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  2562.             if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
  2563.                 $isAgent true;
  2564.                 $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  2565.                 $idAgentLogo $agent->getId();
  2566.                 $folderImg 'assets/octopus_assets/img/custom/logoAgent/'.$idAgentLogo.'.png';
  2567.                 $domain 'https://'.$agency->getDomain();
  2568.                 $folderLogoAgent $domain.'/'.$folderImg;
  2569.                 if (file_exists($folderImg)) {
  2570.                     $emailData['imgLogoAgent'] = $folderLogoAgent;
  2571.                 }
  2572.             }
  2573.         }
  2574.         $renderResumeView $emailData;
  2575.         $renderResumeView['infos'][0] = $emailData;
  2576.         $setTo null == $customer null $customer->getEmail();
  2577.         if ($session->has('operatorId')) {
  2578.             $userFront simplexml_load_string($session->get('front_user'));
  2579.             $setTo = (string) $userFront->CORREO_ELECTRONICO;
  2580.         }
  2581.         if (!isset($resumeTransaction['error']) && isset($resumeTransaction['Message']['OTA_InsuranceBookRS'])) {
  2582.             if (null != $emailData['infoDataInsurance']) {
  2583.                 $voucherFile $projectDir.'/app/serviceLogs/InsuranceVoucher/ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId().'_'.$transactionId.'.pdf';
  2584.                 if (!$session->has($transactionId.'[emission_assist_email]')) {
  2585.                     $pdf->generateFromHtml(
  2586.                         $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView),
  2587.                         $voucherFile
  2588.                     );
  2589.                     $message = (new \Swift_Message())
  2590.                             ->setContentType('text/html')
  2591.                             ->setFrom($session->get('emailNoReply'))
  2592.                             ->setTo($setTo)
  2593.                             ->setBcc([$emailNotification'soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co'])
  2594.                             ->setSubject($session->get('agencyShortName').' - '.'Reserva '.$informationCard[1].' Creada')
  2595.                             ->attach(\Swift_Attachment::fromPath($voucherFile))
  2596.                             ->setBody(
  2597.                                 $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView)
  2598.                             );
  2599.                     try {
  2600.                         $mailer->send($message);
  2601.                         $session->set($transactionId.'[emission_assist_email]''emailed');
  2602.                         /*
  2603.                          * Email de la reserva del agente hijo enviado al agente Padre Octopus.
  2604.                          */
  2605.                         //Fin entrega de tarjeta One-timeUnited
  2606.                         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
  2607.                             $bccMails = [$agency->getMailBooking()];
  2608.                             $agencyName '';
  2609.                             if ($session->has('whitemark')) {
  2610.                                 if ('' != $session->get('whitemarkMail')) {
  2611.                                     $bccMails[] = $session->get('whitemarkMail');
  2612.                                 }
  2613.                                 $agencyName $session->get('whitemarkName');
  2614.                             } else {
  2615.                                 $bccMails[] = $agency->getMailcontact();
  2616.                                 $agencyName $session->get('agencyShortName');
  2617.                             }
  2618.                             $user $this->getUser();
  2619.                             $agent $user->getAgent();
  2620.                             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  2621.                             if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
  2622.                                 $agent $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
  2623.                                 $request $request;
  2624.                                 $parent $agent->getparentAgent();
  2625.                                 if (!= $parent) {
  2626.                                     $myParent $em->createQuery('SELECT a,b FROM AviaturAgentBundle:Agent a  JOIN a.customer b WHERE a.id= :idAgent');
  2627.                                     $myParent $myParent->setParameter('idAgent'$parent);
  2628.                                     $parentInfo $myParent->getResult();
  2629.                                     $emailParent $parentInfo[0]->getCustomer()->getEmail();
  2630.                                     $emailData['infoSubAgent'] = ['nameSubAgent' => strtoupper($agent->getCustomer()->__toString()), 'emailSubAgent' => strtoupper($agent->getCustomer()->getEmail())];
  2631.                                     $renderResumeView $emailData;
  2632.                                     $renderResumeView['infos'][0] = $emailData;
  2633.                                     $messageAgent = (new \Swift_Message())
  2634.                                             ->setContentType('text/html')
  2635.                                             ->setFrom($session->get('emailNoReply'))
  2636.                                             ->setTo([$agent->getCustomer()->getEmail(), $emailParent])
  2637.                                             ->setBcc($bccMails)
  2638.                                             ->setSubject($agencyName.' - Reserva '.$informationCard[1].' Creada - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
  2639.                                             ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView));
  2640.                                     $mailer->send($messageAgent);
  2641.                                 } else {
  2642.                                     $messageAgent = (new \Swift_Message())
  2643.                                             ->setContentType('text/html')
  2644.                                             ->setFrom($session->get('emailNoReply'))
  2645.                                             ->setTo($agent->getCustomer()->getEmail())
  2646.                                             ->setBcc($bccMails)
  2647.                                             ->setSubject($session->get('agencyShortName').' - '.'Reserva '.$informationCard[1].' Creada'.' - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
  2648.                                             ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView));
  2649.                                     $mailer->send($messageAgent);
  2650.                                 }
  2651.                             }
  2652.                         }
  2653.                     } catch (\Exception $ex) {
  2654.                         $exceptionLog->log(
  2655.                             var_dump($message),
  2656.                             $ex
  2657.                         );
  2658.                     }
  2659.                 }
  2660.             }
  2661.         }
  2662.         $orderProduct->setEmail(json_encode($renderResumeView));
  2663.         if ($session->has($transactionId.'[emission][error]')) {
  2664.             $renderResumeView['emission_error'] = true;
  2665.         }
  2666.         if (isset($renderResumeView['paymentResume']['description'])) {
  2667.             $renderResumeView['descriptionInsurance'] = $renderResumeView['paymentResume']['description'];
  2668.         }
  2669.         if (isset($paymentResume['id_context'])) {
  2670.             $voucherFile $projectDir.'/app/serviceLogs/CashTransaction/ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  2671.             if (file_exists($voucherFile)) {
  2672.                 $renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  2673.             }
  2674.         }
  2675.         if ($session->has($transactionId.'[assist][cash_result]') && !$session->has($transactionId.'[emission_baloto_email]')) {
  2676.             $renderResumeView['cash_result'] = json_decode($session->get($transactionId.'[assist][cash_result]'));
  2677.             $renderResumeView['exportPDF'] = true;
  2678.             $ruta '@AviaturTwig/'.$agencyFolder.'/General/Templates/email_cash.html.twig';
  2679.             if (!file_exists($voucherFile)) {
  2680.                 $pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $renderResumeView), $voucherFile);
  2681.                 $renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  2682.             }
  2683.             $setTo $paymentResume['client_email'];
  2684.             $paymentResume['exportPDF'] = false;
  2685.             $message = (new \Swift_Message())
  2686.                     ->setContentType('text/html')
  2687.                     ->setFrom($session->get('emailNoReply'))
  2688.                     ->setTo($setTo)
  2689.                     // ->setBcc(array('soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co', $emailNotification))
  2690.                     ->setSubject($session->get('agencyShortName').' - Transacción Efectivo Creada '.$paymentResume['id_context'])
  2691.                     ->attach(\Swift_Attachment::fromPath($voucherFile))
  2692.                     ->setBody(
  2693.                         $this->renderView($twigFolder->twigExists($ruta), $renderResumeView)
  2694.                     );
  2695.             try {
  2696.                 $mailer->send($message);
  2697.                 $session->set($transactionId.'[emission_email]''emailed');
  2698.             } catch (\Exception $ex) {
  2699.                 $exceptionLog->log(var_dump($message), $ex);
  2700.             }
  2701.         }
  2702.         $pixelInfo = [];
  2703.         if (!$session->has('operatorId') && == $renderResumeView['paymentResume']['transaction_state']) {
  2704.             $pixel json_decode($session->get($transactionId.'[pixeles_info]'), true);
  2705.             $pixel['partner_datalayer']['event'] = 'seguros_purchase';
  2706.             $pixel['partner_datalayer']['dimension12'] = 'compra-seguro';
  2707.             $products = [
  2708.                 'actionField' => "{'id': '".$renderResumeView['paymentResume']['id_context']."', 'affiliation': 'Portal Web', 'revenue': '".$renderResumeView['paymentResume']['total_amount']."', 'tax':'".$renderResumeView['paymentResume']['iva']."', 'coupon': ''}",
  2709.                 'name' => $renderResumeView['Name'],
  2710.                 'price' => $renderResumeView['paymentResume']['total_amount'],
  2711.                 'brand' => 'assist card',
  2712.                 'category' => 'Seguros',
  2713.                 'variant' => $renderResumeView['descriptionInsurance'],
  2714.                 'quantity' => $detail->get('passenger'),
  2715.             ];
  2716.             if (isset($pixel['partner_datalayer']['ecommerce']['checkout'])) {
  2717.                 unset($pixel['partner_datalayer']['ecommerce']['checkout']);
  2718.             }
  2719.             $pixel['partner_datalayer']['ecommerce']['purchase']['products'] = $products;
  2720.             //$pixel['dataxpand'] = true;
  2721.             //$pixel['pickback'] = true;
  2722.             $pixelInfo $aviaturPixeles->verifyPixeles($pixel'insurance''resume'$agency->getAssetsFolder(), false);
  2723.             $renderResumeView['pixel_info'] = $pixelInfo;
  2724.         }
  2725.         $urlHome preg_replace('/^(https?:\/\/[^\/]+\/seguros-de-viaje).*/''$1'$session->get($transactionId '[availability_url]'));
  2726.         $renderResumeView['urlBase'] = $urlHome;
  2727.         $setResume $this->render($twigFolder->twigExists($urlResume), $renderResumeView);
  2728.         $orderProduct->setResume($setResume);
  2729.         $em->persist($orderProduct);
  2730.         $em->flush();
  2731.         return $setResume;
  2732.     }
  2733.     public function calcInfoPassenger(InsuranceService $insuranceService$passenger$method$infoBirth$fullRequest)
  2734.     {
  2735.         $dateBirth = [];
  2736.         $calculoEdades = [];
  2737.         $passanger_type = [];
  2738.         $variable = [];
  2739.         for ($i 1$i <= $passenger; ++$i) {
  2740.             if ('flight' == $method) {
  2741.                 if (== $passenger) {
  2742.                     $dateBirth[] = $infoBirth[0]['BirthDate'];
  2743.                 } else {
  2744.                     $dateBirth[] = $infoBirth[($i 1)]['BirthDate'];
  2745.                 }
  2746.             } else {
  2747.                 if (== $passenger) {
  2748.                     $dateBirth[] = $fullRequest->attributes->get('birth1');
  2749.                 } else {
  2750.                     $dateBirth[] = $fullRequest->attributes->get('birth'.$i);
  2751.                 }
  2752.             }
  2753.             $calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i 1)]);
  2754.             if ($calculoEdades[($i 1)] >= && $calculoEdades[($i 1)] < 2) {
  2755.                 $passanger_type[] = 1;
  2756.             } elseif ($calculoEdades[($i 1)] >= && $calculoEdades[($i 1)] < 12) {
  2757.                 $passanger_type[] = 2;
  2758.             } else {
  2759.                 $passanger_type[] = 3;
  2760.             }
  2761.             $variable[] = [
  2762.                 'BirthDate' => $dateBirth[($i 1)],
  2763.                 'Age' => $calculoEdades[($i 1)],
  2764.                 'passanger_type' => $passanger_type[($i 1)],
  2765.             ];
  2766.         }
  2767.         return $variable;
  2768.     }
  2769.     public function quotationAction(Request $fullRequestPdf $pdfAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderSessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBag, \Swift_Mailer $mailerAviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerExceptionLog $exceptionLogQuotationUtils $QuotationUtils)
  2770.     {
  2771.         $projectDir $parameterBag->get('kernel.project_dir');
  2772.         $typePerson = [];
  2773.         $quotationName $fullRequest->request->get('quotationName');
  2774.         $quotationLastname $fullRequest->request->get('quotationLastname');
  2775.         $quotationEmail $fullRequest->request->get('quotationEmail');
  2776.         $request $fullRequest->request;
  2777.         $transactionId $session->get('transactionId');
  2778.         //$fullRequest = $session->get($transactionId.'[assist][fullrequest]');
  2779.         $request $session->get($transactionId.'[assist][request]');
  2780.         $server $fullRequest->server;
  2781.         $isAgent false;
  2782.         $queryString $fullRequest->query;
  2783.         $isFront $session->has('operatorId');
  2784.         $em $registry->getManager();
  2785.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  2786.         $TypeID = (base64_decode($request->get('TypeID')));
  2787.         $partes explode('*'$TypeID);
  2788.         $variable_deseada trim($partes[1] . '.pdf');
  2789.         // src/Aviatur/InsuranceBundle/Entity/InsuranceInformation.php
  2790.         $InsuranceInfo $em->getRepository(\Aviatur\InsuranceBundle\Entity\InsuranceInformation::class)->findBy(['name' => $variable_deseada]);
  2791.         // $test = $em->getRepository(\Aviatur\InsuranceBundle\Entity\InsuranceInformation::class)->find($variable_deseada);
  2792.         $agencyFolder $twigFolder->twigFlux();
  2793.         $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  2794.         $datosAgente simplexml_load_string($session->get('front_user'));
  2795.         $detailIns simplexml_load_string($session->get($transactionId.'[assist][infoInsurance]'));
  2796.         if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
  2797.             $user $this->getUser();
  2798.             $emailuser $user->getemail();
  2799.             $agent $user->getAgent();
  2800.             if (!empty($agent[0])) {
  2801.                 $idagent $agent[0]->getid();
  2802.                 $nombreagente $user->getFirstname().' '.$user->getLastname();
  2803.                 $agencyFolder $twigFolder->twigFlux();
  2804.                 $isAgent true;
  2805.             }
  2806.         }
  2807.         $company = (string) $detailIns->OTA_InsuranceQuoteRS->PlanForQuoteRS->QuoteDetail->ProviderCompany['CompanyShortName'];
  2808.         $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_insurance');
  2809.         $twig_readonly false;
  2810.         $passanger_type json_decode($request->get('passanger_type'));
  2811.         $inf $chd $adt 0;
  2812.         for ($i 0$i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
  2813.             if (== $passanger_type[$i]) {
  2814.                 ++$inf;
  2815.             } elseif (== $passanger_type[$i]) {
  2816.                 ++$chd;
  2817.             } else {
  2818.                 ++$adt;
  2819.             }
  2820.         }
  2821.         $typePerson[1] = [
  2822.             'ADT' => $adt,
  2823.             'CHD' => $chd,
  2824.             'INF' => $inf,
  2825.         ];
  2826.         $TypeID explode('*'base64_decode($request->get('TypeID')));
  2827.         $x_total_amount $TypeID[3];
  2828.         // $x_base_amount = str_replace(array('[',']'),'',$TypeID[4]);
  2829.         $x_base_amount $x_total_amount;
  2830.         if ($isAgent) {
  2831.             $x_base_amount -= (float) $TypeID[7];
  2832.             $commissionAgent $TypeID[7];
  2833.             $commissionActive $TypeID[8];
  2834.             $commissionPay $TypeID[9];
  2835.             $activeDetail $TypeID[10];
  2836.             $amountTa $TypeID[11];
  2837.             $commissionTa $TypeID[12];
  2838.             $amountPay $TypeID[13];
  2839.             $percentageTarifa $TypeID[14];
  2840.         }
  2841.         $dataRestric = [];
  2842.         $countPlanRestrictions 0;
  2843.         $ProductInfoUnsort = [];
  2844.         $productPrices = [];
  2845.         // stores the plan restriction of the universal assistance.
  2846.         $arrPlanRestrictions = [];
  2847.         $arrDataExtra = [];
  2848.         $arrAttributesPlanRestrictions = [];
  2849.         foreach ($detailIns->OTA_InsuranceQuoteRS->PlanForQuoteRS as $Info) {
  2850.             if ($Info['PlanID'] == $request->get('id')) {
  2851.                 if (=== strcmp($company'Universal Assistance')) {
  2852.                     $countRestric 0;
  2853.                     foreach ($Info->QuoteDetail->PlanRestrictions->PlanRestriction as $restric) {
  2854.                         $dataRestric[$countRestric]['Name'] = $restric['Name'];
  2855.                         $dataRestric[$countRestric]['Code'] = $restric['Code'];
  2856.                         $dataRestric[$countRestric]['CodeContext'] = $restric['CodeContext'];
  2857.                         ++$countRestric;
  2858.                         if ($countRestric 2) {
  2859.                             break;
  2860.                         }
  2861.                     }
  2862.                 }
  2863.             }
  2864.             ++$countPlanRestrictions;
  2865.         }
  2866.         $variables = [
  2867.             'transactionId' => base64_encode($transactionId),
  2868.             'destiny' => $request->get('destiny'),
  2869.             'dateEntry' => $request->get('dateEntry'),
  2870.             'dateEnd' => $request->get('dateEnd'),
  2871.             'passenger' => $request->get('passenger'),
  2872.             'birth' => $request->get('birth'),
  2873.             'id' => $request->get('id'),
  2874.             'TypeID' => base64_decode($request->get('TypeID')),
  2875.             'informationCard' => base64_decode($request->get('informationCard')),
  2876.             'dataRestric' => $dataRestric ?? null,
  2877.             'providerId' => $request->get('providerId'),
  2878.             'method' => $request->get('method'),
  2879.             'passanger_type' => $passanger_type,
  2880.             'Age' => json_decode($request->get('Age')),
  2881.             'x_total_amount' => $x_total_amount,
  2882.             'x_base_amount' => $x_base_amount,
  2883.             'reintento' => false,
  2884.             'echoToken' => $request->get('echoToken'),
  2885.         ];
  2886.         if ($isAgent) {
  2887.             $variables['commissionAgent'] = $commissionAgent;
  2888.             $variables['commissionActive'] = $commissionActive;
  2889.             $variables['commissionPay'] = $commissionPay;
  2890.             $variables['commissionTa'] = $commissionTa;
  2891.             $variables['amountTa'] = $amountTa;
  2892.             $variables['activeDetail'] = $activeDetail;
  2893.             $variables['amountPay'] = $amountPay;
  2894.             /*$info_product = array('amountQse' => (float) $commissionAgent,
  2895.                 'commissionQse' => (float) $commissionPay,
  2896.                 'amountTa' => (float) $amountTa,
  2897.                 'commissionTa' => (float) $commissionTa,
  2898.                 'amountPay' => (float) $amountPay,
  2899.                 'amountProduct' => $x_base_amount,
  2900.                 'percentageTarifa' => isset($percentageTarifa) ? (float) $percentageTarifa : 0);
  2901.             $session->set($transactionId . '_agentInfoTransaction', $info_product);*/
  2902.         }
  2903.         if($company == "Axa Assistance"){
  2904.             $variables['description'] = $InsuranceInfo[0]->getDescription();
  2905.         }
  2906.         $codImg $QuotationUtils->curlImg($session);
  2907.         $tempFilePath $QuotationUtils->getfile($detailIns->OTA_InsuranceQuoteRS->PlanForQuoteRS$session$parameterBag);
  2908.         $urlAvailability $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/quotation.html.twig');
  2909.         $returnInfo = [
  2910.             'quotationName' => $quotationName,
  2911.             'quotationLastname' => $quotationLastname,
  2912.             'quotationEmail' => $quotationEmail,
  2913.             'services' => $typePerson,
  2914.             'codImg' => $codImg,
  2915.             'variables' => $variables,
  2916.             'conditions' => $conditions,
  2917.             'agentName' => $datosAgente->NOMBRE_AGENTE,
  2918.             'agentMail' => $additionalUserFront->CORREO_ELECTRONICO ?? $datosAgente->CORREO_ELECTRONICO,
  2919.             'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
  2920.             'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL ?? $datosAgente->CIUDAD,
  2921.             'agentCity' => $datosAgente->CIUDAD,
  2922.         ];
  2923.         
  2924.         $html $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/quotation.html.twig');
  2925.         $namefilepdf 'Aviatur_cotizacion_tarjeta_asistencia_'.$transactionId;
  2926.         $voucherInsuranceFile $projectDir.'/app/quotationLogs/insuranceQuotation/'.$namefilepdf.'.pdf';
  2927.         if (!file_exists($voucherInsuranceFile)) {
  2928.             $pdf->setOption('page-size''LETTER');
  2929.             $pdf->setOption('margin-top'0);
  2930.             $pdf->setOption('margin-right'0);
  2931.             $pdf->setOption('margin-bottom'0);
  2932.             $pdf->setOption('margin-left'0);
  2933.             $pdf->setOption('orientation''portrait');
  2934.             $pdf->setOption('enable-javascript'true);
  2935.             $pdf->setOption('no-stop-slow-scripts'true);
  2936.             $pdf->setOption('no-background'false);
  2937.             $pdf->setOption('lowquality'false);
  2938.             $pdf->setOption('encoding''utf-8');
  2939.             $pdf->setOption('images'true);
  2940.             $pdf->setOption('dpi'300);
  2941.             $pdf->setOption('enable-external-links'true);
  2942.             $pdf->setOption('enable-internal-links'true);
  2943.             $pdf->generateFromHtml($this->renderView($html$returnInfo), $voucherInsuranceFile);
  2944.         }
  2945.         $voucherInsuranceFiles array_merge ([$voucherInsuranceFile],[$tempFilePath]);
  2946.         $nameProduct str_replace(["cotizacion""/""check-conditions"], ""$fullRequest->getPathInfo());
  2947.         $QuotationUtils->sendQuotation($nameProduct,$voucherInsuranceFiles$mailer$session$twigFolder$codImg ,$fullRequest$parameterBag ,$aviaturWebService ,$pdf ,$exceptionLog);
  2948.         chmod($projectDir.'/app/quotationLogs/insuranceQuotation/'0777);
  2949.         
  2950.         
  2951.         foreach ($voucherInsuranceFiles as $voucherFile) {
  2952.             if (file_exists($voucherFile)) {
  2953.                 unlink($voucherFile);
  2954.             }
  2955.         }
  2956.         $this->saveInformationCGS($registry$aviaturLogSave$aviaturWebService$aviaturErrorHandler$returnInfo$additionalUserFront$request$agency);
  2957.         return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Hotel/Default/resume_quotation.html.twig'), ['nameProduct'=> $nameProduct]);
  2958.         
  2959.     }
  2960.     public function saveInformationCGS(ManagerRegistry $registryAviaturLogSave $aviaturLogSaveAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandler$data$customer$request$agency)
  2961.     {
  2962.         $em $registry->getManager();
  2963.         $parametersLogin $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency'aviatur_service_login_cgs');
  2964.         $urlLoginCGS $parametersLogin[0]['value'];
  2965.         $parametersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency'aviatur_service_insurance_cgs');
  2966.         $urlAddProductInsurance $parametersProduct[0]['value'];
  2967.         /*
  2968.          * get token api autentication
  2969.          * PENDIENTE: Validar si se puede obtener el token, si no entonces no hacer este proceso
  2970.          */
  2971.         $userLoginCGS $aviaturWebService->encryptUser(trim(strtolower($customer->CODIGO_USUARIO)), 'AviaturCGSMTK');
  2972.         $jsonReq json_encode(['username' => $userLoginCGS]); //j_acosta (encriptado)
  2973.         $curl curl_init();
  2974.         curl_setopt_array($curl, [
  2975.             CURLOPT_URL => $urlLoginCGS,
  2976.             CURLOPT_RETURNTRANSFER => true,
  2977.             CURLOPT_SSL_VERIFYPEER => false,
  2978.             CURLOPT_ENCODING => '',
  2979.             CURLOPT_MAXREDIRS => 10,
  2980.             CURLOPT_TIMEOUT => 0,
  2981.             CURLOPT_FOLLOWLOCATION => true,
  2982.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  2983.             CURLOPT_CUSTOMREQUEST => 'POST',
  2984.             CURLOPT_POSTFIELDS => $jsonReq,
  2985.             CURLOPT_HTTPHEADER => [
  2986.                 'Content-Type: application/json',
  2987.             ],
  2988.         ]);
  2989.         $response curl_exec($curl);
  2990.         $httpcode curl_getinfo($curlCURLINFO_HTTP_CODE);
  2991.         curl_close($curl);
  2992.         if (200 != $httpcode) {
  2993.             $aviaturLogSave->logSave('HTTPCODE: '.$httpcode.' Error usuario: '.strtolower($customer->CODIGO_USUARIO), 'CGS_LOGIN''CGS_ERRORLOGIN');
  2994.             $aviaturLogSave->logSave(print_r($responsetrue), 'CGS_LOGIN''RSLoginCGS');
  2995.             return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/seguros-de-viaje/''Error Login''Error Login'));
  2996.         } else {
  2997.             $tokenInfoApiQuotation json_decode($response);
  2998.             $tokenApiQuotation $tokenInfoApiQuotation->TOKEN;
  2999.         }
  3000.         ini_set('xdebug.var_display_max_depth''-1');
  3001.         ini_set('xdebug.var_display_max_children''-1');
  3002.         ini_set('xdebug.var_display_max_data''-1');
  3003.         $informationCard explode('*'base64_decode($request->get('informationCard')));
  3004.         $TypeID explode('*'base64_decode($request->get('TypeID')));
  3005.         $destiny '';
  3006.         switch ($request->get('destiny')) {
  3007.             case '1':
  3008.                 $destiny 'Norteamérica';
  3009.                 break;
  3010.             case '2':
  3011.                 $destiny 'Europa - Medio Oriente';
  3012.             break;
  3013.             case '3':
  3014.                 $destiny 'Centroamérica y Caribe';
  3015.             break;
  3016.             case '4':
  3017.                 $destiny 'Suramérica (sin cobertura en Colombia)';
  3018.             break;
  3019.             case '5':
  3020.                 $destiny 'África';
  3021.             break;
  3022.             case '6':
  3023.                 $destiny 'Asia';
  3024.             break;
  3025.             case '7':
  3026.                 $destiny 'Oceanía';
  3027.             break;
  3028.             case '8':
  3029.                 $destiny 'Colombia (sin cobertura para extranjeros)';
  3030.             break;
  3031.             default:
  3032.                 $destiny 'Sin destino';
  3033.                 break;
  3034.         }
  3035.         $emails_arr = [
  3036.             'active' => true,
  3037.             'dateCreated' => '0001-01-01T00:00:00',
  3038.             'emailAddress' => (string) $data['quotationEmail'],
  3039.             'id' => 0,
  3040.             'lastUpdated' => '0001-01-01T00:00:00',
  3041.             'version' => 0,
  3042.         ];
  3043.         $phones_arr = [
  3044.             'active' => false,
  3045.             'dateCreated' => '0001-01-01T00:00:00',
  3046.             'id' => 0,
  3047.             'lastUpdated' => '0001-01-01T00:00:00',
  3048.             'number' => null,
  3049.             'type' => null,
  3050.             'version' => 0,
  3051.         ];
  3052.         $data_send = [
  3053.             'customer' => [
  3054.                 'firstName' => (string) $data['quotationName'],
  3055.                 'lastName' => (string) $data['quotationLastname'],
  3056.                 'mothersName' => null,
  3057.                 'fullName' => trim($data['quotationName']).' '.trim($data['quotationLastname']),
  3058.                 'birthDate' => 'true',
  3059.                 'billingInformations' => null,
  3060.                 'emails' => [$emails_arr],
  3061.                 'phones' => [$phones_arr],
  3062.                 'city' => null,
  3063.                 ],
  3064.             'selectedProduct' => [
  3065.                 'description' => (string) $TypeID[1],
  3066.                 'packageName' => (string) $TypeID[1],
  3067.                 'emit' => false,
  3068.                 'fareData' => [
  3069.                     'aditionalFee' => 0.0,
  3070.                     'airpotService' => null,
  3071.                     'baseFare' => (int) $data['variables']['x_total_amount'],
  3072.                     'cO' => 0.0,
  3073.                     'commission' => 0.0,                //Consultar esto
  3074.                     'commissionPercentage' => 0.0,      //Consultar esto
  3075.                     'complements' => null,
  3076.                     'currency' => [
  3077.                         'type' => (string) $TypeID[2],
  3078.                     ],
  3079.                     'equivFare' => 0.0,
  3080.                     'iva' => 0.0,
  3081.                     'otherDebit' => null,
  3082.                     'otherTax' => null,
  3083.                     'price' => (int) $data['variables']['x_total_amount'],
  3084.                     'providerPrice' => 0.0,
  3085.                     'qSe' => 0.0,                       //Consultar esto
  3086.                     'qSeIva' => 0.0,
  3087.                     'qse' => null,
  3088.                     'revenue' => 0.0,
  3089.                     'serviceCharge' => 0.0,
  3090.                     'sureCancel' => null,
  3091.                     'tA' => 0.0,
  3092.                     'taIva' => 0.0,
  3093.                     'tax' => 0.0,
  3094.                     'total' => (int) $data['variables']['x_total_amount'],
  3095.                     'yQ' => 0.0,
  3096.                     'yQiva' => 0.0,
  3097.                     'originalNationalCurrencyTotal' => (int) $data['variables']['x_total_amount'],
  3098.                 ],
  3099.                 'passengerDataList' => [
  3100.                     [
  3101.                         'fareData' => null,
  3102.                         'gender' => '',
  3103.                         'id' => '',
  3104.                         'lastName' => (string) $request->get('quotationLastname'),
  3105.                         'mail' => (string) $request->get('quotationEmail'),
  3106.                         'mothersName' => '',
  3107.                         'name' => (string) $request->get('quotationName'),
  3108.                         'passengerCode' => [
  3109.                             'accountCode' => '',
  3110.                             'promo' => false,
  3111.                             'realType' => 'ADT',
  3112.                             'type' => 'ADT',
  3113.                         ],
  3114.                         'passengerContact' => null,
  3115.                         'passengerInsuranceInfo' => null,
  3116.                         'phone' => null,
  3117.                         'document' => null,
  3118.                         'typeDocument' => null,
  3119.                     ],
  3120.                 ],
  3121.                 'productType' => [
  3122.                     'description' => 'Tarjeta de Asistencia',
  3123.                     'typeProduct' => 'Insurance',
  3124.                 ],
  3125.                 'provider' => [
  3126.                     'category' => null,
  3127.                     'claveProveedor' => null,
  3128.                     'commissionPercentage' => 0,
  3129.                     'descripcionProveedor' => null,
  3130.                     'idProviders' => 0,
  3131.                     'name' => (string) $informationCard[1],
  3132.                     'nuevoProveedor' => false,
  3133.                     'providerRef' => null,
  3134.                     'utilityMax' => 0,
  3135.                     'utilityMin' => 0,
  3136.                 ],
  3137.                 'route' => [
  3138.                     'arrivalDate' => (string) $request->get('dateEnd').'T00:00:00',
  3139.                     'arrivalDateString' => null,
  3140.                     'arrivalDescription' => (string) $destiny,
  3141.                     'arrivalIATA' => null,
  3142.                     'departureDate' => (string) $request->get('dateEntry').'T00:00:00',
  3143.                     'departureDateString' => null,
  3144.                     'departureDescription' => (string) $destiny,
  3145.                     'departureIATA' => null,
  3146.                     'destination' => null,
  3147.                     'flightTime' => null,
  3148.                     'origin' => null,
  3149.                     'providerCode' => null,
  3150.                     'subRoutes' => null,
  3151.                 ],
  3152.             ],
  3153.             'quote' => [
  3154.                 'channel' => 'B2C WEB',
  3155.             ],
  3156.         ];
  3157.         $authorization 'Authorization: Bearer '.$tokenApiQuotation;
  3158.         //API URL
  3159.         $url $urlAddProductInsurance;
  3160.         //create a new cURL resource
  3161.         $ch curl_init($url);
  3162.         //setup request to send json via POST
  3163.         $payload json_encode($data_send);
  3164.         $aviaturLogSave->logSave(print_r($payloadtrue), 'CGS_INSURANCE''RQInsuranceCGS');
  3165.         // print_r($payload);die;
  3166.         //attach encoded JSON string to the POST fields
  3167.         curl_setopt($chCURLOPT_POSTFIELDS$payload);
  3168.         //set the content type to application/json
  3169.         curl_setopt($chCURLOPT_HTTPHEADER, [
  3170.             'accept: application/json',
  3171.             'authorization: Bearer '.$tokenApiQuotation,
  3172.             'content-type: application/json',
  3173.         ]);
  3174.         curl_setopt($chCURLOPT_CUSTOMREQUEST'POST');
  3175.         curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  3176.         curl_setopt($chCURLOPT_MAXREDIRS10);
  3177.         curl_setopt($chCURLOPT_TIMEOUT0);
  3178.         curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  3179.         curl_setopt($chCURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_1);
  3180.         //return response instead of outputting
  3181.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  3182.         //execute the POST request
  3183.         $result curl_exec($ch);
  3184.         $aviaturLogSave->logSave(print_r($resulttrue), 'CGS_INSURANCE''RSInsuranceCGS');
  3185.         //print_r($result);
  3186.         //die;
  3187.         //close CURL resource
  3188.         curl_close($ch);
  3189.         /*
  3190.          * End API data send
  3191.          */
  3192.     }
  3193.     protected function authenticateUser(UserInterface $userLoginManagerInterface $loginManager)
  3194.     {
  3195.         try {
  3196.             $loginManager->loginUser(
  3197.                 'main',
  3198.                 $user
  3199.             );
  3200.         } catch (AccountStatusException $ex) {
  3201.             // We simply do not authenticate users which do not pass the user
  3202.             // checker (not enabled, expired, etc.).
  3203.         }
  3204.     }
  3205. }