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

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