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