src/Aviatur/CustomerBundle/Controller/DefaultController.php line 670

Open in your IDE?
  1. <?php
  2. namespace Aviatur\CustomerBundle\Controller;
  3. use Aviatur\CustomerBundle\Entity\Customer;
  4. use Aviatur\CustomerBundle\Entity\CustomerBillingList;
  5. use Aviatur\CustomerBundle\Entity\HistoricalCustomer;
  6. use Aviatur\GeneralBundle\Entity\OrderTrace;
  7. use Aviatur\CustomerBundle\Models\CustomerModel;
  8. use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
  9. use Aviatur\FormBundle\Entity\Newsletter;
  10. use Aviatur\GeneralBundle\Services\AviaturAthServices;
  11. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  12. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  13. use Aviatur\GeneralBundle\Services\AviaturLoginService;
  14. use Aviatur\GeneralBundle\Services\AviaturWebService;
  15. use Aviatur\PaymentBundle\Entity\PaymentMethodCustomer;
  16. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  17. use Aviatur\PaymentBundle\Services\TokenizerService;
  18. use Aviatur\TwigBundle\Services\TwigFolder;
  19. use DateTime;
  20. use Doctrine\Persistence\ManagerRegistry;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\HttpFoundation\Session\Session;
  27. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  28. use Symfony\Component\Routing\RouterInterface;
  29. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  30. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  31. use Symfony\Component\Validator\Validator\ValidatorInterface;
  32. use Aviatur\CustomerBundle\Services\PhoneNumberService;
  33. class DefaultController extends AbstractController
  34. {
  35.     /**
  36.      * @var \Doctrine\Persistence\ObjectManager
  37.      */
  38.     protected $em;
  39.     /**
  40.      * @var \Aviatur\AgencyBundle\Entity\Agency|object|null
  41.      */
  42.     protected $agency;
  43.     /**
  44.      * @var AviaturAthServices
  45.      */
  46.     protected $athServices;
  47.     /**
  48.      * @var bool
  49.      */
  50.     protected $isAval;
  51.     public function __construct(ManagerRegistry $managerRegistrySessionInterface $sessionAviaturAthServices $athServices)
  52.     {
  53.         $em $managerRegistry->getManager();
  54.         $agencyId $session->has('agencyId') ? $session->get('agencyId') : 1;
  55.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
  56.         $this->em $em;
  57.         $this->agency $agency;
  58.         $this->athServices $athServices;
  59.         // Validación para agencia Aval
  60.         if ($agency->getAssetsFolder() == 'aval') {
  61.             $this->isAval true;
  62.         } else {
  63.             $this->isAval false;
  64.         }
  65.     }
  66.     public function getDataAction(Request $requestManagerRegistry $managerRegistryAviaturWebService $webServiceAviaturErrorHandler $errorHandlerTwigFolder $twigFolderParameterBagInterface $parameterBag)
  67.     {
  68.         if ($request->isXmlHttpRequest()) {
  69.             $doc_type $request->query->get('doc_type');
  70.             $documentNumber $request->query->get('doc_num');
  71.             $em $managerRegistry->getManager();
  72.             $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($doc_type);
  73.             $data $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['documentType' => $documentType'documentnumber' => $documentNumber]);
  74.             if (empty($data)) {
  75.                 //si no encuentra en la base local busca en el servidor de aviatur
  76.                 $customerModel = new CustomerModel();
  77.                 $xmlRequest $customerModel->getXmlFindUser($doc_type$documentNumber'0926EB''BOGVU2900');
  78.                 $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  79.                 if ((null != $response) && ('error' != $response)) {
  80.                     if (!isset($response['error']) && is_object($response)) {
  81.                         if (('FALLO' == $response->RESULTADO) && (false !== strpos($response->MENSAJE'No se enco'))) {
  82.                             return $this->json(['no_info' => (string) $response->MENSAJE]);
  83.                         } elseif (('FALLO' == $response->RESULTADO)) {
  84.                             $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: '.(string) $response->MENSAJE);
  85.                             return $this->json(['error' => (string) $response->MENSAJE]);
  86.                         } else {
  87.                             $customer = new Customer();
  88.                             $dataNumber $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneBy(['code' => $response->document->id]);
  89.                             $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneBy(['code' => $response->gender->id]);
  90.                             $dataMaritalStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneBy(['code' => $response->marital_starus->id]);
  91.                             $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['code' => $response->city->id]);
  92.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneBy(['code' => $response->country->id]);
  93.                             try {
  94.                                 $customer->setAviaturclientid((int) $response->id);
  95.                                 $customer->setDocumentType($dataNumber);
  96.                                 $customer->setCivilStatus($dataMaritalStatus);
  97.                                 $customer->setGenderAviatur($dataGender);
  98.                                 $customer->setCity($dataCity);
  99.                                 $customer->setCountry($dataCountry);
  100.                                 $customer->setDocumentnumber($documentNumber);
  101.                                 $customer->setFirstname($response->name);
  102.                                 $customer->setLastname($response->last_name);
  103.                                 $customer->setBirthdate(new \DateTime($response->birth_date));
  104.                                 $customer->setAddress($response->address);
  105.                                 $customer->setPhone($response->phone_number);
  106.                                 $customer->setCellphone($response->mobile_phone_number);
  107.                                 $customer->setEmail($response->email);
  108.                                 $customer->setEmailCanonical($response->email);
  109.                                 $customer->setUsername($response->email);
  110.                                 $customer->setUsernameCanonical($response->email);
  111.                                 $customer->setPassword($response->password);
  112.                                 $customer->setAcceptInformation(0);
  113.                                 $customer->setAcceptSms(0);
  114.                                 $customer->setPersonType($response->person_type->id);
  115.                                 $customer->setFrecuencySms(0);
  116.                                 $customer->setCorporateId('');
  117.                                 $customer->setCorporateName('');
  118.                                 $customer->setEnabled(1);
  119.                                 $customer->setRoles([]);
  120.                                 $emo $managerRegistry->getManager();
  121.                                 $emo->persist($customer);
  122.                                 $emo->flush();
  123.                                 $return = [
  124.                                     'id' => $customer->getId(),
  125.                                     'first_name' => substr_replace($response->name'********'3),
  126.                                     'last_name' => substr_replace($response->last_name'********'3),
  127.                                     'address' => substr_replace($response->address'********'3),
  128.                                     'doc_num' => (string) $response->document->number,
  129.                                     'doc_type' => $dataNumber->getExternalcode(),
  130.                                     'phone' => substr_replace($response->phone_number'*******'3),
  131.                                     'email' => substr_replace($response->email'********'3),
  132.                                     'gender' => $dataGender->getCode(),
  133.                                     'birthday' => ((null != $response->birth_date) && ('' != $response->birth_date)) ? \date('Y-m-d', \strtotime($response->birth_date)) : null,
  134.                                     'nationality' => ((null != $dataCountry) && ('' != $dataCountry)) ? $dataCountry->getIataCode() : null,
  135.                                     'nationality_label' => ((null != $dataCountry) && ('' != $dataCountry)) ? \ucwords(\mb_strtolower($dataCountry->getDescription())).' ('.$dataCountry->getIataCode().')' null,
  136.                                 ];
  137.                             } catch (\Doctrine\ORM\ORMException $e) {
  138.                                 $errorHandler->errorRedirect('/vuelos/detalle''''Ha ocurrido un error ingresando el nuevo usuario a la base de datos');
  139.                                 return $this->json(['error' => 'Ha ocurrido un error ingresando el nuevo usuario a la base de datos']);
  140.                             } catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
  141.                                 $mensaje 'Información incompleta o inconsistente: '.$e->getMessage();
  142.                                 $errorHandler->errorRedirect('/vuelos/detalle'''$mensaje);
  143.                                 return $this->json(['error' => $mensaje]);
  144.                             } catch (\Exception $e) {
  145.                                 $errorHandler->errorRedirect('/vuelos/detalle''''Ha ocurrido un error inesperado en la creación del nuevo usuario');
  146.                                 return $this->json(['error' => 'Ha ocurrido un error inesperado en la creación del nuevo usuario']);
  147.                             }
  148.                         }
  149.                     } else {
  150.                         $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: '.(string) $response['error']);
  151.                         return $this->json(['error' => (string) $response['error']]);
  152.                     }
  153.                 } else {
  154.                     $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: Error inesperado en la consulta');
  155.                     return $this->json(['error' => 'Error inesperado en la consulta']);
  156.                 }
  157.             } else {
  158.     $phoneService = new PhoneNumberService($em);
  159.     
  160.     $hasPhone = (null != $data->getPhone()) && ('' != $data->getPhone());
  161.     $hasCellphone = (null != $data->getCellphone()) && ('' != $data->getCellphone());
  162.     
  163.     $phoneParts $hasPhone 
  164.         $phoneService->extractPhoneComponents($data->getPhone()) 
  165.         : ['prefix' => null'number' => null];
  166.     $cellphoneParts $hasCellphone 
  167.         $phoneService->extractPhoneComponents($data->getCellphone()) 
  168.         : ['prefix' => null'number' => null];
  169.     
  170.     $return = [
  171.         'id' => $data->getId(),
  172.         'first_name' => ((null != $data->getFirstname()) && ('' != $data->getFirstname())) ? utf8_encode(substr_replace($data->getFirstname(), '********'3)) : null,
  173.         'last_name' => ((null != $data->getLastname()) && ('' != $data->getLastname())) ? utf8_encode(substr_replace($data->getLastname(), '********'3)) : null,
  174.         'address' => ((null != $data->getAddress()) && ('' != $data->getAddress())) ? substr_replace($data->getAddress(), '********'3) : null,
  175.         'city' => ((null != $data->getCity()) && ('' != $data->getCity())) ? substr_replace($data->getCity()->getDescription(), '********'3) : null,
  176.         'doc_num' => ((null != $data->getDocumentnumber()) && ('' != $data->getDocumentnumber())) ? $data->getDocumentnumber() : null,
  177.         'doc_type' => ((null != $data->getDocumentType()) && ('' != $data->getDocumentType())) ? $data->getDocumentType()->getExternalcode() : null,
  178.         'phone' => $hasPhone substr_replace($phoneParts['number'], '*******'3) : null,
  179.         'cellphone' => $hasCellphone substr_replace($cellphoneParts['number'], '*******'3) : null,
  180.         'phone_prefix' => $phoneParts['prefix'],
  181.         'cellphone_prefix' => $cellphoneParts['prefix'],       
  182.         'email' => ((null != $data->getEmail()) && ('' != $data->getEmail())) ? substr_replace($data->getEmail(), '********'3) : null,
  183.         'gender' => ((null != $data->getGenderAviatur()) && ('' != $data->getGenderAviatur())) ? $data->getGenderAviatur()->getCode() : null,
  184.         'birthday' => ((null != $data->getBirthdate()) && ('' != $data->getBirthdate())) ? \date('Y-m-d'$data->getBirthdate()->getTimestamp()) : null,
  185.         'city_id' => ((null != $data->getCity()) && (null != $data->getCity()->getIatacode()) && ('' != $data->getCity()->getIatacode())) ? $data->getCity()->getIatacode() : null,
  186.         'nationality' => ((null != $data->getCountry()) && ('' != $data->getCountry())) ? $data->getCountry()->getIataCode() : null,
  187.         'nationality_label' => ((null != $data->getCountry()) && ('' != $data->getCountry())) ? \ucwords(\mb_strtolower($data->getCountry()->getDescription())).' ('.$data->getCountry()->getIataCode().')' null,
  188.     ];
  189.     }
  190.             return $this->json($return);
  191.         } else {
  192.             $errorHandler->errorRedirect('/vuelos/detalle''''Acceso no autorizado');
  193.             return $errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado');
  194.         }
  195.     }
  196.     public function getB2TDataAction(Request $requestAviaturWebService $webServiceAviaturErrorHandler $errorHandlerParameterBagInterface $parameterBag)
  197.     {
  198.         $return = [];
  199.         $doc_type $request->query->get('doc_type');
  200.         $documentNumber $request->query->get('doc_num');
  201.         //si no encuentra en la base local busca en el servidor de aviatur
  202.         $customerModel = new CustomerModel();
  203.         $xmlRequest $customerModel->getXmlFindUserB2T($doc_type$documentNumber'G_ROA''BOGVU2900');
  204.         $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  205.         if ((('FALLO' == $response->RESULTADO) && (false !== strpos($response->MENSAJE'No se enco'))) || (('EXITO' == $response->RESULTADO) && empty($response->CLIENTES))) {
  206.             return $this->json(['no_info' => (string) $response->MENSAJE]);
  207.         } elseif (('FALLO' == $response->RESULTADO)) {
  208.             $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: '.(string) $response->MENSAJE);
  209.             return $this->json(['error' => (string) $response->MENSAJE]);
  210.         } else {
  211.             foreach ($response->CLIENTES->ELEMENTO_LISTA_CLIENTES as $client) {
  212.                 $return[] = [
  213.                     'id' => (string) $client->IDENTIFICADOR_INTERNO,
  214.                     'first_name' => ucwords($this->sanear_string(mb_strtolower((string) $client->NOMBRE))),
  215.                     'last_name' => ucwords($this->sanear_string(mb_strtolower((string) $client->APELLIDO))),
  216.                     'doc_num' => ucwords(mb_strtolower((string) $client->NUMERO_DE_DOCUMENTO)),
  217.                     'doc_type' => $request->query->get('doc_type'),
  218.                     'phone' => (string) $client->TELEFONO,
  219.                     'consecutive' => (string) $client->CONSECUTIVO,
  220.                 ];
  221.             }
  222.         }
  223.         return $this->json($return);
  224.     }
  225.     public function createAction(Request $requestManagerRegistry $managerRegistryAviaturWebService $webServiceAviaturErrorHandler $errorHandlerTokenStorageInterface $tokenStorageSessionInterface $sessionValidateSanctionsRenewal $validateSanctionsRenewalParameterBagInterface $parameterBag)
  226.     {
  227.         $customer null;
  228.         $transactionId $session->get('transactionId');
  229.         $em $this->em;
  230.         $billingData $request->get('BD');
  231.         $paymentData $request->get('PD');
  232.         $customerdData $request->get('CD');
  233.         $customerdData['phone'] = (new PhoneNumberService($em))->choosePhone($customerdData);
  234.         $billingData['phone'] = (new PhoneNumberService($em))->choosePhone($billingData);
  235.         $paymentData['phone'] = (new PhoneNumberService($em))->choosePhone($paymentData);
  236.         $paymentMethod $paymentData['type'] ?? 'other';
  237.         if ($request->request->has('MS')) {
  238.             $passangers $billingData;
  239.         } else {
  240.             $passangers array_merge($billingData$request->get('PI'));
  241.         }
  242.         $isFront $session->has('operatorId');
  243.         $session->remove('loginFromDetail');
  244.         foreach ($passangers as $prop => $passanger) {
  245.             if (preg_match('/^doc_num/i'$prop) && '' == $passangers[$prop]) {
  246.                 $errorHandler->errorRedirect('/vuelos/detalle''''undefined_doc_num');
  247.                 return $this->json(['error' => 'El número de identificación no puede estar vacío']);
  248.             }
  249.         }
  250.         $server $request->server;
  251.         $urlDomain parse_url($server->get('HTTP_REFERER'), PHP_URL_HOST);
  252.         /* Inicio comparación ONU-OFAC */
  253.         $postData $request->request->all();
  254.         if(!$this->getValidationOnuOfac($postData$server->get('HTTP_REFERER'), $session$validateSanctionsRenewal)){
  255.             $errorHandler->errorRedirect('/vuelos/detalle''''sanctions_candidate');
  256.             return $this->json(['error' => 'No se puede continuar con la transacción. Por favor, contáctese con la línea de atención al usuario de AVIATUR']);
  257.         }
  258.         /* Fin comparación ONU-OFAC */
  259.         $parameters json_decode($session->get($request->getHost().'[parameters]'));
  260.         if (isset($parameters->switch_login_agencies) && '' != $parameters->switch_login_agencies) {
  261.             $login_agencies json_decode($parameters->switch_login_agenciestrue);
  262.             if (isset($login_agencies[$session->get('agencyId')])) {
  263.                 $login_is_on $login_agencies[$session->get('agencyId')];
  264.             } else {
  265.                 $login_is_on $login_agencies['all'];
  266.             }
  267.         } else {
  268.             $login_is_on '0';
  269.         }
  270.         if (!$isFront && false !== strpos($urlDomain'bbva') && !$this->validateSpecialConditionPayment($request->get('PD')['card_num'])) {
  271.             $errorHandler->errorRedirectNoEmail('/vuelos/detalle''''no_sppayment_condition');
  272.             return $this->json(['error' => 'no_sppayment_condition']);
  273.         }
  274.         if ((isset($billingData['id'])) && ('' != $billingData['id']) && (null != $billingData['id'])) {
  275.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  276.             /* if ($login_is_on == '1') {
  277.               if ($this->get("aviatur_login_service")->validActiveSession() === false) {
  278.               $session->set('loginFromDetail', true);
  279.               return $this->json(array("error" => "no_granted_session_condition"));
  280.               } else if (!isset($request->get('PD')['methodsRecovered'])) { */
  281. //                $customerLogin = $this->get('security.token_storage')->getToken()->getUser();
  282. //
  283. //                //Verify is client is same logged client
  284.             ////                if ($customerLogin->getEmail() != $customer->getEmail() && !isset($billingData['anotherCustomerCheck'])) {
  285.             ////                    return $this->json(array("error" => "notSamePersonLogged"));
  286.             ////                }
  287. //
  288. //                $infoMethodPaymentByClient = $this->get("aviatur_methods_customer_service")->getMethodsByCustomer($customerLogin, false);
  289. //                if ($infoMethodPaymentByClient['info'] !== 'NoInfo') {
  290. //                    return $this->json(array("error" => "customer_with_methods_saved", "info" => $infoMethodPaymentByClient['info']));
  291. //                }
  292.             /* }
  293.               } */
  294.             if (isset($billingData['address']) && (false === strpos($billingData['address'], '***')) && (('' == $customer->getAddress()) || (null == $customer->getAddress()))) {
  295.                 $customer->setAddress($billingData['address']);
  296.             }
  297.             if (isset($billingData['phone']) && (false === strpos($billingData['phone'], '***')) && (('' == $customer->getPhone()) || (null == $customer->getPhone()))) {
  298.                 $customer->setPhone($billingData['phone']);
  299.             }
  300.             $em->flush();
  301.             /*
  302.             if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $customer->getDocumentnumber(), 'name' => $customer->getFirstname().' '.$customer->getLastname()], $paymentMethod)) {
  303.                 $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  304.                 return $this->json(['error' => 'sanctions_candidate']);
  305.             }
  306.             */
  307.             $passengerStructured = [];
  308.             $passengerStructuredGroup null;
  309.             foreach ($passangers as $passKey => $passengerValue) {
  310.                 if (!preg_match('/.*_\d_\d$/'$passKey) || strstr($passengerValue'***')) {
  311.                     continue;
  312.                 }
  313.                 $matchArray = [];
  314.                 preg_match('/.*_(\d_\d)$/'$passKey$matchArray);
  315.                 if (!isset($matchArray[1])) {
  316.                     continue;
  317.                 }
  318.                 $passengerStructuredGroup = !$passengerStructuredGroup $matchArray[1] : ($passengerStructuredGroup !== $matchArray[1] ? $matchArray[1] : $passengerStructuredGroup);
  319.                 if (strstr($passKey'doc_num')) {
  320.                     $passengerStructured[$passengerStructuredGroup]['document'] = $passengerValue;
  321.                     $passengerStructured[$passengerStructuredGroup]['name'] = '';
  322.                 } elseif (strstr($passKey'first_name') || strstr($passKey'last_name')) {
  323.                     $passengerStructured[$passengerStructuredGroup]['name'] .= $passengerValue.' ';
  324.                 }
  325.             }
  326.             foreach ($passengerStructured as $pax) {
  327.                 if ('' === trim($pax['name'])) {
  328.                     continue;
  329.                 }
  330.                 /*
  331.                 if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $pax['document'], 'name' => $pax['name']], $paymentMethod)) {
  332.                     $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  333.                     return $this->json(['error' => 'sanctions_candidate']);
  334.                 }
  335.                 */
  336.             }
  337.             $return = [
  338.                 'id' => $customer->getId(),
  339.             ];
  340.             $redemptionPoint $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($this->agency);
  341.             if (isset($redemptionPoint) && isset($postData['PD']['pointRedemptionValue'])) {
  342.                 if ($postData['PD']['pointRedemptionValue'] !== '0' && $postData['PD']['pointRedemptionValue'] != null) {
  343.                     $avalPoints $postData['PD']['pointRedemptionValue'];
  344.                     if ($avalPoints 0) {
  345.                         $info = [
  346.                             "token" => NULL,
  347.                             "transactionId" => $transactionId,
  348.                             "totalPoints" => $avalPoints
  349.                         ];
  350.                         $disposablePoints $this->athServices->disposablePoints($infotrue);
  351.                         if (isset($disposablePoints['ok']) && $avalPoints $disposablePoints['ok']['text']['PointOfService']) {
  352.                             $return += ["error" => "Los puntos que quiere redimir no están disponibles para completar su transacción, por favor intente nuevamente"];
  353.                         } else if (isset($disposablePoints['error'])) {
  354.                             $return += ["error" => "1.Lo sentimos no podemos procesar la transacción, por favor vuelva a intentar más tarde"];
  355.                         } else {
  356.                             $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_ath');
  357.                             if (!isset(json_decode($parameters->getDescription())->NoOtp) || (isset(json_decode($parameters->getDescription())->NoOtp) && !json_decode($parameters->getDescription())->NoOtp)) {
  358.                                 $return += $this->generateOtp($redemptionPoint$session$postData);
  359.                             }
  360.                             if (isset($return['StatusCode'])) {
  361.                                 if ($return['StatusCode'] !== '0' && $return['StatusCode'] !== 0) {
  362.                                     $return += ["error" => "Lo sentimos no podemos procesar  a la transacción, por favor vuelva a intentar más tarde"];
  363.                                 }
  364.                             }
  365.                         }
  366.                     }
  367.                 }
  368.             }
  369.             return $this->json($return);
  370.         } else {
  371.             $userLogged $tokenStorage->getToken()->getUser();
  372.             if ($userLogged && $userLogged = !'anon.') {
  373.                 $billingData['id'] = $userLogged->getId();
  374.                 if (null != $userLogged->getFacebookId() || null != $userLogged->getGoogleId()) {
  375.                     $passangerData $request->get('PI');
  376.                     /*
  377.                     if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $billingData['doc_num'], 'name' => $billingData['first_name'].' '.$billingData['last_name']], $paymentMethod)) {
  378.                         $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  379.                         return $this->json(['error' => 'sanctions_candidate']);
  380.                     }
  381.                     */
  382.                     if ($request->get('same-billing')) {
  383.                         if ('on' == $request->get('same-billing')) {
  384.                             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($userLogged->getId());
  385.                             $dataNumberDocType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($passangerData['doc_type_1_1']);
  386.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangerData['nationality_1_1']);
  387.                             $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
  388.                             $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangerData['gender_1_1']);
  389.                             $customer->setDocumentType($dataNumberDocType);
  390.                             $customer->setDocumentnumber($passangerData['doc_num_1_1']);
  391.                             $customer->setFirstname($passangerData['first_name_1_1']);
  392.                             $customer->setLastname($passangerData['last_name_1_1']);
  393.                             $customer->setAddress($passangerData['address_1_1']);
  394.                             $customer->setPhone($customerdData['phone']);
  395.                             $customer->setCountry($dataCountry);
  396.                             $customer->setCity($dataCity);
  397.                             $customer->setBirthdate(new \DateTime($passangerData['birthday_1_1']));
  398.                             $customer->setGenderAviatur($dataGender);
  399.                         }
  400.                     } else {
  401.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($userLogged->getId());
  402.                         $dataNumberDocType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($billingData['doc_type']);
  403.                         if (isset($billingData['nationality']) && '' != $billingData['nationality']) {
  404.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($billingData['nationality']);
  405.                         } else {
  406.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode('CO');
  407.                         }
  408.                         $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
  409.                         $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($billingData['gender']);
  410.                         $customer->setDocumentType($dataNumberDocType);
  411.                         $customer->setDocumentnumber($billingData['doc_num']);
  412.                         $customer->setFirstname($billingData['first_name']);
  413.                         $customer->setLastname($billingData['last_name']);
  414.                         $customer->setAddress($billingData['address']);
  415.                         $customer->setPhone($billingData['phone']);
  416.                         $customer->setCountry($dataCountry);
  417.                         $customer->setCity($dataCity);
  418.                         $customer->setBirthdate(new \DateTime($billingData['birthday']));
  419.                         $customer->setGenderAviatur($dataGender);
  420.                     }
  421.                     $em->persist($customer);
  422.                     $em->flush();
  423.                     $return = [
  424.                         'id' => $userLogged->getId(),
  425.                     ];
  426.                     return $this->json($return);
  427.                 }
  428.             }
  429.             $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findByExternalcode($billingData['doc_type']);
  430.             $registered $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findBy(['documentnumber' => $billingData['doc_num'], 'documentType' => $documentType]);
  431.             if (!= sizeof($registered)) {
  432.                 return $this->json(['id' => $registered[0]->getId()]);
  433.             }
  434.             /*$data = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findByEmail($billingData['email']);
  435.             if (0 != sizeof($data)) {
  436.                 $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'email_exist');
  437.                 return $this->json(['error' => 'email_exist']);
  438.             }*/
  439.             $customerModel = new CustomerModel();
  440.             $doc_type explode('-'$billingData['doc_type']);
  441.             $xmlRequest $customerModel->getXmlFindUser($doc_type[0] , $billingData['doc_num'], '0926EB''BOGVU2900');
  442.             //$xmlRequest = $customerModel->getXmlFindUserByEmail($billingData['email'], 4);
  443.             $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  444.             if ((isset($response->RESULTADO) && ('FALLO' != $response->RESULTADO)) || (isset($response->ID))) {
  445.                 $errorHandler->errorRedirectNoEmail('/vuelos/detalle''''Error al crear el usuario');
  446.                 return $this->json(['error' => 'Error al crear el usuario']);
  447.             } elseif (isset($response->MENSAJE) && (false !== strpos($response->MENSAJE'No se enco'))) {
  448.                 $doc_type explode('-'$billingData['doc_type']);
  449.                 $passangerData $request->get('PI');
  450.                 /* if ($login_is_on == '0') { */
  451.                 $dataNumber $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($doc_type[0]);
  452.                 $personType = (!= $dataNumber->getId()) && (!= $dataNumber->getId()) && (!= $dataNumber->getId()) ? 7;
  453.                 $customer = new Customer();
  454.                 $customer->setAddress('' != $billingData['address'] ? $billingData['address'] : $passangerData['address_1_1']);
  455.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
  456.                 if (isset($passangerData['nationality_1_1']) && '' != $passangerData['nationality_1_1']) {
  457.                     $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangerData['nationality_1_1']);
  458.                 } else {
  459.                     $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode('CO');
  460.                 }
  461.                 $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangerData['gender_1_1']);
  462.                 $customer->setGenderAviatur($dataGender);
  463.                 if ($billingData['doc_num'] == $passangerData['doc_num_1_1']) {
  464.                     $customer->setBirthdate(new \DateTime($passangerData['birthday_1_1']));
  465.                 } else {
  466.                     $customer->setBirthdate(new \DateTime(date('Y-m-d'strtotime('-18 year'time()))));
  467.                 }
  468.                 $customer->setDocumentType($dataNumber);
  469.                 $customer->setCity($dataCity);
  470.                 $customer->setCountry($dataCountry);
  471.                 $customer->setDocumentnumber($billingData['doc_num']);
  472.                 $customer->setFirstname($billingData['first_name']);
  473.                 $customer->setLastname($billingData['last_name']);
  474.                 $customer->setPhone($billingData['phone']);
  475.                 $customer->setCellphone($billingData['phone']);
  476.                 $customer->setEmail($billingData['email']);
  477.                 $customer->setEmailCanonical($billingData['email']);
  478.                 $customer->setUsername($billingData['email']);
  479.                 $customer->setUsernameCanonical($billingData['email']);
  480.                 $customer->setAcceptInformation(0);
  481.                 $customer->setAcceptSms(0);
  482.                 $customer->setAviaturclientid(0);
  483.                 $customer->setPersonType($personType);
  484.                 $customer->setPassword(sha1('Default Aviatur'));
  485.                 $customer->setRoles([]);
  486.                 try {
  487.                     $em->persist($customer);
  488.                     $em->flush();
  489.                 } catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
  490.                     $mensaje 'Información incompleta o inconsistente: '.$e->getMessage();
  491.                     $errorHandler->errorRedirectNoEmail('/vuelos/detalle'''$mensaje);
  492.                     return $this->json(['error' => $mensaje]);
  493.                 }
  494.                 /* } */
  495.                 /*
  496.                 if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $billingData['doc_num'], 'name' => $billingData['first_name'].' '.$billingData['last_name']], $paymentMethod)) {
  497.                     $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  498.                     return $this->json(['error' => 'sanctions_candidate']);
  499.                 }
  500.                 */
  501.                 /* if ($login_is_on == '1') {
  502.                   $session->set('register-extra-data', [
  503.                   'email' => $billingData["email"],
  504.                   'documentType' => $doc_type[0],
  505.                   'documentNumber' => $billingData['doc_num'],
  506.                   'firstName' => $billingData["first_name"],
  507.                   'lastName' => $billingData["last_name"],
  508.                   'gender' => $passangerData["gender_1_1"],
  509.                   'birthDate' => $passangerData["birthday_1_1"],
  510.                   'address' => $billingData['address'] != '' ? $billingData['address'] : $passangerData["address_1_1"],
  511.                   'phone' => $billingData["phone"]
  512.                   ]);
  513.                   return $this->json(array("error" => "redirect_to_register"));
  514.                   } */
  515.                 $return = [
  516.                     'id' => $customer->getId(),
  517.                 ];
  518.                 if (isset($redemptionPoint)) {
  519.                     $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_ath');
  520.                     if (!isset(json_decode($parameters->getDescription())->NoOtp) || (isset(json_decode($parameters->getDescription())->NoOtp) && json_decode($parameters->getDescription())->NoOtp == false)) {
  521.                         $return += $this->generateOtp($redemptionPoint$session$postData);
  522.                     }
  523.                 }
  524.                 return $this->json($return);
  525.             } else {
  526.                 $errorHandler->errorRedirect('/vuelos/detalle''''Ha ocurrido un error en la consulta de usuarios por email');
  527.                 return $this->json(['error' => 'Ha ocurrido un error en la consulta de usuarios por email']);
  528.             }
  529.         }
  530.     }
  531.     public function loginSelectAction(Request $requestAviaturWebService $webServiceRouterInterface $routerParameterBagInterface $parameterBag)
  532.     {
  533.         $email $request->request->get('email');
  534.         $em $this->getDoctrine()->getManager();
  535.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['email' => $email]);
  536.         $enabled false;
  537.         $session = new Session();
  538.         $session->set('AnonymousEmail'$email);
  539.         if (!empty($customer)) {
  540.             if (false == $customer->getEnabled()) {
  541.                 return $this->redirect($this->generateUrl('aviatur_password_create_nocheck'));
  542.             } else {
  543.                 $route $router->match($this->generateUrl('fos_user_security_login'));
  544.                 return $this->forward($route['_controller'], $route);
  545.             }
  546.         } else {
  547.             $customerModel = new CustomerModel();
  548.             $xmlRequest $customerModel->getXmlFindUserByEmail($email4);
  549.             $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  550.             if (!is_object($response)) {
  551.                 return $this->redirect($this->generateUrl('fos_user_registration_register'));
  552.             } elseif (('FALLO' == $response->RESULTADO)) {
  553.                 return $this->redirect($this->generateUrl('fos_user_registration_register'));
  554.             } else {
  555.                 $customer = new Customer();
  556.                 $dataNumber $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneBy(['code' => $response->document->id]);
  557.                 $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneBy(['code' => $response->gender->id]);
  558.                 $dataMaritalStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneBy(['code' => $response->marital_starus->id]);
  559.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['code' => $response->city->id]);
  560.                 $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneBy(['code' => $response->country->id]);
  561.                 $customer->setAviaturclientid((int) $response->id);
  562.                 $customer->setDocumentType($dataNumber);
  563.                 $customer->setCivilStatus($dataMaritalStatus);
  564.                 $customer->setGenderAviatur($dataGender);
  565.                 $customer->setCity($dataCity);
  566.                 $customer->setCountry($dataCountry);
  567.                 $customer->setDocumentnumber($response->document->number);
  568.                 $customer->setFirstname($response->name);
  569.                 $customer->setLastname($response->last_name);
  570.                 $customer->setBirthdate(new \DateTime($response->birth_date));
  571.                 $customer->setAddress($response->address);
  572.                 $customer->setPhone($response->phone_number);
  573.                 $customer->setCellphone($response->mobile_phone_number);
  574.                 $customer->setEmail($response->email);
  575.                 $customer->setEmailCanonical($response->email);
  576.                 $customer->setUsername($response->email);
  577.                 $customer->setUsernameCanonical($response->email);
  578.                 $customer->setPassword($response->password);
  579.                 $customer->setAcceptInformation(0);
  580.                 $customer->setAcceptSms(0);
  581.                 $customer->setPersonType(8);
  582.                 $customer->setFrecuencySms(0);
  583.                 $customer->setCorporateId('');
  584.                 $customer->setCorporateName('');
  585.                 $customer->setEnabled(1);
  586.                 $customer->setRoles([]);
  587.                 $emo $this->getDoctrine()->getManager();
  588.                 $emo->persist($customer);
  589.                 $emo->flush();
  590.                 $route $router->match($this->generateUrl('fos_user_security_login'));
  591.                 return $this->forward($route['_controller'], $route);
  592.             }
  593.         }
  594.     }
  595.     public function getCustomerCardsAction(Request $requestTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentService)
  596.     {
  597.         if ($request->isXmlHttpRequest()) {
  598.             $customerLogin $tokenStorage->getToken()->getUser();
  599.             $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLoginfalse);
  600.             if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
  601.                 return $this->json(['info' => 'customer_with_methods_saved''info' => $infoMethodPaymentByClient['info']]);
  602.             }
  603.             return $this->json(['error' => 'no-data']);
  604.         }
  605.         return $this->json(['error']);
  606.     }
  607.     public function passwordCreateAction(TwigFolder $twigFolder)
  608.     {
  609.         $agencyFolder $twigFolder->twigFlux();
  610.         $response $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/create-password.html.twig'), []);
  611.         return $response;
  612.     }
  613.     public function passwordRessetAction(TwigFolder $twigFolder)
  614.     {
  615.         $agencyFolder $twigFolder->twigFlux();
  616.         $response $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/resset-password.html.twig'), []);
  617.         return $response;
  618.     }
  619.     public function customerAccountAction(AviaturErrorHandler $errorHandlerTwigFolder $twigFolderTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentServiceAviaturLoginService $loginService)
  620.     {
  621.         $agencyFolder $twigFolder->twigFlux();
  622.         $em $this->getDoctrine()->getManager();
  623.         //var_dump($tokenStorage->getToken()->getUser());die;
  624.         if (is_object($tokenStorage->getToken()->getUser())) {
  625.             $userLogged $tokenStorage->getToken()->getUser()->getId();
  626.         } else {
  627.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  628.         }
  629.         $customer $this->getUser();
  630.         $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerfalse);
  631.         if ($infoMethodPaymentByClient) {
  632.             $cardSaved = [];
  633.             if (false !== $loginService->validActiveSession()) {
  634.                 if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
  635.                     foreach ($infoMethodPaymentByClient['info'] as $key => $value) {
  636.                         $cardSaved['info'][] = [substr($key02), substr($key24)];
  637.                     }
  638.                 }
  639.             }
  640.         }
  641.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  642.         if ($billingList) {
  643.             $dataBilling = [];
  644.             $count 0;
  645.             foreach ($billingList as $billings) {
  646.                 if ('ACTIVE' == $billings->getStatus()) {
  647.                     $dataBilling[$count]['id'] = $billings->getId();
  648.                     $dataBilling[$count]['customerId'] = $userLogged;
  649.                     $dataBilling[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  650.                     $dataBilling[$count]['documentNumber'] = $billings->getDocumentnumber();
  651.                     $dataBilling[$count]['firstname'] = $billings->getFirstname();
  652.                     $dataBilling[$count]['lastname'] = $billings->getLastname();
  653.                     $dataBilling[$count]['email'] = $billings->getEmail();
  654.                     $dataBilling[$count]['address'] = $billings->getAddress();
  655.                     $dataBilling[$count]['phone'] = $billings->getPhone();
  656.                     ++$count;
  657.                 }
  658.             }
  659.         }
  660.         $newsletter = new Newsletter();
  661.         $newsletterForm $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
  662.         $paylaterParam $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_later');
  663.         $data = [
  664.             'cards' => !empty($cardSaved) ? $cardSaved null,
  665.             'billings' => !empty($dataBilling) ? $dataBilling null,
  666.             'newsletter_form' => $newsletterForm->createView(),
  667.             'paylater' => $paylaterParam->getValue() == true false,
  668.         ];
  669.         $response $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-account.html.twig'), $data);
  670.         return $response;
  671.     }
  672.     public function getBillingsAjaxAction(TokenStorageInterface $tokenStorage)
  673.     {
  674.         $userLogged $tokenStorage->getToken()->getUser()->getId();
  675.         $em $this->getDoctrine()->getManager();
  676.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  677.         if ($billingList) {
  678.             $dataBilling = [];
  679.             $count 0;
  680.             foreach ($billingList as $billings) {
  681.                 if ('ACTIVE' == $billings->getStatus()) {
  682.                     $dataBilling[$count]['id'] = $billings->getId();
  683.                     $dataBilling[$count]['customerId'] = $userLogged;
  684.                     $dataBilling[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  685.                     $dataBilling[$count]['documentNumber'] = $billings->getDocumentnumber();
  686.                     $dataBilling[$count]['firstname'] = $billings->getFirstname();
  687.                     $dataBilling[$count]['lastname'] = $billings->getLastname();
  688.                     $dataBilling[$count]['email'] = $billings->getEmail();
  689.                     $dataBilling[$count]['address'] = $billings->getAddress();
  690.                     $dataBilling[$count]['phone'] = $billings->getPhone();
  691.                     $dataBilling[$count]['country'] = $billings->getCountry()->getId();
  692.                     $dataBilling[$count]['city'] = $billings->getCity()->getId();
  693.                     ++$count;
  694.                 }
  695.             }
  696.             return $this->json(['status' => 'success''data' => ['billings' => !empty($dataBilling) ? $dataBilling null'totalBillings' => $count]]);
  697.         } else {
  698.             return $this->json(['status' => 'error']);
  699.         }
  700.     }
  701.     public function customerBookingAction(SessionInterface $sessionAviaturEncoder $aviaturEncoderTwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  702.     {
  703.         $customer $tokenStorage->getToken()->getUser();
  704.         $em $this->getDoctrine()->getManager();
  705.         $orderProducts = [];
  706.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  707.         $agencyOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$agency);
  708.         $orderProducts = \array_merge($orderProducts$agencyOrderProducts);
  709.         if ('aviatur.com' == $agency->getDomain()) {
  710.             $metasearch $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1); //Metasearch
  711.             $metaOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$metasearch);
  712.             $orderProducts = \array_merge($orderProducts$metaOrderProducts);
  713.             $mobile $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(102); //Mobile
  714.             $mobileOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$mobile);
  715.             $orderProducts = \array_merge($orderProducts$mobileOrderProducts);
  716.         }
  717.         $payRequests = [];
  718.         $orders = [];
  719.         foreach ($orderProducts as $key => $orderProduct) {
  720.             $productRequestString $aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey());
  721.             $productResponseString $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  722.             $productRequest json_decode($productRequestStringtrue);
  723.             $productResponse json_decode($productResponseStringtrue);
  724.             if(!is_array($productRequest)){
  725.                 continue;
  726.             }
  727.             $productRequest['orderId'] = 'ON'.$orderProduct->getOrder()->getId();
  728.             if (isset($productRequest['x_amount'])) {
  729.                 $productRequest['x_payment_type'] = 'p2p';
  730.                 $productRequest['x_transaction_date'] = $productResponse['x_transaction_date'] ?? '';
  731.                 $productRequest['x_response_code'] = $productResponse['x_response_code'] ?? '';
  732.                 $productRequest['x_response_reason_code'] = $productResponse['x_response_reason_code'] ?? '';
  733.                 $productRequest['x_response_reason_text'] = isset($productResponse['x_response_reason_text']) ? utf8_decode($productResponse['x_response_reason_text']) : '';
  734.                 $productRequest['x_ta_response_reason_code'] = $productResponse['x_ta_response_reason_code'] ?? '--';
  735.                 $productRequest['x_approval_code'] = $productResponse['x_approval_code'] ?? '';
  736.                 $productRequest['x_ta_approval_code'] = $productResponse['x_ta_approval_code'] ?? '--';
  737.                 $productRequest['x_transaction_id'] = $productResponse['x_transaction_id'] ?? '--';
  738.                 $productRequest['x_ta_transaction_id'] = $productResponse['x_ta_transaction_id'] ?? '--';
  739.                 $payRequests[] = $productRequest;
  740.                 $orders['ON'.$orderProduct->getOrder()->getId()] = null;
  741.             } elseif (isset($productRequest['totalAmount']) && isset($productResponse['getTransactionInformationResult'])) {
  742.                 $productRequest['x_payment_type'] = 'pse';
  743.                 $productRequest['x_invoice_num'] = $productRequest['reference'];
  744.                 $productRequest['x_description'] = $productRequest['description'];
  745.                 $productRequest['x_currency_code'] = $productRequest['currency'];
  746.                 $productRequest['x_amount'] = $productRequest['totalAmount'];
  747.                 $productRequest['x_tax'] = $productRequest['taxAmount'];
  748.                 $productRequest['x_amount_base'] = $productRequest['devolutionBase'];
  749.                 $productRequest['x_transaction_date'] = $productResponse['getTransactionInformationResult']['requestDate'] ?? '';
  750.                 $productRequest['x_response_code'] = $productResponse['getTransactionInformationResult']['responseCode'] ?? '';
  751.                 $productRequest['x_response_reason_code'] = $productResponse['getTransactionInformationResult']['responseReasonCode'] ?? '';
  752.                 $productRequest['x_response_reason_text'] = $productResponse['getTransactionInformationResult']['responseReasonText'] ?? '';
  753.                 $productRequest['x_approval_code'] = $productResponse['getTransactionInformationResult']['trazabilityCode'] ?? '';
  754.                 $productRequest['x_transaction_id'] = $productResponse['getTransactionInformationResult']['transactionID'] ?? '';
  755.                 $payRequests[] = $productRequest;
  756.                 $orders['ON'.$orderProduct->getOrder()->getId()] = null;
  757.             } elseif (isset($productRequest['notificationRequest']) && isset($productResponse['payResponse'])) {
  758.                 $productRequest['x_payment_type'] = 'safetypay';
  759.                 $productRequest['x_invoice_num'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:MerchantSalesID'];
  760.                 $productRequest['x_description'] = @$productRequest['dataTransf']['x_description'];
  761.                 $productRequest['x_currency_code'] = @$productRequest['dataTransf']['x_currency'];
  762.                 $productRequest['x_amount'] = @$productRequest['dataTransf']['x_total_amount'];
  763.                 $productRequest['x_tax'] = @$productRequest['dataTransf']['x_tax_amount'];
  764.                 $productRequest['x_airport_tax'] = 0;
  765.                 $productRequest['x_service_fee_tax'] = 0;
  766.                 $productRequest['x_airport_tax'] = 0;
  767.                 $productRequest['x_airport_tax'] = 0;
  768.                 $productRequest['x_amount_base'] = @$productRequest['dataTransf']['x_devolution_base'];
  769.                 $productRequest['x_transaction_date'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:RequestDateTime'];
  770.                 $productRequest['x_response_reason_code'] = @$productResponse['dataTransf']['x_response_code'];
  771.                 switch ($productRequest['x_response_reason_code']) {
  772.                     case 101:
  773.                         $productRequest['x_response_code'] = 3;
  774.                         break;
  775.                     case 100:
  776.                         $productRequest['x_response_code'] = 2;
  777.                         break;
  778.                     case null:
  779.                         $productRequest['x_response_code'] = 3;
  780.                         break;
  781.                     default:
  782.                         $productRequest['x_response_code'] = 1;
  783.                         break;
  784.                 }
  785.                 $productRequest['x_response_reason_text'] = @$productResponse['dataTransf']['x_response_reason_text'];
  786.                 $productRequest['x_approval_code'] = 'N/A';
  787.                 $productRequest['x_transaction_id'] = 'N/A';
  788.                 $payRequests[] = $productRequest;
  789.                 $orders['ON'.$orderProduct->getOrder()->getId()] = null;
  790.             }
  791.             $historicalOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalOrderProduct::class)->findByOrderProduct($orderProduct);
  792.             if (!= sizeof($historicalOrderProducts)) {
  793.                 foreach ($historicalOrderProducts as $historicalOrderProduct) {
  794.                     $productRequest $aviaturEncoder->AviaturDecode($historicalOrderProduct->getPayrequest(), $historicalOrderProduct->getPublickey());
  795.                     $productResponse $aviaturEncoder->AviaturDecode($historicalOrderProduct->getPayresponse(), $historicalOrderProduct->getPublickey());
  796.                     $productRequest json_decode($productRequesttrue);
  797.                     $productResponse json_decode($productResponsetrue);
  798.                     if (isset($productRequest['x_amount'])) {
  799.                         $productRequest['x_payment_type'] = 'p2p';
  800.                         $productRequest['x_transaction_date'] = $productResponse['x_transaction_date'] ?? '';
  801.                         $productRequest['x_response_code'] = $productResponse['x_response_code'] ?? '';
  802.                         $productRequest['x_response_reason_code'] = $productResponse['x_response_reason_code'] ?? '';
  803.                         $productRequest['x_response_reason_text'] = isset($productResponse['x_response_reason_text']) ? utf8_decode($productResponse['x_response_reason_text']) : '';
  804.                         $productRequest['x_ta_response_reason_code'] = $productResponse['x_ta_response_reason_code'] ?? '';
  805.                         $productRequest['x_approval_code'] = $productResponse['x_approval_code'] ?? '';
  806.                         $productRequest['x_ta_approval_code'] = $productResponse['x_ta_approval_code'] ?? '';
  807.                         $productRequest['x_transaction_id'] = $productResponse['x_transaction_id'] ?? '';
  808.                         $productRequest['x_ta_transaction_id'] = $productResponse['x_ta_transaction_id'] ?? '';
  809.                         $payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
  810.                     } elseif (isset($productRequest['totalAmount']) && isset($productResponse['getTransactionInformationResult'])) {
  811.                         $productRequest['x_payment_type'] = 'pse';
  812.                         $productRequest['x_invoice_num'] = $productRequest['reference'];
  813.                         $productRequest['x_description'] = $productRequest['description'];
  814.                         $productRequest['x_currency_code'] = $productRequest['currency'];
  815.                         $productRequest['x_amount'] = $productRequest['totalAmount'];
  816.                         $productRequest['x_tax'] = $productRequest['taxAmount'];
  817.                         $productRequest['x_amount_base'] = $productRequest['devolutionBase'];
  818.                         $productRequest['x_transaction_date'] = $productResponse['getTransactionInformationResult']['requestDate'] ?? '';
  819.                         $productRequest['x_response_code'] = $productResponse['getTransactionInformationResult']['responseCode'];
  820.                         $productRequest['x_response_reason_code'] = $productResponse['getTransactionInformationResult']['responseReasonCode'];
  821.                         $productRequest['x_response_reason_text'] = utf8_decode($productResponse['getTransactionInformationResult']['responseReasonText']);
  822.                         $productRequest['x_approval_code'] = $productResponse['getTransactionInformationResult']['trazabilityCode'] ?? '';
  823.                         $productRequest['x_transaction_id'] = $productResponse['getTransactionInformationResult']['transactionID'] ?? '';
  824.                         $payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
  825.                     } elseif (isset($productRequest['notificationRequest']) && isset($productResponse['payResponse'])) {
  826.                         $productRequest['x_payment_type'] = 'safetypay';
  827.                         $productRequest['x_invoice_num'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:MerchantSalesID'];
  828.                         $productRequest['x_description'] = @$productRequest['dataTransf']['x_description'];
  829.                         $productRequest['x_currency_code'] = @$productRequest['dataTransf']['x_currency'];
  830.                         $productRequest['x_amount'] = @$productRequest['dataTransf']['x_total_amount'];
  831.                         $productRequest['x_tax'] = @$productRequest['dataTransf']['x_tax_amount'];
  832.                         $productRequest['x_airport_tax'] = 0;
  833.                         $productRequest['x_service_fee_tax'] = 0;
  834.                         $productRequest['x_amount_base'] = @$productRequest['dataTransf']['x_devolution_base'];
  835.                         $productRequest['x_transaction_date'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:RequestDateTime'];
  836.                         $productRequest['x_response_code'] = 'N/A'//$productResponse['getTransactionInformationResult']['responseCode'];
  837.                         $productRequest['x_response_reason_code'] = 'N/A'//$productResponse['getTransactionInformationResult']['responseReasonCode'];
  838.                         $productRequest['x_response_reason_text'] = 'N/A'//$productResponse['getTransactionInformationResult']['responseReasonText'];
  839.                         $productRequest['x_approval_code'] = 'N/A'//$productResponse['getTransactionInformationResult']['trazabilityCode'];
  840.                         $productRequest['x_transaction_id'] = 'N/A'//$productResponse['getTransactionInformationResult']['transactionID'];
  841.                         $payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
  842.                     }
  843.                 }
  844.             }
  845. //            var_dump($productResponse);
  846. //            CREATE THE PUBLIC KEY AND ENCODE PayRequest AND PayResponse
  847. //            $encodedRequest = $this->get("aviatur_md5")->AviaturEncode($orderProduct->getPayRequest(), $orderProduct->getPublicKey());
  848. //            $encodedResponse = $this->get("aviatur_md5")->AviaturEncode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  849. //            $publicKey = $this->get("aviatur_md5")->aviaturRandomKey();
  850. //            $orderProduct->setPayRequest($encodedRequest);
  851. //            $orderProduct->setPayResponse($encodedResponse);
  852. //            $orderProduct->setPublicKey($publicKey);
  853. //            $em = $this->getDoctrine()->getManager();
  854. //            $em->persist($orderProduct);
  855. //            $em->flush();
  856.         }
  857.         $agencyFolder $twigFolder->twigFlux();
  858.         $twigView $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-booking.html.twig');
  859.         return $this->render($twigView, ['payRequests' => $payRequests'orders' => $orders]);
  860.     }
  861.     
  862.     public function customerBookingCAction(SessionInterface $sessionAviaturEncoder $aviaturEncoderTwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  863.     {
  864.         $em $this->getDoctrine()->getManager();
  865.         $paylaterParam $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_later');
  866.         if($paylaterParam->getValue() == 1){
  867.         $customer $tokenStorage->getToken()->getUser();
  868.         $em $this->getDoctrine()->getManager();
  869.         $orderProducts = [];
  870.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  871.         $agencyOrderProductsPayLater $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPayLaterWithCustomerAndAgency($customer$agency);
  872.         $orderProducts = \array_merge($orderProducts$agencyOrderProductsPayLater);
  873.         if ('aviatur.com' == $agency->getDomain()) {
  874.             $metasearch $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1); //Metasearch
  875.             $metaOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$metasearch);
  876.             $orderProducts = \array_merge($orderProducts$metaOrderProducts);
  877.             $mobile $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(102); //Mobile
  878.             $mobileOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$mobile);
  879.             $orderProducts = \array_merge($orderProducts$mobileOrderProducts);
  880.         }
  881.         
  882.         $payRequests = [];
  883.         $orders = [];
  884.         foreach ($orderProducts as $key => $orderProduct) {
  885.             
  886.             
  887.             $xml simplexml_load_string($orderProduct->getAddproductdata());
  888.             $totalAmount = (string) $xml->xpath('//fare_data//fare//total_amount')[0];
  889.             $transa = (string) $xml->xpath('//transaction_id')[0];
  890.             $data = (string) $xml->xpath('//booking_data')[0];
  891.             $cdata simplexml_load_string("<root>$data</root>");
  892.             $arrivalAirportCode = (string) $cdata->xpath('//arrival_airport/code')[0];
  893.             $departureAirportCode = (string) $cdata->xpath('//departure_airport/code')[0];
  894.             $departuredate = (string) $cdata->xpath('//departure_datetime')[0];
  895.             $airline = (string) $xml->xpath('//aerolinea/code')[0];
  896.             $orderProduct->Amount $totalAmount;
  897.             $orderProduct->transaction $transa;
  898.             $orderProduct->destination $departureAirportCode." - ".$arrivalAirportCode ;
  899.             $orderProduct->departureDate $departuredate;
  900.             $orderProduct->airline $airline;
  901.             
  902.             
  903.             $trace $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderTrace::class)->findByTransactionId($transa);
  904.             //valida si se generaron ambas reservas en la combinacion
  905.             $hasNullOrder false;
  906.             foreach ($trace as $item) {
  907.                 if ($item->getOrder() === null) {
  908.                     $hasNullOrder true;
  909.                     break;
  910.                 }
  911.             }
  912.              if ($hasNullOrder) {
  913.                 unset($orderProducts[$key]);
  914.                 continue; 
  915.             }
  916.             if (isset($orders[$transa])) {
  917.                 $orders[$transa] .=  "|" $orderProduct->getorder()->getId();
  918.             } else {
  919.                 $orders[$transa] = $orderProduct->getorder()->getId();
  920.             }
  921.         }
  922.     }else{
  923.         $agencyFolder $twigFolder->twigFlux();
  924.         $twigView $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-booking.html.twig');
  925.         return $this->render($twigView, ['orderProducts' => [], 'orders' => [], 'data' => 'true']);
  926.     }
  927.         $agencyFolder $twigFolder->twigFlux();
  928.         $twigView $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-booking.html.twig');
  929.         return $this->render($twigView, ['orderProducts' => $orderProducts'orders' => $orders'data' => 'true']);
  930.     }
  931.     public function editAction(Request $requestSessionInterface $sessionAviaturWebService $webServiceTwigFolder $twigFolderUserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailerAviaturErrorHandler $errorHandlerTokenStorageInterface $tokenStorageValidatorInterface $validatorParameterBagInterface $parameterBag)
  932.     {
  933.         $providerService $parameterBag->get('provider_service');
  934.         $emailNotification $parameterBag->get('email_notification');
  935.         $em $this->getDoctrine()->getManager();
  936.         $agencyFolder $twigFolder->twigFlux();
  937.         $user $tokenStorage->getToken()->getUser();
  938.         if (false === is_object($user)) {
  939.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  940.         }
  941.         $id $user->getId();
  942.         $post $request->request->get('customer_edit_form');
  943.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
  944.         $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($customer->getCountry()->getId(), ['description' => 'ASC']);
  945.         $email $customer->getEmail();
  946.         foreach ($city as $infocities) {
  947.             $idCity[] = $infocities->getCode();
  948.             $nameCity[] = $infocities->getDescription();
  949.         }
  950.         $info = ['idCity' => $idCity'nameCity' => $nameCity];
  951.         $form $this->createForm(\Aviatur\CustomerBundle\Form\CustomerEdit::class, $customer);
  952.         $method 'edition';
  953.         $date = new DateTime();
  954.         $form->handleRequest($request);
  955.         if ($form->isSubmitted()) {
  956.             $historical = (object) [
  957.                         'Firstname' => $customer->getFirstname(),
  958.                         'Documentnumber' => $customer->getDocumentnumber(),
  959.                         'DocumentType' => $customer->getDocumentType()->getCode(),
  960.                         'Lastname' => $customer->getLastname(),
  961.                         'Birthdate' => $customer->getBirthdate(),
  962.                         'Address' => $customer->getAddress(),
  963.                         'Phone' => $customer->getPhone(),
  964.                         'Cellphone' => $customer->getCellphone(),
  965.                         'Email' => $customer->getEmail(),
  966.                         'Password' => $customer->getPassword(),
  967.                         'Username' => $customer->getUsername(),
  968.                         'UsernameCanonical' => $customer->getUsernameCanonical(),
  969.                         'EmailCanonical' => $customer->getEmailCanonical(),
  970.                         'Enabled' => $customer->getEnabled(),
  971.                         'Salt' => $customer->getSalt(),
  972.                         'country_id' => $customer->getCountry()->getCode(),
  973.                         //'CreatedAt' => $customer->getCreatedAt(),
  974.                         //'UpdatedAt' => $date,
  975.                         'CustomerId' => $customer->getId(),
  976.             ];
  977.             if ($form->isValid()) {
  978.                 $userchange $this->getCustomerInfo($request$session$parameterBag$webService$twigFolder$passwordEncoder$mailer$customer$post$method$email);
  979.                 $this->historicalCustomer($historical$post$emnull$customer);
  980.                 return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_customer_edit_info', ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getId(), 'id' => $id]), 'Actualizar Datos'$userchange));
  981.             } else {
  982.                 $errors $validator->validate($customer);
  983.                 $datos = ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getCode(), 'info' => $info'form' => $form->createView(), 'errors' => $errors];
  984.                 return $this->render($twigFolder->twigExists('@AviaturTwig'.$agencyFolder.'/Customer/Customer/customer-edition.html.twig'), $datos);
  985.             }
  986.         } else {
  987.             return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-edition.html.twig'), ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getCode(), 'info' => $info'form' => $form->createView()]);
  988.         }
  989.     }
  990.     public function resetPasswordAction(Request $requestSessionInterface $sessionAviaturWebService $webServiceAviaturErrorHandler $errorHandlerTokenStorageInterface $tokenStorageTwigFolder $twigFolderUserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailerParameterBagInterface $parameterBag)
  991.     {
  992.         $providerService $parameterBag->get('provider_service');
  993.         $emailNotification $parameterBag->get('email_notification');
  994.         $post = [];
  995.         $em $this->getDoctrine()->getManager();
  996.         $agencyFolder $twigFolder->twigFlux();
  997.         $id $tokenStorage->getToken()->getUser();
  998.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
  999.         $post_form $request->request->get('customer_edit_form');
  1000.         $method 'password';
  1001.         $CivilStatus '';
  1002.         if ($customer->getCivilStatus()) {
  1003.             $CivilStatus $customer->getCivilStatus()->getId();
  1004.         }
  1005.         $date = new DateTime();
  1006.         $historical = (object) [
  1007.                     'Firstname' => $customer->getFirstname(),
  1008.                     'Documentnumber' => $customer->getDocumentnumber(),
  1009.                     'DocumentType' => $customer->getDocumentType()->getCode(),
  1010.                     'Lastname' => $customer->getLastname(),
  1011.                     'Birthdate' => $customer->getBirthdate(),
  1012.                     'Address' => $customer->getAddress(),
  1013.                     'Phone' => $customer->getPhone(),
  1014.                     'Cellphone' => $customer->getCellphone(),
  1015.                     'Email' => $customer->getEmail(),
  1016.                     'Password' => $customer->getPassword(),
  1017.                     'Username' => $customer->getUsername(),
  1018.                     'UsernameCanonical' => $customer->getUsernameCanonical(),
  1019.                     'EmailCanonical' => $customer->getEmailCanonical(),
  1020.                     'Enabled' => $customer->getEnabled(),
  1021.                     'Salt' => $customer->getSalt(),
  1022.                     'country_id' => $customer->getCountry()->getCode(),
  1023.                     //'CreatedAt' => $customer->getCreatedAt(),
  1024.                     //'UpdatedAt' => $date,
  1025.                     'CustomerId' => $customer->getId(),
  1026.         ];
  1027.         if ('POST' == $request->getMethod()) {
  1028.             $post['Firstname'] = $customer->getFirstname();
  1029.             $post['lastname'] = $customer->getLastname();
  1030.             $post['birthdate'] = $customer->getBirthdate()->format('Y-m-d');
  1031.             $post['address'] = $customer->getAddress();
  1032.             $post['phone'] = $customer->getPhone();
  1033.             $post['cellphone'] = $customer->getCellphone();
  1034.             $post['email'] = $customer->getEmail();
  1035.             $post['city'] = $customer->getCity()->getId();
  1036.             $post['country'] = $customer->getCountry()->getId();
  1037.             $post['CivilStatus'] = $CivilStatus;
  1038.             $post['aviaturclientid'] = $customer->getAviaturclientid();
  1039.             $post['DocumentNumber'] = $customer->getDocumentnumber();
  1040.             $post['genderAviatur'] = $customer->getFirstname();
  1041.             $post['acceptInformation'] = $customer->getAcceptInformation();
  1042.             $post['acceptSms'] = $customer->getAcceptSms();
  1043.             $post['password_last'] = $post_form['password_last'];
  1044.             $post['password_new'] = $post_form['password_new'];
  1045.             $post['password_repeat'] = $post_form['password_repeat'];
  1046.             $userchange $this->getCustomerInfo($request$session$parameterBag$webService$twigFolder$passwordEncoder$mailer$customer$post$method);
  1047.             $this->historicalCustomer($historical$post$emnull$customer);
  1048.             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_customer_edit_info', ['id' => $id]), 'Actualizar Datos'$userchange));
  1049.         } else {
  1050.             return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/reset-password-user.html.twig'));
  1051.         }
  1052.     }
  1053.     public function historicalCustomer($customer$post$doctrine$asessor$newData null)
  1054.     {
  1055.         $em = !empty($doctrine) ? $doctrine $this->getDoctrine()->getManager();
  1056.         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($post['country']);
  1057.         $country_id $country->getCode();
  1058.         $json '{"fields":[';
  1059.         $json_modfied_fields null;
  1060.         //Guardamos los datos antiguos en la tabla historical_customer
  1061.         $historicalCustomer = new HistoricalCustomer();
  1062.         //$historicalCustomer->setAviaturclientid($customer->getAviaturclientid());
  1063.         $historicalCustomer->setDocumentnumber($customer->Documentnumber);
  1064.         if ($customer->Documentnumber != $newData->getDocumentnumber()) {
  1065.             if (isset($json_modfied_fields)) {
  1066.                 $json_modfied_fields $json_modfied_fields.',"Documentnumber"';
  1067.             } else {
  1068.                 $json_modfied_fields '"Documentnumber"';
  1069.             }
  1070.         }
  1071.         $historicalCustomer->setDocumentTypeId($customer->DocumentType);
  1072.         if ($customer->DocumentType != $newData->getDocumentType()->getCode()) {
  1073.             if (isset($json_modfied_fields)) {
  1074.                 $json_modfied_fields $json_modfied_fields.',"DocumentType"';
  1075.             } else {
  1076.                 $json_modfied_fields '"DocumentType"';
  1077.             }
  1078.         }
  1079.         $historicalCustomer->setFirstname($customer->Firstname);
  1080.         if ($customer->Firstname != $newData->getFirstname()) {
  1081.             if (isset($json_modfied_fields)) {
  1082.                 $json_modfied_fields $json_modfied_fields.',"Firstname"';
  1083.             } else {
  1084.                 $json_modfied_fields '"Firstname"';
  1085.             }
  1086.         }
  1087.         $historicalCustomer->setLastname($customer->Lastname);
  1088.         if ($customer->Lastname != $newData->getLastname()) {
  1089.             if (isset($json_modfied_fields)) {
  1090.                 $json_modfied_fields $json_modfied_fields.',"Lastname"';
  1091.             } else {
  1092.                 $json_modfied_fields '"Lastname"';
  1093.             }
  1094.         }
  1095.         $historicalCustomer->setBirthdate($customer->Birthdate);
  1096.         if ($customer->Birthdate != $newData->getBirthdate()) {
  1097.             if (isset($json_modfied_fields)) {
  1098.                 $json_modfied_fields $json_modfied_fields.',"Birthdate"';
  1099.             } else {
  1100.                 $json_modfied_fields '"Birthdate"';
  1101.             }
  1102.         }
  1103.         $historicalCustomer->setAddress($customer->Address);
  1104.         if ($customer->Address != $newData->getAddress()) {
  1105.             if (isset($json_modfied_fields)) {
  1106.                 $json_modfied_fields $json_modfied_fields.',"Address"';
  1107.             } else {
  1108.                 $json_modfied_fields '"Address"';
  1109.             }
  1110.         }
  1111.         $historicalCustomer->setPhone($customer->Phone);
  1112.         if ($customer->Phone != $newData->getPhone()) {
  1113.             if (isset($json_modfied_fields)) {
  1114.                 $json_modfied_fields $json_modfied_fields.',"Phone"';
  1115.             } else {
  1116.                 $json_modfied_fields '"Phone"';
  1117.             }
  1118.         }
  1119.         $historicalCustomer->setCellphone($customer->Cellphone);
  1120.         if ($customer->Cellphone != $newData->getCellphone()) {
  1121.             if (isset($json_modfied_fields)) {
  1122.                 $json_modfied_fields $json_modfied_fields.',"Cellphone"';
  1123.             } else {
  1124.                 $json_modfied_fields '"Cellphone"';
  1125.             }
  1126.         }
  1127.         $historicalCustomer->setEmail($customer->Email);
  1128.         if ($customer->Email != $newData->getEmail()) {
  1129.             if (isset($json_modfied_fields)) {
  1130.                 $json_modfied_fields $json_modfied_fields.',"Email"';
  1131.             } else {
  1132.                 $json_modfied_fields '"Email"';
  1133.             }
  1134.         }
  1135.         $historicalCustomer->setPassword($customer->Password);
  1136.         if ($customer->Password != $newData->getPassword()) {
  1137.             if (isset($json_modfied_fields)) {
  1138.                 $json_modfied_fields $json_modfied_fields.',"Password"';
  1139.             } else {
  1140.                 $json_modfied_fields '"Password"';
  1141.             }
  1142.         }
  1143.         $historicalCustomer->setUsername($customer->Username);
  1144.         if ($customer->Username != $newData->getUsername()) {
  1145.             if (isset($json_modfied_fields)) {
  1146.                 $json_modfied_fields $json_modfied_fields.',"Username"';
  1147.             } else {
  1148.                 $json_modfied_fields '"Username"';
  1149.             }
  1150.         }
  1151.         $historicalCustomer->setUsernameCanonical($customer->UsernameCanonical);
  1152.         if ($customer->UsernameCanonical != $newData->getUsernameCanonical()) {
  1153.             if (isset($json_modfied_fields)) {
  1154.                 $json_modfied_fields $json_modfied_fields.',"UsernameCanonical"';
  1155.             } else {
  1156.                 $json_modfied_fields '"UsernameCanonical"';
  1157.             }
  1158.         }
  1159.         $historicalCustomer->setEmailCanonical((string) $customer->EmailCanonical);
  1160.         if ($customer->EmailCanonical != $newData->getEmailCanonical()) {
  1161.             if (isset($json_modfied_fields)) {
  1162.                 $json_modfied_fields $json_modfied_fields.',"EmailCanonical"';
  1163.             } else {
  1164.                 $json_modfied_fields '"EmailCanonical"';
  1165.             }
  1166.         }
  1167.         $historicalCustomer->setEnabled($customer->Enabled);
  1168.         $historicalCustomer->setSalt($customer->Salt);
  1169.         if ($customer->Salt != $newData->getSalt()) {
  1170.             if (isset($json_modfied_fields)) {
  1171.                 $json_modfied_fields $json_modfied_fields.',"Salt"';
  1172.             } else {
  1173.                 $json_modfied_fields '"Salt"';
  1174.             }
  1175.         }
  1176.         $historicalCustomer->setCityId($customer->country_id);
  1177.         if ($customer->country_id != $country_id) {
  1178.             if (isset($json_modfied_fields)) {
  1179.                 $json_modfied_fields $json_modfied_fields.',"country_id"';
  1180.             } else {
  1181.                 $json_modfied_fields '"country_id"';
  1182.             }
  1183.         }
  1184.         //$historicalCustomer->setCreatedAt($customer->CreatedAt);
  1185.         //$historicalCustomer->setUpdatedAt($customer->UpdatedAt);
  1186.         if (isset($asessor) && null != $asessor) {
  1187.             $historicalCustomer->setAsessorID($asessor->getid());
  1188.             $historicalCustomer->setAsessorEmail($asessor->getemail());
  1189.         }
  1190.         //$historicalCustomer->setLocale($customer->getLocale());
  1191.         //$historicalCustomer->setTimezone($customer->getTimezone());
  1192.         $historicalCustomer->setCustomerid($customer->CustomerId);
  1193.         $historicalCustomer->setIpAddres($_SERVER['REMOTE_ADDR']);
  1194.         if (isset($json_modfied_fields)) {
  1195.             $json $json.$json_modfied_fields.']}';
  1196.             $historicalCustomer->setModifiedfields($json);
  1197. //        var_dump($json);die;
  1198.             try {
  1199. //            var_dump($historicalCustomer);die;
  1200.                 $em->persist($historicalCustomer);
  1201.                 $em->flush();
  1202.             } catch (\Exception $e) {
  1203.             }
  1204.         }
  1205.         //////////////////////////////////////////////////////////////
  1206.     }
  1207.     public function getCustomerInfo(Request $requestSessionInterface $sessionParameterBagInterface $parameterBagAviaturWebService $webServiceTwigFolder $twigFolderUserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer$customer$post$method$email null$doctrine null$asessor null)
  1208.     {
  1209.         $em $this->getDoctrine()->getManager();
  1210.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1211.         $providerService $parameterBag->get('provider_service');
  1212.         $emailNotification $parameterBag->get('email_notification');
  1213.         $passwordEncode null;
  1214.         $passwordUser null;
  1215.         $newPassword null;
  1216.         $repeatPassword null;
  1217.         $mensaje null;
  1218.         //var_dump($customer);die();
  1219.         $em = !empty($doctrine) ? $doctrine $this->getDoctrine()->getManager();
  1220.         $fullRequest $request;
  1221.         $agencyFolder $twigFolder->twigFlux();
  1222.         //Get city code in database clientes web
  1223.         $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneById($post['city']);
  1224.         $city_id $city->getCode();
  1225.         $Lastcustomer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($post['email']);
  1226.         //Get country code in database clientes web
  1227.         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($post['country']);
  1228.         $country_id $country->getCode();
  1229.         $customer->setFirstname($post['Firstname']);
  1230.         $customer->setLastname($post['lastname']);
  1231.         $customer->setBirthdate(new \DateTime($post['birthdate']));
  1232.         $customer->setAddress($post['address']);
  1233.         $customer->setPhone($post['phone']);
  1234.         $customer->setCellphone($post['cellphone']);
  1235.         //$customer->setEmail($post['email']);
  1236.         //$customer->setUsername($post['email']);
  1237.         //Get document id code in database clientes web
  1238.         $document $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneById($customer->getDocumentType()->getId());
  1239.         $document_type_id $document->getCode();
  1240.         if (4877 == $document_type_id || 11 == $document_type_id) {
  1241.             // if document_type_id == NIT or NIT international
  1242.             $person_type_id 7;
  1243.         } else {
  1244.             $person_type_id 8;
  1245.         }
  1246.         //Get civil status code in database clientes web
  1247.         $civilStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneById($post['CivilStatus']);
  1248.         if (isset($civilStatus)) {
  1249.             $marital_status_id $civilStatus->getCode();
  1250.         } else {
  1251.             $marital_status_id '';
  1252.         }
  1253.         $client_id $post['aviaturclientid'];
  1254.         $document_number $post['DocumentNumber'];
  1255.         if ('password' == $method) {
  1256.             $passwordEncode $passwordEncoder->encodePassword($customer$post['password_last']);
  1257.             $newPassword $post['password_new'];
  1258.             $repeatPassword $post['password_repeat'];
  1259.             $passwordUser $customer->getPassword();
  1260.             $password $passwordEncoder->encodePassword($customer$post['password_new']);
  1261.         } else {
  1262.             $password $customer->getPassword();
  1263.         }
  1264.         $corporate_name $customer->getFirstname();
  1265.         $gender $post['genderAviatur'];
  1266.         if (== $gender) {
  1267.             $gender_id 334;
  1268.         } else {
  1269.             $gender_id 335;
  1270.         }
  1271.         $state_id 0;
  1272.         $season_id 1;
  1273.         $sms_frequency_id $customer->getFrecuencySms();
  1274.         $info = [
  1275.             'client_id' => $client_id,
  1276.             'person_type_id' => $person_type_id,
  1277.             'corporate_name' => $post['Firstname'],
  1278.             'corporate_id' => $post['DocumentNumber'],
  1279.             'name' => $post['Firstname'],
  1280.             'last_name' => $post['lastname'],
  1281.             'document_type_id' => $document_type_id,
  1282.             'document_number' => $document_number,
  1283.             'gender_id' => $gender_id,
  1284.             'marital_status_id' => $marital_status_id,
  1285.             'birth_date' => $post['birthdate'],
  1286.             'country_id' => $country_id,
  1287.             'state_id' => $state_id,
  1288.             'city_id' => $city_id,
  1289.             'address' => $post['address'],
  1290.             'phone_number' => $post['phone'],
  1291.             'mobile_phone_number' => $post['cellphone'],
  1292.             'password' => $password,
  1293.             'season_id' => '',
  1294.             'class_trip_id' => 0,
  1295.             'accept_information' => $post['acceptInformation'],
  1296.             'accept_sms' => $post['acceptSms'],
  1297.             'status_id' => 1,
  1298.         ];
  1299.         if ($post['email'] != $customer->getUsername()) {
  1300.             $info['email'] = $customer->getUsername();
  1301.         } else {
  1302.             $info['email'] = $post['email'];
  1303.         }
  1304.         //Consulting Id user to modify
  1305.         $customerModel = new CustomerModel();
  1306.         $xmlRequest $customerModel->getXmlEditUser($info2);
  1307.         //Modify User into database
  1308.         if ('password' == $method) {
  1309.             if ($passwordEncode != $passwordUser) {
  1310.                 $mensaje 'El Campo Contraseña Anterior no corresponse a la asignada al usuario '.$customer->getEmail();
  1311.             } elseif ($newPassword != $repeatPassword) {
  1312.                 $mensaje 'Los Campos Ingresados No son Iguales, por favor Validar.';
  1313.             } else {
  1314.                 $customer->setPassword($password);
  1315.                 //$em->persist($customer);
  1316.                 $em->flush();
  1317.                 $mensaje 'La Contraseña del usuario '.$customer->getEmail().' se ha Modificado Correctamente';
  1318.                 $response $webService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  1319.             }
  1320.         } else {
  1321.             if ((is_countable($Lastcustomer) ? count($Lastcustomer) : 0) > && $email != $Lastcustomer->getEmail()) {
  1322.                 $mensaje 'El Correo '.$customer->getEmail().' ya se encuentra registrado con otro Usuario';
  1323.             } else {
  1324.                 try {
  1325.                     if ($post['email'] != $customer->getUsername()) {
  1326.                         $customer->setEmail($post['email']);
  1327.                         $customer->setUsername($post['email']);
  1328.                         $customer->setEmailCanonical($post['email']);
  1329.                         $tokenTemp bin2hex(random_bytes(64));
  1330.                         $customer->setTempEmail($post['email']);
  1331.                         $customer->setTempEmailToken($tokenTemp);
  1332.                         $customer->setEmail($email);
  1333.                         $customer->setUsername($email);
  1334.                         if ($agency->getAssetsFolder() == 'octopus') {
  1335.                             $messageEmail = (new \Swift_Message())
  1336.                                 ->setContentType('text/html')
  1337.                                 ->setFrom($session->get('emailNoReply'))
  1338.                                 ->setTo($email)
  1339.                                 ->setSubject('Octopus: Confirmación de Cambios en Tu Correo Electrónico')
  1340.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/Customer/customer-edition-email.html.twig'), [
  1341.                                     'nameCustomer' => $post['Firstname'],
  1342.                                     'tokenTemp' => $tokenTemp,
  1343.                                     'idCustomer' => $customer->getId(),
  1344.                                 ]), 'text/html');
  1345.                         } else {
  1346.                             $messageEmail = (new \Swift_Message())
  1347.                                 ->setContentType('text/html')
  1348.                                 ->setFrom($session->get('emailNoReply'))
  1349.                                 ->setTo($post['email'])
  1350.                                 ->setSubject('Cambio de email')
  1351.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/Customer/customer-edition-email.html.twig'), [
  1352.                                     'nameCustomer' => $post['Firstname'],
  1353.                                     'tokenTemp' => $tokenTemp,
  1354.                                     'idCustomer' => $customer->getId(),
  1355.                                 ]), 'text/html');
  1356.                         }
  1357.                         $em->persist($customer);
  1358.                         $em->flush();
  1359.                         $mailer->send($messageEmail);
  1360.                         $mensaje 'Hemos enviado un mensaje a su correo actual, por favor confírmenos el cambio.';
  1361.                     } elseif ($post['email'] == $customer->getUsername()) {
  1362.                         $customer->setEmail($post['email']);
  1363.                         $customer->setUsername($post['email']);
  1364.                         $customer->setEmailCanonical($post['email']);
  1365.                         $tokenTemp bin2hex(random_bytes(64));
  1366.                         $customer->setTempEmail($post['email']);
  1367.                         $customer->setTempEmailToken($tokenTemp);
  1368.                         $customer->setEmail($email);
  1369.                         $customer->setUsername($email);
  1370.                         if ($agency->getAssetsFolder() == 'octopus') {
  1371.                             $mensaje 'Los datos del agente ' $customer->getFirstname() . ' ' $customer->getlastname() . ' se modificaron correctamente';
  1372.                             $messageEmail = (new \Swift_Message())
  1373.                                 ->setContentType('text/html')
  1374.                                 ->setFrom($session->get('emailNoReply'))
  1375.                                 ->setTo($email)
  1376.                                 ->setSubject('Notificación de Verificación de Datos en Octopus')
  1377.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/Customer/customer-edition-data-notification.html.twig'), [
  1378.                                     'nameCustomer' => $post['Firstname'],
  1379.                                     'tokenTemp' => $tokenTemp,
  1380.                                     'idCustomer' => $customer->getId(),
  1381.                                 ]), 'text/html');
  1382.                         } else {
  1383.                             $mensaje 'Los datos del agente ' $customer->getFirstname() . ' ' $customer->getlastname() . ' se modificaron correctamente';
  1384.                             $messageEmail = (new \Swift_Message())
  1385.                                 ->setContentType('text/html')
  1386.                                 ->setFrom($session->get('emailNoReply'))
  1387.                                 ->setTo($post['email'])
  1388.                                 ->setSubject('Notificación')
  1389.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/Customer/customer-edition-email.html.twig'), [
  1390.                                     'nameCustomer' => $post['Firstname'],
  1391.                                     'tokenTemp' => $tokenTemp,
  1392.                                     'idCustomer' => $customer->getId(),
  1393.                                 ]), 'text/html');
  1394.                         }
  1395.                         $mailer->send($messageEmail);
  1396.                         $em->persist($customer);
  1397.                         $em->flush();
  1398.                     }
  1399.                     if (!isset($doctrine)) {
  1400.                         $response $webService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  1401.                     }
  1402.                 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
  1403.                     $mensaje 'El Correo '.$customer->getEmail().' ya se encuentra registrado con otro Usuario';
  1404.                     //$mensaje = 'El Documento'.$customer->getDocumentType().' :'.$customer->getDocumentnumber().' ya se encuentra registrado con otro Usuario';
  1405.                 } catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
  1406.                     $mensaje 'Información incompleta o inconsistente: '.$e->getMessage();
  1407.                 } catch (\Exception $e) {
  1408.                     $mensaje 'Se produjo un error al editar los datos, Por favor contactate con nosotros para mejor información.';
  1409.                 }
  1410.             }
  1411.         }
  1412.         if (!isset($response)) {
  1413.             $mensaje $mensaje;
  1414.         } elseif (('FALLO' == $response->RESULTADO)) {
  1415.             $mailInfo print_r($infotrue).'<br>'.print_r($responsetrue);
  1416.             $message = (new \Swift_Message())
  1417.                     ->setContentType('text/html')
  1418.                     ->setFrom($session->get('emailNoReply'))
  1419.                     ->setTo('b_botina@aviatur.com'$emailNotification 'negocioselectronicos@aviatur.com.co')
  1420.                     ->setSubject('Error Al Modificar Usuario en Base de Datos Clientes Web')
  1421.                     ->setBody($mailInfo);
  1422.             $mailer->send($message);
  1423.             $mensaje 'Se produjo un error al editar los datos, Por Favor Contactate con Nosotros';
  1424.         } /* else {
  1425.           $em->flush();
  1426.           } */
  1427.         return $mensaje;
  1428.     }
  1429.     public function setNewEmailAction(Request $requestSessionInterface $sessionParameterBagInterface $parameterBagAviaturWebService $webServiceAviaturErrorHandler $errorHandler, \Swift_Mailer $mailer$customerId$token)
  1430.     {
  1431.         $providerService $parameterBag->get('provider_service');
  1432.         $emailNotification $parameterBag->get('email_notification');
  1433.         $em $this->getDoctrine()->getManager();
  1434.         $fullRequest $request;
  1435.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneById($customerId);
  1436.         //var_dump($customer);die();
  1437.         if (!$customer) {
  1438.             return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), '''Ha ocurrido un error'));
  1439.         }
  1440.         if ($customerId && $token) {
  1441.             if (!is_null($customer->getTempEmailToken()) && !is_null($customer->getTempEmail())) {
  1442.                 if ($customerId == $customer->getId() && $token == $customer->getTempEmailToken()) {
  1443.                     $null null;
  1444.                     $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneById($customer->getCity()->getId());
  1445.                     $city_id $city->getCode();
  1446.                     //Get country code in database clientes web
  1447.                     $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($customer->getCountry()->getId());
  1448.                     $country_id $country->getCode();
  1449.                     $document $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneById($customer->getDocumentType()->getId());
  1450.                     $document_type_id $document->getCode();
  1451.                     if (4877 == $document_type_id || 11 == $document_type_id) {
  1452.                         // if document_type_id == NIT or NIT international
  1453.                         $person_type_id 7;
  1454.                     } else {
  1455.                         $person_type_id 8;
  1456.                     }
  1457.                     //Get civil status code in database clientes web
  1458.                     $civilStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneById($customer->getCivilStatus());
  1459.                     if (isset($civilStatus)) {
  1460.                         $marital_status_id $civilStatus->getCode();
  1461.                     } else {
  1462.                         $marital_status_id '';
  1463.                     }
  1464.                     //$document_number = $post['DocumentNumber'];
  1465.                     $password $customer->getPassword();
  1466.                     $corporate_name $customer->getFirstname();
  1467.                     $gender $customer->getGenderAviatur()->getCode();
  1468.                     if (== $gender) {
  1469.                         $gender_id 334;
  1470.                     } else {
  1471.                         $gender_id 335;
  1472.                     }
  1473.                     $state_id 0;
  1474.                     $season_id 1;
  1475.                     $sms_frequency_id $customer->getFrecuencySms();
  1476.                     $info = [
  1477.                         'client_id' => $customer->getAviaturclientid(),
  1478.                         'person_type_id' => $person_type_id,
  1479.                         'corporate_name' => $customer->getFirstname(),
  1480.                         'corporate_id' => $customer->getDocumentnumber(),
  1481.                         'name' => $customer->getFirstname(),
  1482.                         'last_name' => $customer->getLastname(),
  1483.                         'document_type_id' => $document_type_id,
  1484.                         'document_number' => $customer->getDocumentnumber(),
  1485.                         'gender_id' => $gender_id,
  1486.                         'marital_status_id' => $marital_status_id,
  1487.                         'birth_date' => $customer->getBirthdate()->format('Y-m-d'),
  1488.                         'country_id' => $country_id,
  1489.                         'state_id' => $state_id,
  1490.                         'city_id' => $city_id,
  1491.                         'address' => $customer->getAddress(),
  1492.                         'phone_number' => $customer->getPhone(),
  1493.                         'mobile_phone_number' => $customer->getCellphone(),
  1494.                         'password' => $customer->getPassword(),
  1495.                         'season_id' => '',
  1496.                         'class_trip_id' => 0,
  1497.                         'accept_information' => $customer->getAcceptinformation(),
  1498.                         'accept_sms' => $customer->getAcceptsms(),
  1499.                         'status_id' => 1,
  1500.                         'email' => $customer->getTempEmail(),
  1501.                     ];
  1502.                     $customerModel = new CustomerModel();
  1503.                     $xmlRequest $customerModel->getXmlEditUser($info2);
  1504.                     $response $webService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  1505.                     if (!isset($response)) {
  1506.                         $mensaje $mensaje;
  1507.                     } elseif (('FALLO' == $response->RESULTADO)) {
  1508.                         $mailInfo print_r($infotrue).'<br>'.print_r($responsetrue);
  1509.                         $message = (new \Swift_Message())
  1510.                                 ->setContentType('text/html')
  1511.                                 ->setFrom($session->get('emailNoReply'))
  1512.                                 ->setTo('b_botina@aviatur.com'$emailNotification 'negocioselectronicos@aviatur.com.co')
  1513.                                 ->setSubject('Error Al Modificar Usuario en Base de Datos Clientes Web')
  1514.                                 ->setBody($mailInfo);
  1515.                         $mailer->send($message);
  1516.                         $mensaje 'Se produjo un error al editar los datos, Por Favor Contactate con Nosotros';
  1517.                     }
  1518.                     $customer->setEmail($customer->getTempEmail());
  1519.                     $customer->setUsername($customer->getTempEmail());
  1520.                     $customer->setEmailCanonical($customer->getTempEmail());
  1521.                     $customer->setTempEmailToken($null);
  1522.                     $customer->setTempEmail($null);
  1523.                     $em->persist($customer);
  1524.                     $em->flush();
  1525.                     return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Felicidades''Cambio satifactorio de email'));
  1526.                 } else {
  1527.                     return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error''Ha ocurrido un error'));
  1528.                 }
  1529.             } else {
  1530.                 return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error''Ha ocurrido un error'));
  1531.             }
  1532.         } else {
  1533.             return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error''Direccion url incorrecta'));
  1534.         }
  1535.     }
  1536.     public function getpaymentMethodsSavedAction(TwigFolder $twigFolderCustomerMethodPaymentService $methodPaymentServiceAviaturLoginService $loginService)
  1537.     {
  1538.         $em $this->getDoctrine()->getManager();
  1539.         $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1540.         $infoSaved = [];
  1541.         if (false !== $loginService->validActiveSession()) {
  1542.             $customer $this->getUser();
  1543.             $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerfalse);
  1544.             if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
  1545.                 foreach ($infoMethodPaymentByClient['info'] as $key => $value) {
  1546.                     $infoSaved['info'][] = [substr($key02), substr($key24)];
  1547.                 }
  1548.             }
  1549.         }
  1550.         $infoSaved['doc_type'] = $typeDocument;
  1551.         $newsletter = new Newsletter();
  1552.         $newsletterForm $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
  1553.         $infoSaved['newsletter_form'] = $newsletterForm->createView();
  1554.         $agencyFolder $twigFolder->twigFlux();
  1555.         $twigView $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-payments-saved.html.twig');
  1556.         return $this->render($twigView$infoSaved);
  1557.     }
  1558.     public function saveNewCardAction(Request $requestTokenizerService $tokenizerServiceTokenStorageInterface $tokenStorage)
  1559.     {
  1560.         if ($request) {
  1561.             $em $this->getDoctrine()->getManager();
  1562.             $customer $tokenStorage->getToken()->getUser();
  1563.             $cardNumToken $tokenizerService->getToken($request->request->get('cardNum'));
  1564.             $fecha = new \DateTime();
  1565.             $franchise $request->request->get('franqui');
  1566.             $numcard = \substr($request->request->get('cardNum'), -44);
  1567.             $new_method_payment = [
  1568.                 $franchise.$numcard => [
  1569.                     'token' => $cardNumToken//['card_num'],
  1570.                     'firstname' => $request->request->get('nombreCard'),
  1571.                     'lastname' => $request->request->get('apellidoCard'),
  1572.                     'datevig' => $request->request->get('cardExp'),
  1573.                     'datecreation' => $fecha->format('Y-m-d H:i:s'),
  1574.                     'typeDocument' => $request->request->get('docType'),
  1575.                     'documentNumber' => $request->request->get('docNum'),
  1576.                     'status' => 'NOTVERIFIED',
  1577.                 ],
  1578.             ];
  1579.             $paymentMethodsCustomer $em->getRepository(\Aviatur\PaymentBundle\Entity\PaymentMethodCustomer::class)->findBy(['customer' => $customer]);
  1580.             if (count($paymentMethodsCustomer) > 0) {
  1581.                 $actualInfo json_decode($paymentMethodsCustomer[0]->getInfoPaymentMethod(), true);
  1582.                 $preExist array_intersect_key($new_method_payment$actualInfo);
  1583.                 if (count($preExist) > 0) {
  1584.                     foreach ($preExist as $key => $value) {
  1585.                         $actualInfo[$key]['status'] = 'REPLACED';
  1586.                         $actualInfo[$key.'_'.$fecha->format('YmdHis')] = $actualInfo[$key];
  1587.                         unset($actualInfo[$key]);
  1588.                     }
  1589.                 }
  1590.                 $newInfo array_merge($actualInfo$new_method_payment);
  1591.                 $paymentMethodsCustomer[0]->setInfoPaymentMethod(json_encode($newInfo));
  1592.             } else {
  1593.                 $newMethodObject = new PaymentMethodCustomer();
  1594.                 $newMethodObject->setCustomer($customer);
  1595.                 $newMethodObject->setInfoPaymentMethod(json_encode($new_method_payment));
  1596.                 $newMethodObject->setIsactive(true);
  1597.                 $em->persist($newMethodObject);
  1598.             }
  1599.             $em->flush();
  1600.             return $this->json(['status' => 'success']);
  1601.         }
  1602.     }
  1603.     public function setMethodsByCustomer($customer$infoCard)
  1604.     {
  1605.         $fecha = new \DateTime();
  1606.         $franchise $infoCard['franqui'];
  1607.         $numcard = \substr($infoCard['cardNum'], -44);
  1608.         $new_method_payment = [
  1609.             $franchise.$numcard => [
  1610.                 'token' => $infoCard['cardNum'], //['card_num'],
  1611.                 'firstname' => $infoCard['nombreCard'],
  1612.                 'lastname' => $infoCard['apellidoCard'],
  1613.                 'datevig' => $infoCard['cardExp'],
  1614.                 'datecreation' => $fecha->format('Y-m-d H:i:s'),
  1615.                 'typeDocument' => $infoCard['docType'],
  1616.                 'documentNumber' => $infoCard['docNum'],
  1617.                 'status' => 'NOTVERIFIED',
  1618.             ],
  1619.         ];
  1620.         $paymentMethodsCustomer $this->em->getRepository(\Aviatur\PaymentBundle\Entity\PaymentMethodCustomer::class)->findBy(['customer' => $customer]);
  1621.         if ((is_countable($paymentMethodsCustomer) ? count($paymentMethodsCustomer) : 0) > 0) {
  1622.             $actualInfo json_decode($paymentMethodsCustomer[0]->getInfoPaymentMethod(), true);
  1623.             $preExist array_intersect_key($new_method_payment$actualInfo);
  1624.             if (count($preExist) > 0) {
  1625.                 foreach ($preExist as $key => $value) {
  1626.                     $actualInfo[$key]['status'] = 'REPLACED';
  1627.                     $actualInfo[$key.'_'.$fecha->format('YmdHis')] = $actualInfo[$key];
  1628.                     unset($actualInfo[$key]);
  1629.                 }
  1630.             }
  1631.             $newInfo array_merge($actualInfo$new_method_payment);
  1632.             $paymentMethodsCustomer[0]->setInfoPaymentMethod(json_encode($newInfo));
  1633.         } else {
  1634.             $newMethodObject = new PaymentMethodCustomer();
  1635.             $newMethodObject->setCustomer($customer);
  1636.             $newMethodObject->setInfoPaymentMethod(json_encode($new_method_payment));
  1637.             $newMethodObject->setIsactive(true);
  1638.             $this->em->persist($newMethodObject);
  1639.         }
  1640.         $this->em->flush();
  1641.     }
  1642.     public function deletePaymentsSavedAction(Request $requestCustomerMethodPaymentService $methodPaymentServiceAviaturErrorHandler $errorHandler)
  1643.     {
  1644.         $cardKey $request->request->get('keycardtodelete');
  1645.         $customer $this->getUser();
  1646.         $methodPaymentService->deleteMethodsByCustomer($customer$cardKey);
  1647.         $redirectRoute 'aviatur_customer_show_saved_pay_info';
  1648.         return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl($redirectRoute), 'Información actualizada''Se actualizaron los medios de pago almacenados'));
  1649.     }
  1650.     public function deleteCardSavedAjaxAction(Request $requestCustomerMethodPaymentService $methodPaymentService)
  1651.     {
  1652.         $cardKey $request->request->get('key');
  1653.         $customer $this->getUser();
  1654.         $methodPaymentService->deleteMethodsByCustomer($customer$cardKey);
  1655.         return $this->json(['status' => 'success']);
  1656.     }
  1657.     public function billingViewAction(TwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  1658.     {
  1659.         $agencyFolder $twigFolder->twigFlux();
  1660.         $em $this->getDoctrine()->getManager();
  1661.         $userLogged $tokenStorage->getToken()->getUser()->getId();
  1662.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  1663.         //var_dump($billingList);die();
  1664.         $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1665.         if ($billingList) {
  1666.             $data = [];
  1667.             $count 0;
  1668.             foreach ($billingList as $billings) {
  1669.                 if ('ACTIVE' == $billings->getStatus()) {
  1670.                     $data[$count]['id'] = $billings->getId();
  1671.                     $data[$count]['customerId'] = $userLogged;
  1672.                     $data[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  1673.                     $data[$count]['documentNumber'] = $billings->getDocumentnumber();
  1674.                     $data[$count]['firstname'] = $billings->getFirstname();
  1675.                     $data[$count]['lastname'] = $billings->getLastname();
  1676.                     $data[$count]['email'] = $billings->getEmail();
  1677.                     $data[$count]['address'] = $billings->getAddress();
  1678.                     $data[$count]['phone'] = $billings->getPhone();
  1679.                     $data[$count]['country'] = ((null != $billings->getCountry()) && ('' != $billings->getCountry())) ? $billings->getCountry()->getIataCode() : null;
  1680.                     $data[$count]['countryname'] = ((null != $billings->getCountry()) && ('' != $billings->getCountry())) ? \ucwords(\mb_strtolower($billings->getCountry()->getDescription())).' ('.$billings->getCountry()->getIataCode().')' null;
  1681.                     $data[$count]['city'] = $billings->getCity()->getIataCode();
  1682.                     $data[$count]['cityname'] = ((null != $billings->getCity()) && ('' != $billings->getCity())) ? \ucwords(\mb_strtolower($billings->getCity()->getDescription())).' ('.$billings->getCity()->getIataCode().')' null;
  1683.                     ++$count;
  1684.                 }
  1685.             }
  1686.         } else {
  1687.             $data null;
  1688.         }
  1689.         /* $country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->createQueryBuilder('u')->where('u.languagecode = :languagecode')->setParameter('languagecode', 'es-ES')->orderBy('u.description', 'ASC')->getQuery()->getResult();
  1690.           var_dump($country);die; */
  1691.         /* $city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($customer->getCountry()->getId(), array('description' => 'ASC'));
  1692.           foreach ($city as $infocities) {
  1693.           $idCity[] = $infocities->getCode();
  1694.           $nameCity[] = $infocities->getDescription();
  1695.           }
  1696.           $info = array('idCity' => $idCity, 'nameCity' => $nameCity); */
  1697.         $twigView $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-billing-view.html.twig');
  1698.         return $this->render($twigView, ['billings' => $data'doc_type' => $typeDocument]);
  1699.     }
  1700.     public function billingListAction(TokenStorageInterface $tokenStorage)
  1701.     {
  1702.         $em $this->getDoctrine()->getManager();
  1703.         $userLogged $tokenStorage->getToken()->getUser()->getId();
  1704.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  1705.         if ($billingList) {
  1706.             $data = [];
  1707.             $count 0;
  1708.             foreach ($billingList as $billings) {
  1709.                 if ('ACTIVE' == $billings->getStatus()) {
  1710.                     $data[$count]['id'] = $billings->getId();
  1711.                     $data[$count]['customerId'] = $userLogged;
  1712.                     $data[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  1713.                     $data[$count]['documentNumber'] = $billings->getDocumentnumber();
  1714.                     $data[$count]['firstname'] = $billings->getFirstname();
  1715.                     $data[$count]['lastname'] = $billings->getLastname();
  1716.                     $data[$count]['email'] = $billings->getEmail();
  1717.                     $data[$count]['address'] = $billings->getAddress();
  1718.                     $data[$count]['phone'] = $billings->getPhone();
  1719.                     ++$count;
  1720.                 }
  1721.             }
  1722.         } else {
  1723.             $data null;
  1724.         }
  1725.         return $this->json($data);
  1726.     }
  1727.     public function billingDeleteAction(Request $requestTokenStorageInterface $tokenStorage)
  1728.     {
  1729.         $idBilling $request->request->get('idBilling');
  1730.         $em $this->getDoctrine()->getManager();
  1731.         //$userLogged = $tokenStorage->getToken()->getUser()->getId();
  1732.         $billing $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->find($idBilling);
  1733.         $billing->setStatus('ERASED');
  1734.         $em->flush();
  1735.         return $this->json(['status' => 'success']);
  1736.     }
  1737.     public function billingAddOrEditAction(Request $requestTokenStorageInterface $tokenStorage)
  1738.     {
  1739.         $em $this->getDoctrine()->getManager();
  1740.         $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findByExternalcode($request->request->get('doc_type'));
  1741.         $userLogged $tokenStorage->getToken()->getUser();
  1742.         if ($request) {
  1743.             $fecha = new \DateTime();
  1744.             if ('' != $request->request->get('id')) {
  1745.                 $billing $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->find($request->request->get('id'));
  1746.                 if (!$billing) {
  1747.                     return $this->json([
  1748.                                 'status' => 'error',
  1749.                                 'message' => 'Usuario no existe',
  1750.                     ]);
  1751.                 }
  1752.                 $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($request->request->get('country'));
  1753.                 if (!$dataCountry) {
  1754.                     return $this->json([
  1755.                                 'status' => 'error',
  1756.                                 'message' => 'País no existe',
  1757.                     ]);
  1758.                 }
  1759.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($request->request->get('city'));
  1760.                 if (!$dataCountry) {
  1761.                     return $this->json([
  1762.                                 'status' => 'error',
  1763.                                 'message' => 'Ciudad no existe',
  1764.                     ]);
  1765.                 }
  1766.                 $billing->setDocumentnumber($request->request->get('doc_num'));
  1767.                 $billing->setDocumentType($documentType[0]);
  1768.                 $billing->setCustomer($userLogged);
  1769.                 $billing->setFirstname($request->request->get('first-name'));
  1770.                 $billing->setLastname($request->request->get('last-name'));
  1771.                 $billing->setEmail($request->request->get('email'));
  1772.                 $billing->setAddress($request->request->get('address'));
  1773.                 $billing->setPhone($request->request->get('phone'));
  1774.                 $billing->setCountry($dataCountry);
  1775.                 $billing->setCity($dataCity);
  1776.                 $billing->setUpdated($fecha->format('Y-m-d H:i:s'));
  1777.             } else {
  1778.                 $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($request->request->get('country'));
  1779.                 if (!$dataCountry) {
  1780.                     return $this->json([
  1781.                                 'status' => 'error',
  1782.                                 'message' => 'País no existe',
  1783.                     ]);
  1784.                 }
  1785.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($request->request->get('city'));
  1786.                 if (!$dataCountry) {
  1787.                     return $this->json([
  1788.                                 'status' => 'error',
  1789.                                 'message' => 'Ciudad no existe',
  1790.                     ]);
  1791.                 }
  1792.                 $billing = new CustomerBillingList();
  1793.                 $billing->setDocumentnumber($request->request->get('doc_num'));
  1794.                 $billing->setDocumentType($documentType[0]);
  1795.                 $billing->setCustomer($userLogged);
  1796.                 $billing->setFirstname($request->request->get('first-name'));
  1797.                 $billing->setLastname($request->request->get('last-name'));
  1798.                 $billing->setEmail($request->request->get('email'));
  1799.                 $billing->setAddress($request->request->get('address'));
  1800.                 $billing->setPhone($request->request->get('phone'));
  1801.                 $billing->setCountry($dataCountry);
  1802.                 $billing->setCity($dataCity);
  1803.                 $billing->setStatus('ACTIVE');
  1804.                 $billing->setCreated($fecha->format('Y-m-d H:i:s'));
  1805.                 $billing->setUpdated($fecha->format('Y-m-d H:i:s'));
  1806.                 $em->persist($billing);
  1807.             }
  1808.             $em->flush();
  1809.             return $this->json([
  1810.                         'status' => 'success',
  1811.                         'message' => 'Registro creado',
  1812.             ]);
  1813.         } else {
  1814.             return $this->json([
  1815.                         'status' => 'error',
  1816.                         'message' => 'Ha ocurrido un error',
  1817.             ]);
  1818.         }
  1819.     }
  1820.     public function getCitiesAjaxAction(Request $request)
  1821.     {
  1822.         $data = [];
  1823.         $em $this->getDoctrine()->getManager();
  1824.         $term $request->request->get('term') ?: null;
  1825.         if (!is_null($term)) {
  1826.             $em $this->getDoctrine()->getManager();
  1827.             $json_template '<value>:<label>-';
  1828.             $countries $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findByOrWithSingleValue(['iatacode''description'], $term);
  1829.             $json = [];
  1830.             if ($countries) {
  1831.                 $data = [];
  1832.                 $count 0;
  1833.                 foreach ($countries as $country) {
  1834.                     $data[$count]['id'] = $count;
  1835.                     $data[$count]['code'] = $country['iata'];
  1836.                     $data[$count]['label'] = ucwords(mb_strtolower($country['description']));
  1837.                     /* $arraytmp = array(
  1838.                       'description' => ucwords(mb_strtolower($country['description'])),
  1839.                       'iata' => $country['iata']
  1840.                       );
  1841.                       array_push($json, $arraytmp); */
  1842.                 }
  1843.             } else {
  1844.                 $json['error'] = 'No hay Resultados';
  1845.             }
  1846.             return $this->json($data);
  1847.         } else {
  1848.             return $this->json(['error' => 'Termino de consulta invalido']);
  1849.         }
  1850.         /* $city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry("165", array('description' => 'ASC'));
  1851.           $data = [];
  1852.           $count = 0;
  1853.           foreach ($city as $infocities) {
  1854.           $data[$count]['id'] = $infocities->getId();
  1855.           $data[$count]['code'] = $infocities->getCode();
  1856.           $data[$count]['name'] = $infocities->getDescription();
  1857.           $count++;
  1858.           }
  1859.           return $this->json(array(
  1860.           "status" => "success",
  1861.           "data" => array($data)
  1862.           )); */
  1863.     }
  1864.     public function searchCountryAction(Request $request)
  1865.     {
  1866.         $data json_decode($request->getContent());
  1867.         $term $request->request->get('term') ?: null;
  1868.         if (!is_null($term)) {
  1869.             $em $this->getDoctrine()->getManager();
  1870.             $json_template '<value>:<label>-';
  1871.             $countries $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findByOrWithSingleValue(['iatacode''description'], $term);
  1872.             $json = [];
  1873.             if ($countries) {
  1874.                 foreach ($countries as $country) {
  1875.                     $arraytmp = [
  1876.                         'description' => ucwords(mb_strtolower($country['description'])),
  1877.                         'iata' => $country['iata'],
  1878.                     ];
  1879.                     array_push($json$arraytmp);
  1880.                 }
  1881.             } else {
  1882.                 $json['error'] = 'No hay Resultados';
  1883.             }
  1884.             return $this->json(['country' => $json]);
  1885.         } else {
  1886.             return $this->json(['error' => 'Termino de consulta invalido']);
  1887.         }
  1888.     }
  1889.     public function getCitiesAction(Request $requestTwigFolder $twigFolder)
  1890.     {
  1891.         $em $this->getDoctrine()->getManager();
  1892.         $agencyFolder $twigFolder->twigFlux();
  1893.         $country $request->request->get('country');
  1894.         $id $request->request->get('id');
  1895.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
  1896.         $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($country, ['description' => 'ASC']);
  1897.         foreach ($city as $infocities) {
  1898.             $idCity[] = $infocities->getId();
  1899.             $iataCity[] = $infocities->getIatacode();
  1900.             $nameCity[] = $infocities->getDescription();
  1901.         }
  1902.         $info = ['idCity' => $idCity'iataCity' => $iataCity'nameCity' => $nameCity];
  1903.         return $this->json($info);
  1904.     }
  1905.     public function frozenRateAction(TwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  1906.     {
  1907.         $agencyFolder $twigFolder->twigFlux();
  1908.         $em $this->getDoctrine()->getManager();
  1909.         $freezeData $em->getRepository(\Aviatur\RestBundle\Entity\HopperFreeze::class)->findByCustomerid($tokenStorage->getToken()->getUser()->getId());
  1910.         if (!$freezeData) {
  1911.             return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/frozen-rate.html.twig'), ['status' => false'data' => null'message' => 'No tiene tarifas congeladas']);
  1912.         }
  1913.         $arrayFreeze = [];
  1914.         for ($i 0$i < (is_countable($freezeData) ? count($freezeData) : 0); ++$i) {
  1915.             // Obtener la informaqción de vuelo en formato JSON
  1916.             $infoFlight json_decode($freezeData[$i]->getIdRouteFlight()->getInfo());
  1917.             // Obtener la información de ida y regreso en formato JSON
  1918.             $infoIda json_decode($infoFlight->selection[0]);
  1919.             $infoRegreso null;
  1920.             $infoRegresoDate null;
  1921.             $infoRegreso2 null;
  1922.             setlocale(LC_TIME'spanish');
  1923.             if ((is_countable($infoFlight->selection) ? count($infoFlight->selection) : 0) > 1) {
  1924.                 $infoRegreso json_decode($infoFlight->selection[1]);
  1925.                 $infoRegresoDate strftime('%d %B del %Y'strtotime(date('d-m-Y'$infoRegreso->S[0]->E)));
  1926.                 $infoRegreso $infoRegreso->S[0]->O;
  1927.                 $infoRegreso2 $infoIda->S[0]->O;
  1928.             }
  1929.             //Calcular los días restantes
  1930.             $date1 = new \DateTime('now');
  1931.             $date2 json_decode(json_encode($freezeData[$i]->getFinishDate()), true);
  1932.             $diff $date1->diff(new \DateTime($date2['date']));
  1933.             $a = (== $diff->invert) ? '-'.$diff->days $diff->days;
  1934.             $paymentInfo json_decode($freezeData[$i]->getFlightInfo(), true);
  1935.             $used 'used' == $freezeData[$i]->getState() ? 'Usado' 'Activo';
  1936.             array_push($arrayFreeze, [
  1937.                 'FlightInfo' => [
  1938.                     'Going' => [
  1939.                         'Date' => strftime('%d %B del %Y'strtotime(date('d-m-Y'$infoIda->S[0]->E))),
  1940.                         'Origin' => [
  1941.                             'Code' => $infoIda->S[0]->O,
  1942.                         ],
  1943.                         'Destination' => [
  1944.                             'Code' => $infoIda->S[0]->D,
  1945.                         ],
  1946.                     ],
  1947.                     'Return' => [
  1948.                         'Date' => $infoRegresoDate,
  1949.                         'Origin' => [
  1950.                             'Code' => $infoRegreso,
  1951.                         ],
  1952.                         'Destination' => [
  1953.                             'Code' => $infoRegreso2,
  1954.                         ],
  1955.                     ],
  1956.                 ],
  1957.                 'Dates' => [
  1958.                     'DateCreated' => $freezeData[$i]->getCreationDate(),
  1959.                     'DateExpiration' => $freezeData[$i]->getFinishDate(),
  1960.                     'DaysLeft' => (int) $a,
  1961.                 ],
  1962.                 'Url' => $freezeData[$i]->getIdRouteFlight()->getUrl(),
  1963.                 'Prices' => [
  1964.                     'PriceHopper' => $freezeData[$i]->getInfoHopper(),
  1965.                     'PriceFlight' => $paymentInfo['x_total_payment']['x_amount'] + $paymentInfo['x_total_payment']['x_airport_tax'] + $paymentInfo['x_total_payment']['x_service_fee'],
  1966.                     'MaxHopperCover' => $freezeData[$i]->getMaxHopperCover(),
  1967.                 ],
  1968.                 'state' => ((int) $a <= 0) ? 'Expirado' $used,
  1969.             ]);
  1970.         }
  1971.         //var_dump(json_encode($arrayFreeze));die;
  1972.         //var_dump($arrayFreeze);die;
  1973.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/frozen-rate.html.twig'), ['status' => true'data' => $arrayFreeze]);
  1974.     }
  1975.     public function sanear_string($string)
  1976.     {
  1977.         $string trim($string);
  1978.         $string str_replace(
  1979.             ['á''à''ä''â''ª'],
  1980.             ['a''a''a''a''a'],
  1981.             $string
  1982.         );
  1983.         $string str_replace(
  1984.             ['é''è''ë''ê'],
  1985.             ['e''e''e''e'],
  1986.             $string
  1987.         );
  1988.         $string str_replace(
  1989.             ['í''ì''ï''î'],
  1990.             ['i''i''i''i'],
  1991.             $string
  1992.         );
  1993.         $string str_replace(
  1994.             ['ó''ò''ö''ô'],
  1995.             ['o''o''o''o'],
  1996.             $string
  1997.         );
  1998.         $string str_replace(
  1999.             ['ú''ù''ü''û'],
  2000.             ['u''u''u''u'],
  2001.             $string
  2002.         );
  2003.         $string str_replace(
  2004.             ['ç'],
  2005.             ['c'],
  2006.             $string
  2007.         );
  2008.         //Esta parte se encarga de eliminar cualquier caracter extraño
  2009.         $string str_replace(
  2010.             ['\\''¨''º''-''~',
  2011.             '#''|''!''"'':',
  2012.             '·''$''%''&''/',
  2013.             '('')''?'"'"'¡',
  2014.             '¿''[''^''`'']',
  2015.             '+''}''{''¨''´',
  2016.             '>''< '';'',', ],
  2017.             '',
  2018.             $string
  2019.         );
  2020.         return $string;
  2021.     }
  2022.     /*
  2023.     private function validateSanctions(SessionInterface $session, ValidateSanctionsRenewal $validateSanctions, $info, $paymentMethod)
  2024.     {
  2025.         if ($session->has('Marked_name') && $session->has('Marked_document')) {
  2026.             $session->remove('Marked_name');
  2027.             $session->remove('Marked_document');
  2028.         }
  2029.         if ($validateSanctions->validateSanctions($info['documentnumber'], $info['name'])) {
  2030.             if (!$session->has('Marked_name') && !$session->has('Marked_document')) {
  2031.                 $session->remove('Marked_name');
  2032.                 $session->remove('Marked_document');
  2033.                 $session->set('Marked_name', $info['name']);
  2034.                 $session->set('Marked_document', $info['documentnumber']);
  2035.             }
  2036.             return 'p2p' === $paymentMethod;
  2037.         }
  2038.         return true;
  2039.     }
  2040.     */
  2041.     private function validateSpecialConditionPayment($cardNum)
  2042.     {
  2043.         $validBins = [
  2044.             '421892',
  2045.             '450407',
  2046.             '492488',
  2047.             '455100',
  2048.             '799955',
  2049.             '813001',
  2050.             '518761',
  2051.             '542650',
  2052.             '527564',
  2053.             '540699',
  2054.             '518841',
  2055.             '454094',
  2056.             '454759',
  2057.             '459418',
  2058.             '492489',
  2059.             '450408',
  2060.             '459419',
  2061.             '404280',
  2062.             '548115',
  2063.             '553643',
  2064.             '450418',
  2065.             '456783',
  2066.             '483080',
  2067.             '485995',
  2068.             '547457',
  2069.             '410164',
  2070.             '404279',
  2071.             '418253',
  2072.             '459317',
  2073.             '462550',
  2074.             '491268',
  2075.             '492468',
  2076.             '589515',
  2077.             '799955',
  2078.         ];
  2079.         if (in_array(substr($cardNum06), $validBins)) {
  2080.             return true;
  2081.         } else {
  2082.             return false;
  2083.         }
  2084.     }
  2085.     private function getValidationOnuOfac($postData$urlDomainSessionInterface $sessionValidateSanctionsRenewal $validateSanctionsRenewal){
  2086.         // Comprobar si la URL contiene "experiencias"
  2087.         $exceptionWords = ['experiencias''paquetes'];
  2088.         $isException false;
  2089.         foreach ($exceptionWords as $eWord) {
  2090.             $isException = (strpos($urlDomain$eWord) !== false);
  2091.             if($isException){
  2092.                 break;
  2093.             }
  2094.         }
  2095.         $isExperiencia strpos($urlDomain'experiencias') !== false;
  2096.         // Si es una experiencia, omitir la validación de pago
  2097.         if ($isException) {
  2098.             $clientArray $validateSanctionsRenewal->getClientsArray($postData$urlDomain);
  2099.             return $validateSanctionsRenewal->validateSanctions($clientArray$sessionnull);
  2100.         } else {
  2101.             // Procesar como de costumbre para otros productos
  2102.             $paymentInfo $postData['PD'];
  2103.             $paymentMethod $paymentInfo['type'];
  2104.             $clientArray $validateSanctionsRenewal->getClientsArray($postData$urlDomain);
  2105.             return $validateSanctionsRenewal->validateSanctions($clientArray$session$paymentMethod);
  2106.         }
  2107.     }
  2108.     /**
  2109.      * @param $redemptionPoint
  2110.      * @param $session
  2111.      * @param $postData
  2112.      * @return array[]|string[]
  2113.      */
  2114.     public function generateOtp($redemptionPoint$session$postData) {
  2115.         if (isset($redemptionPoint) && $session->has('token')) {
  2116.             $info = ["token" => NULL"amount" => $postData['PD']['pointRedemptionValue']];
  2117.             if ($postData['PD']['pointRedemptionValue'] !== '0' || (int) $postData['PD']['pointRedemptionValue'] !== 0) {
  2118.                 $response $this->athServices->addOtp($info);
  2119.             }
  2120.         } else {
  2121.             $response = ["StatusDesc" => 'error en sesion'"StatusCode" => "500"];
  2122.         }
  2123.         return $response;
  2124.     }
  2125. }