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

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