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

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