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

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