src/Aviatur/CarBundle/Controller/DefaultController.php line 343

Open in your IDE?
  1. <?php
  2. namespace Aviatur\CarBundle\Controller;
  3. use Aviatur\AgencyBundle\Entity\Agency;
  4. use Aviatur\CarBundle\Entity\ConfigCarAgency;
  5. use Aviatur\CarBundle\Entity\DirectRoutesCar;
  6. use Aviatur\CarBundle\Entity\ProviderCarCode;
  7. use Aviatur\CarBundle\Models\CarModel;
  8. use Aviatur\CarBundle\Services\AviaturCarService;
  9. use Aviatur\CarBundle\Services\SearchCarCookie;
  10. use Aviatur\CustomerBundle\Entity\Customer;
  11. use Aviatur\CustomerBundle\Entity\DocumentType;
  12. use Aviatur\CustomerBundle\Entity\Gender;
  13. use Aviatur\CustomerBundle\Services\ValidateSanctions;
  14. use Aviatur\GeneralBundle\Controller\OrderController;
  15. use Aviatur\GeneralBundle\Entity\Card;
  16. use Aviatur\GeneralBundle\Entity\City;
  17. use Aviatur\GeneralBundle\Entity\Country;
  18. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  19. use Aviatur\GeneralBundle\Entity\HistoricalInfo;
  20. use Aviatur\GeneralBundle\Entity\NameBlacklist;
  21. use Aviatur\GeneralBundle\Entity\NameWhitelist;
  22. use Aviatur\GeneralBundle\Entity\Order;
  23. use Aviatur\GeneralBundle\Entity\OrderProduct;
  24. use Aviatur\GeneralBundle\Entity\Parameter;
  25. use Aviatur\GeneralBundle\Entity\PaymentMethod;
  26. use Aviatur\GeneralBundle\Entity\PaymentMethodAgency;
  27. use Aviatur\GeneralBundle\Entity\PointRedemption;
  28. use Aviatur\GeneralBundle\Entity\SeoUrl;
  29. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  30. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  31. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  32. use Aviatur\GeneralBundle\Services\AviaturMailer;
  33. use Aviatur\GeneralBundle\Services\AviaturWebService;
  34. use Aviatur\GeneralBundle\Services\ExceptionLog;
  35. use Aviatur\GeneralBundle\Services\PayoutExtraService;
  36. use Aviatur\MpaBundle\Entity\Provider;
  37. use Aviatur\PackageBundle\Models\PackageModel;
  38. use Aviatur\PaymentBundle\Controller\CashController;
  39. use Aviatur\PaymentBundle\Controller\P2PController;
  40. use Aviatur\PaymentBundle\Controller\PSEController;
  41. use Aviatur\PaymentBundle\Controller\SafetypayController;
  42. use Aviatur\PaymentBundle\Controller\WorldPayController;
  43. use Aviatur\PaymentBundle\Entity\PseBank;
  44. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  45. use Aviatur\PaymentBundle\Services\TokenizerService;
  46. use Aviatur\SearchBundle\Entity\SearchAirports;
  47. use Aviatur\TwigBundle\Services\TwigFolder;
  48. use Doctrine\Persistence\ManagerRegistry;
  49. use FOS\UserBundle\Model\UserInterface;
  50. use FOS\UserBundle\Security\LoginManagerInterface;
  51. use Knp\Component\Pager\PaginatorInterface;
  52. use Knp\Snappy\AbstractGenerator;
  53. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  54. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  55. use Symfony\Component\HttpFoundation\Cookie;
  56. use Symfony\Component\HttpFoundation\RedirectResponse;
  57. use Symfony\Component\HttpFoundation\Request;
  58. use Symfony\Component\HttpFoundation\Response;
  59. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  60. use Symfony\Component\Routing\RouterInterface;
  61. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  62. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  63. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  64. use Knp\Snappy\Pdf;
  65. class DefaultController extends AbstractController
  66. {
  67.     public function searchAction()
  68.     {
  69.         return $this->redirect(
  70.             $this->generateUrl(
  71.                 'aviatur_search_cars',
  72.                 []
  73.             )
  74.         );
  75.     }
  76.     /**
  77.      * @param Request $request
  78.      * @param ManagerRegistry $managerRegistry
  79.      * @param AviaturErrorHandler $errorHandler
  80.      * @param AviaturWebService $webService
  81.      * @param TwigFolder $twigFolder
  82.      * @param ExceptionLog $exceptionLog
  83.      * @param SearchCarCookie $carCookie
  84.      * @param string $origin
  85.      * @param string $destination
  86.      * @param string $date1
  87.      * @param string $date2
  88.      *
  89.      * @return Response
  90.      */
  91.     public function availabilityAction(Request $requestManagerRegistry $managerRegistryAviaturErrorHandler $errorHandlerAviaturWebService $webServiceTwigFolder $twigFolderExceptionLog $exceptionLogSearchCarCookie $carCookie$origin$destination$date1$date2)
  92.     {
  93.         $urlDescription = [];
  94.         $em $managerRegistry->getManager();
  95.         $session $request->getSession();
  96.         $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  97.         $fullRequest $request;
  98.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
  99.         $seoUrl $em->getRepository(SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
  100.         $urlDescription['url'] = null != $seoUrl '/'.$seoUrl[0]->getUrl() : $requestUrl;
  101.         $sameOrigin false;
  102.         if ('' == $destination) {
  103.             $destination $origin;
  104.             $sameOrigin true;
  105.         }
  106.         $pickUpDate strtotime(false !== strpos($date1'T') ? date('Y-m-d\TH:i:s'strtotime(substr($date1010).sprintf('+%d hours'substr($date1, -52)))) : date('Y-m-d\TH:i:s'strtotime(substr($date1010))));
  107.         $returnDate strtotime(false !== strpos($date2'T') ? date('Y-m-d\TH:i:s'strtotime(substr($date2010).sprintf('+%d hours'substr($date2, -52)))) : date('Y-m-d\TH:i:s'strtotime(substr($date2010))));
  108.         $now strtotime('today');
  109.         if ($pickUpDate $now || $returnDate <= $pickUpDate) {
  110.             $returnDate $pickUpDate $now date('Y-m-d\TH:i'strtotime('+8 day')) : date('Y-m-d\TH:i'strtotime($date1.'+8 day'));
  111.             $pickUpDate $pickUpDate $now date('Y-m-d\TH:i'strtotime('+1 day')) : date('Y-m-d\TH:i'$pickUpDate);
  112.             $url 'aviatur_car_availability_1';
  113.             $data = [
  114.                 'origin' => $origin,
  115.                 'destination' => $destination,
  116.                 'date1' => $pickUpDate,
  117.                 'date2' => $returnDate,
  118.             ];
  119.             if ($sameOrigin) {
  120.                 $url 'aviatur_car_availability_2';
  121.                 $data = [
  122.                     'origin' => $origin,
  123.                     'date1' => $pickUpDate,
  124.                     'date2' => $returnDate,
  125.                 ];
  126.             }
  127.             return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl($url$data), 'Recomendación Automática''La consulta que realizaste no era válida, hemos analizado tu búsqueda y esta es nuestra recomendación'));
  128.         }
  129.         if ($fullRequest->isXmlHttpRequest()) {
  130.             $configsCarAgency $em->getRepository(ConfigCarAgency::class)->findProviderForCarsWithAgency($agency);
  131.             $overrideArray = [];
  132.             $overrideProviders = [];
  133.             if ($configsCarAgency) {
  134.                 $providers = [];
  135.                 foreach ($configsCarAgency as $configCarAgency) {
  136.                     $providers[] = $configCarAgency->getProvider()->getProvideridentifier();
  137.                     $provider $configCarAgency->getProvider()->getProvideridentifier();
  138.                     if (== $configCarAgency->getOverride()) {
  139.                         $overrideProviders[] = $configCarAgency->getProvider()->getProvideridentifier();
  140.                         if (null == $configCarAgency->getExternalid()) {
  141.                             $overrideArray[$provider]['externalId'] = $configCarAgency->getOfficeid();
  142.                             $overrideArray[$provider]['officeId'] = $configCarAgency->getOfficeid();
  143.                         } else {
  144.                             $overrideArray[$provider]['externalId'] = $configCarAgency->getExternalid();
  145.                             $overrideArray[$provider]['officeId'] = $configCarAgency->getOfficeid();
  146.                         }
  147.                     }
  148.                 }
  149.                 $carModel = new CarModel();
  150.                 $variable = [
  151.                     'ProviderId' => implode(';'$providers),
  152.                     'correlationId' => '',
  153.                     'pickUpDateTime' => date('Y-m-d\TH:i:s'$pickUpDate),
  154.                     'returnDateTime' => date('Y-m-d\TH:i:s'$returnDate),
  155.                     'pickUpLocation' => $origin,
  156.                     'returnLocation' => $destination,
  157.                 ];
  158.                 $hasTransaction true;
  159.                 $xmlOverrideArray $carModel->getXmlOverride();
  160.                 $tempOverride '';
  161.                 foreach ($overrideArray as $key => $array) {
  162.                     $search = [
  163.                         '{provider}',
  164.                         '{externalId}',
  165.                         '{officeId}',
  166.                     ];
  167.                     $replace = [
  168.                         $key,
  169.                         $array['externalId'],
  170.                         $array['officeId'],
  171.                     ];
  172.                     $tempOverride .= str_replace($search$replace$xmlOverrideArray[1]);
  173.                 }
  174.                 $xmlOverride $xmlOverrideArray[0].$tempOverride.$xmlOverrideArray[2];
  175.                 $overrideVariables = [
  176.                     'ProviderId' => implode(';'$overrideProviders),
  177.                 ];
  178.                 $responseOverride $webService->callWebServiceAmadeus('SERVICIO_MPT''VehOverride''dummy|http://www.aviatur.com.co/dummy/'$xmlOverride$overrideVariablestrue);
  179.                 if (isset($responseOverride->Message->OTA_ScreenTextRS['CorrelationID'])) {
  180.                     $variable['correlationId'] = (string) $responseOverride->Message->OTA_ScreenTextRS['CorrelationID'];
  181.                     $hasTransaction false;
  182.                 }
  183.                 $providersCars $em->getRepository(ProviderCarCode::class)->findBy(['isActive' => 1]);
  184.                 if (empty($providersCars)) {
  185.                     $data = [
  186.                         'error' => 'Error',
  187.                         'message' => 'No se encontraron disponibilidades para las fechas 1.',
  188.                     ];
  189.                     return $this->json($data);
  190.                 }
  191.                 $codeProviders = [];
  192.                 foreach ($providersCars as $providerCar) {
  193.                     $codeProviders[$providerCar->getCodeProviderCar()] = $providerCar->getInfo();
  194.                 }
  195.                 $xmlRequest $carModel->getXmlAvailability($codeProviders);
  196.                 $responseTemp $webService->callWebServiceAmadeus('SERVICIO_MPT''VehAvailRate''dummy|http://www.aviatur.com.co/dummy/'$xmlRequest$variable$hasTransaction);
  197.                 if (null != $responseTemp && !empty($responseTemp->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails)) {
  198.                     $response = \simplexml_load_string(str_replace('4.JPEG''6.JPEG'$responseTemp->asXml())); // try fetching bigger images
  199.                     $response->Message->OTA_VehAvailRateRS['TransactionID'] = $response->Message->OTA_VehAvailRateRS['TransactionIdentifier'];
  200.                     $response $this->orderResponse($response$codeProviders);
  201.                     if (isset($response['error'])) {
  202.                         $response = new Response(json_encode($response));
  203.                         $response->headers->set('Content-Type''application/json');
  204.                         return $response;
  205.                     }
  206.                     $financialValue $this->getCurrencyExchange($webService);
  207.                     /* Se debe inicializar la sesión al momento de generar la disponibilidad */
  208.                     $session->set('[car][finantial_rate_info]'$financialValue);
  209.                     $vendorTypeList = [];
  210.                     $cars = [];
  211.                     foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $vendor) {
  212.                         if (isset($vendor->VehAvails)) {
  213.                             foreach ($vendor->VehAvails as $VehAvails) {
  214.                                 foreach ($VehAvails->VehAvail as $car) {
  215.                                     $car->VehAvailCore->Vehicle['PictureURL'] = str_replace(['9.JPEG''&amp;'], ['4.JPEG''&'], (string) $car->VehAvailCore->Vehicle->PictureURL);
  216.                                     $VehicleChargeAmount = (float) $car->VehAvailCore->RentalRate->VehicleCharges->VehicleCharge['Amount'];
  217.                                     if (
  218.                                         isset($car->VehAvailCore->TPA_Extensions->LocalRate['CurrencyCode']) && isset($financialValue)
  219.                                         && $VehicleChargeAmount 0
  220.                                         && !in_array($car->Vendor['Code'] . '-' $car->VehAvailCore->Vehicle['VendorCarType'] . '-' $car->Vendor['Provider'], $vendorTypeList)
  221.                                     ) {
  222.                                         $cars[] = $car;
  223.                                         $vendorTypeList[] = $car->Vendor['Code'] . '-' $car->VehAvailCore->Vehicle['VendorCarType'] . '-' $car->Vendor['Provider'];
  224.                                     }
  225.                                 }
  226.                             }
  227.                         }
  228.                     }
  229.                 
  230.                     $stringFindReferer = (string) ((empty($_SERVER['HTTPS']) ? 'http' 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
  231.                     $arrayFindReferer explode('?'$stringFindReferer);
  232.                     return $this->render($twigFolder->twigExists(sprintf('@AviaturTwig/%s/Car/Default/availability_ajaxResults.html.twig'$twigFolder->twigFlux())), [
  233.                         'cars' => $cars,
  234.                         'finantial_rate' => $session->get('[car][finantial_rate_info]'),
  235.                         'transactionId' => (string) $response->Message->OTA_VehAvailRateRS['TransactionID'],
  236.                         'correlationId' => (string) $response->Message->OTA_VehAvailRateRS['CorrelationID'],
  237.                         'findReferer' => $arrayFindReferer[0]
  238.                     ]);
  239.                 } else {
  240.                     $data = [
  241.                         'error' => 'Error',
  242.                         'message' => 'No se encontraron disponibilidades para las fechas, por favor intente con otras fechas.',
  243.                     ];
  244.                     return $this->json($data);
  245.                 }
  246.             } else {
  247.                 $exceptionLog->log(
  248.                     'Error Fatal',
  249.                     'No se encontró configuración para la agencia '.$agency->getId(),
  250.                     null,
  251.                     false
  252.                 );
  253.                 return $this->json([
  254.                     'error' => 'error',
  255.                     'message' => 'no se encontró agencias para consultar disponibilidad.',
  256.                 ]);
  257.             }
  258.         } else {
  259.             $from $em->getRepository(SearchAirports::class)->findOneByIata($origin);
  260.             $to $em->getRepository(SearchAirports::class)->findOneByIata($destination);
  261.             if ($from && $to) {
  262.                 $cookieArray = [
  263.                     'date1' => date('Y-m-d\TH:i:s'strtotime($date1)),
  264.                     'date2' => date('Y-m-d\TH:i:s'strtotime($date2)),
  265.                     'origin' => $origin,
  266.                     'originLabel' => $from->getName().', '.$from->getCity().', '.$from->getCountry().' ('.$origin.')',
  267.                     'destination' => $destination,
  268.                     'destinationLabel' => $to->getName().', '.$to->getCity().', '.$to->getCountry().' ('.$destination.')',
  269.                     'sameOrigin' => $sameOrigin,
  270.                 ];
  271.                 if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
  272.                     $safeUrl 'https://'.$agency->getDomain();
  273.                 } else {
  274.                     $safeUrl 'https://'.$agency->getDomainsecure();
  275.                 }
  276.                 $cookieLastSearch $carCookie->searchCarCookie(['car' => base64_encode(json_encode($cookieArray))]);
  277.                 $availableArrayCar array_merge($cookieArray, [
  278.                     'originLocation' => $from->getName(),
  279.                     'destinationLocation' => $to->getName(),
  280.                     'cityOriginName' => $from->getCity(),
  281.                     'cityDestinationName' => $to->getCity(),
  282.                 ]);
  283.                 $pointRedemption $em->getRepository(PointRedemption::class)->findPointRedemptionWithAgency($agency);
  284.                 if (null != $pointRedemption) {
  285.                     $points 0;
  286.                     if ($fullRequest->request->has('pointRedemptionValue')) {
  287.                         $points $fullRequest->request->get('pointRedemptionValue');
  288.                         $session->set('point_redemption_value'$points);
  289.                     } elseif ($fullRequest->query->has('pointRedeem')) {
  290.                         $points $fullRequest->query->get('pointRedeem');
  291.                         $session->set('point_redemption_value'$points);
  292.                     } elseif ($session->has('point_redemption_value')) {
  293.                         $points $session->get('point_redemption_value');
  294.                     }
  295.                     $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  296.                 }
  297.                 $agencyFolder $twigFolder->twigFlux();
  298.                 $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), array_merge($fullRequest->attributes->get('_route_params'), []));
  299.                 $response $this->render($twigFolder->twigExists(sprintf('@AviaturTwig/%s/Car/Default/availability.html.twig'$agencyFolder)), [
  300.                     'ajaxUrl' => $requestUrl,
  301.                     'safeUrl' => $safeUrl,
  302.                     'availableArrayCar' => $availableArrayCar,
  303.                     'cookieLastSearch' => $cookieLastSearch,
  304.                     'urlDescription' => $urlDescription,
  305.                     'inlineEngine' => true,
  306.                     'pointRedemption' => $pointRedemption,
  307.                 ]);
  308.                 $response->headers->setCookie(new Cookie('_availability_array[car]'base64_encode(json_encode($cookieArray)), (time() + 3600 24 7), '/'));
  309.             } else {
  310.                 return $this->redirect($errorHandler->errorRedirect('/''Error búsqueda autos'sprintf('Una de las ciudades no se pudo encontrar en la base de datos, iatas: %s %s'$origin$destination)));
  311.             }
  312.             return $response;
  313.         }
  314.     }
  315.     public function detailPostAction(Request $requestManagerRegistry $managerRegistryAviaturLogSave $logSaveAviaturEncoder $aviaturEncoder)
  316.     {
  317.         $transactionId null;
  318.         $fullRequest $request;
  319.         $request $fullRequest->request;
  320.         //$queryString = $fullRequest->query;
  321.         
  322.         if (true === $request->has('carTransactionID')) {
  323.             $transactionId $request->get('carTransactionID');
  324.             if (false !== strpos($transactionId'||')) {
  325.                 $explodedTransaction explode('||'$transactionId);
  326.                 $transactionId $explodedTransaction[0];
  327.             }
  328.         }
  329.         $logSave->logSave($transactionId'tidDetailCar''RS');
  330.         if ($request->has('carTransactionID')) {
  331.             $info = [];
  332.             $variables = ['carSelection''carPickUpDateTime''carReturnDateTime''carPickUpLocation''carReturnLocation''vehicleCategory''carProviderID'];
  333.             foreach ($variables as $variable) {
  334.                 if ($request->has($variable)) {
  335.                     $info['selection'][$variable] = $request->get($variable);
  336.                 }
  337.             }
  338.             $em $managerRegistry->getManager();
  339.             $directRouteFlight $em->getRepository(DirectRoutesCar::class)->findOneByInfo(json_encode($info));
  340.             if (null == $directRouteFlight) {
  341.                 $url $aviaturEncoder->aviaturRandomKey();
  342.                 $directRoutesFlights = new DirectRoutesCar();
  343.                 $directRoutesFlights->setCreationdate(new \DateTime());
  344.                 $directRoutesFlights->setInfo(json_encode($info));
  345.                 $directRoutesFlights->setUrl($url);
  346.                 $em->persist($directRoutesFlights);
  347.                 $em->flush();
  348.             } else {
  349.                 $url $directRouteFlight->getUrl();
  350.             }
  351.             return $this->redirectToRoute('aviatur_car_detail_specific_secure', ['url' => $url], 307);
  352.         } else {
  353.             return $this->redirectToRoute('aviatur_car_detail_secure', [], 307);
  354.         }
  355.     }
  356.     public function detailSpecificAction(Request $requestManagerRegistry $managerRegistryAviaturErrorHandler $errorHandlerAviaturWebService $webService$url)
  357.     {
  358.         $server $request->server;
  359.         $requestParams $request->request;
  360.         $em $managerRegistry->getManager();
  361.         if (true === $requestParams->has('carTransactionID')) {
  362.             $transactionIdResponse $requestParams->get('carTransactionID');
  363.         } else {
  364.             $transactionIdResponse $webService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/');
  365.             if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  366.                 $errorHandler->errorRedirect('''Error MPA''No se creo Login!');
  367.                 return new Response('Estamos experimentando dificultades técnicas en este momento.');
  368.             }
  369.         }
  370.         $directRouteFlight $em->getRepository(DirectRoutesCar::class)->findOneByUrl($url);
  371.         if (null == $directRouteFlight) {
  372.             return $this->redirect($errorHandler->errorRedirectNoEmail('/''URL no encontrada''La URL de detalle no es valida por favor verifique e intente nuevamente'));
  373.         }
  374.         $infos json_decode($directRouteFlight->getInfo(), true);
  375.         $variables = ['carSelection''carPickUpDateTime''carReturnDateTime''carPickUpLocation''carReturnLocation''vehicleCategory''carProviderID'];
  376.         $requestParams->set('carTransactionID'$transactionIdResponse);
  377.         $requestParams->set('carSessionID''Direct');
  378.         foreach ($variables as $variable) {
  379.             $requestParams->set($variable$infos['selection'][$variable]);
  380.         }
  381.         if (!$server->has('HTTP_REFERER')) {
  382.             $server->set('HTTP_REFERER''/');
  383.         }
  384.         // Using forward instead of calling method directly to send all the services.
  385.         return $this->forward('Aviatur\CarBundle\Controller\DefaultController::detailAction');
  386.     }
  387.     private function orderResponse($response$codeProviders)
  388.     {
  389.         $key 0;
  390.         $options = [];
  391.         $blockedVendors = [
  392.             //            'AC', 'AD', 'EH', 'AT', 'BV',
  393.             //            'CR', 'CI', 'ES', 'EY', 'ET',
  394.             //            'EX', 'EM', 'EP', 'IM', 'EZ',
  395.             //            'FF', 'FC', 'FX', 'GR', 'HH',
  396.             //            'EG', 'MO', 'ZA', 'PC', 'RF',
  397.             //            'RH', 'SX', 'HT', 'ZT', 'SV',
  398.             //            'UN', 'WF', 'MG'
  399.         ];
  400.         foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $vendor) {
  401.             if (!in_array((string) $vendor->Vendor['Code'], $blockedVendors) && isset($vendor->Vendor['Code']) && isset($codeProviders)) {
  402.                 foreach ($vendor->VehAvails as $VehAvails) {
  403.                     foreach ($VehAvails->VehAvail as $car) {
  404.                         $car->Vendor['CompanyShortName'] = $vendor->Vendor['CompanyShortName'];
  405.                         $car->Vendor['TravelSector'] = $vendor->Vendor['TravelSector'];
  406.                         $car->Vendor['Code'] = $vendor->Vendor['Code'];
  407.                         $car->Vendor['RPH'] = $vendor->Info->TPA_Extensions->RPH;
  408.                         $correlationIdArray explode('CorrelationID=', (string) $vendor->Notes);
  409.                         $correlationIdArray explode(';'$correlationIdArray[1]);
  410.                         $correlationSegment $correlationIdArray[0];
  411.                         $car->Vendor['CorrelationId'] = str_replace(['ProviderId='';'], ''$correlationSegment);
  412.                         $providerIdArray explode('ProviderId=', (string) $vendor->Notes);
  413.                         $providerIdArray explode(';'$providerIdArray[1]);
  414.                         $providerSegment $providerIdArray[0];
  415.                         $car->VehAvailCore->Vehicle->PictureURL str_replace(['&amp;''6.JPEG'], ['&''4.JPEG'], $car->VehAvailCore->Vehicle->PictureURL);
  416.                         $car->Vendor['Provider'] = str_replace(['ProviderId='';'], ''$providerSegment);
  417.                         $options[$key]['amount'] = (float) $car->VehAvailCore->TotalCharge['RateTotalAmount'];
  418.                         $options[$key]['xml'] = $car->asXml();
  419.                         $options[$key]['provider'] = $providerSegment;
  420.                         ++$key;
  421.                     }
  422.                 }
  423.             }
  424.         }
  425.         usort($options, fn($a$b) => $a['amount'] - $b['amount']);
  426.         $responseXml explode('<VehAvail>'str_replace('</VehAvail>''<VehAvail>'$response->asXml()));
  427.         $orderedResponse $responseXml[0];
  428.         foreach ($options as $option) {
  429.             $orderedResponse .= $option['xml'];
  430.         }
  431.         $orderedResponse .= $responseXml[sizeof($responseXml) - 1];
  432.         libxml_use_internal_errors(true);
  433.         $orderResponse = \simplexml_load_string($orderedResponse);
  434.         if (false === $orderResponse) {
  435.             $data = ['error' => 'Error''message' => 'No se encontraron disponibilidades para las fechas, por favor intente con otras fechas.'];
  436.             return $data;
  437.         } else {
  438.             return $orderResponse;
  439.         }
  440.     }
  441.     public function availabilitySeoAction(Request $requestManagerRegistry $managerRegistrySessionInterface $sessionRouterInterface $router$url)
  442.     {
  443.         $em $managerRegistry->getManager();
  444.         $seoUrl $em->getRepository(SeoUrl::class)->findOneByUrl('autos/'.$url);
  445.         if (null != $seoUrl) {
  446.             $maskedUrl $seoUrl->getMaskedurl();
  447.             $session->set('maxResults'$request->query->get('maxResults'));
  448.             if (false !== strpos($maskedUrl'?')) {
  449.                 $parameters explode('&'substr($maskedUrlstrpos($maskedUrl'?') + 1));
  450.                 foreach ($parameters as $parameter) {
  451.                     $sessionInfo explode('='$parameter);
  452.                     if (== sizeof($sessionInfo)) {
  453.                         $session->set($sessionInfo[0], $sessionInfo[1]);
  454.                     }
  455.                 }
  456.                 $maskedUrl substr($maskedUrl0strpos($maskedUrl'?'));
  457.             }
  458.             if (null != $seoUrl) {
  459.                 $route $router->match($maskedUrl);
  460.                 $route['_route_params'] = [];
  461.                 foreach ($route as $param => $val) {
  462.                     // set route params without defaults
  463.                     if ('_' !== \substr($param01)) {
  464.                         $route['_route_params'][$param] = $val;
  465.                     }
  466.                 }
  467.                 return $this->forward($route['_controller'], $route);
  468.             } else {
  469.                 throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
  470.             }
  471.         } else {
  472.             throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
  473.         }
  474.     }
  475.     /**
  476.      * @param Request $request
  477.      * @param ManagerRegistry $managerRegistry
  478.      * @param TokenStorageInterface $tokenStorage
  479.      * @param ParameterBagInterface $parameterBag
  480.      * @param LoginManagerInterface $loginManager
  481.      * @param TwigFolder $twigFolder
  482.      * @param AviaturErrorHandler $errorHandler
  483.      * @param CustomerMethodPaymentService $methodPaymentService
  484.      * @param AviaturWebService $webService
  485.      * @param PayoutExtraService $extraService
  486.      *
  487.      * @return RedirectResponse|Response
  488.      */
  489.     public function detailAction(Request $requestManagerRegistry $managerRegistryTokenStorageInterface $tokenStorageParameterBagInterface $parameterBagLoginManagerInterface $loginManagerTwigFolder $twigFolderAviaturErrorHandler $errorHandlerCustomerMethodPaymentService $methodPaymentServiceAviaturWebService $webServicePayoutExtraService $extraService)
  490.     {
  491.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  492.         $correlationIdSessionName $parameterBag->get('correlation_id_session_name');
  493.         $session $request->getSession();
  494.         $em $managerRegistry->getManager();
  495.         $fullRequest $request;
  496.         $availabilityUrl $fullRequest->server->get("HTTP_REFERER");
  497.         $requestParams $request->request;
  498.         $carFindReferer $requestParams->get("carFindReferer");
  499.         $serverParams $request->server;
  500.         $passangerTypes = [];
  501.         $customer null;
  502.         $list = [];
  503.         $location null;
  504.         $financialValue = [];
  505.         $carsInfo = [];
  506.         $response = [];
  507.         $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  508.         $configsCarAgency $em->getRepository(ConfigCarAgency::class)->findProviderForCarsWithAgency($agency);
  509.         $car_homologate_hertz_codes json_decode($em->getRepository(Parameter::class)->findOneByName('car_homologate_hertz_codes')->getDescription(), true);
  510.         if (true === $requestParams->has('whitemarkDataInfo')) {
  511.             $session->set('whitemarkDataInfo'json_decode($requestParams->get('whitemarkDataInfo'), true));
  512.         }
  513.         if (true === $requestParams->has('userLogin') && '' != $requestParams->get('userLogin') && null != $requestParams->get('userLogin')) {
  514.             $user $em->getRepository(Customer::class)->findOneByEmail($requestParams->get('userLogin'));
  515.             $this->authenticateUser($user$loginManager);
  516.         }
  517.         if ($configsCarAgency) {
  518.             $providers = [];
  519.             foreach ($configsCarAgency as $configCarAgency) {
  520.                 $providers[] = $configCarAgency->getProvider()->getProvideridentifier();
  521.             }
  522.         } else {
  523.             $message 'no se encontró agencias para consultar disponibilidad.';
  524.             $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  525.             if (true === $requestParams->has('referer') && true === $requestParams->has('http_referer')) {
  526.                 $returnUrl $requestParams->get('http_referer');
  527.             }
  528.             return $this->redirect($errorHandler->errorRedirect($returnUrl''$message));
  529.         }
  530.         $transactionId $requestParams->get('carTransactionID');
  531.         $isFront $session->has('operatorId');
  532.         if ($session->has('typeCoin')) {
  533.             $session->set($transactionId.'[typeCoin]'$session->get('typeCoin'));
  534.             $session->set($transactionId.'[RateChange]'$session->get('RateChange'));
  535.             $session->set($transactionId.'[financialValue]'$session->get('financialValue'));
  536.             $session->set($transactionId.'[trmValue]'$session->get('trmValue'));
  537.         }
  538.         if ($session->has($transactionId.'[car][retry]')) {
  539.             $response = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
  540.             $typeDocument $em->getRepository(DocumentType::class)->findAll();
  541.             $typeGender $em->getRepository(Gender::class)->findAll();
  542.             $repositoryDocumentType $managerRegistry->getRepository(DocumentType::class);
  543.             $queryDocumentType $repositoryDocumentType
  544.                 ->createQueryBuilder('p')
  545.                 ->where('p.paymentcode != :paymentcode')
  546.                 ->setParameter('paymentcode''')
  547.                 ->getQuery();
  548.             $documentPaymentType $queryDocumentType->getResult();
  549.             $passangerTypes[1] = [
  550.                 'ADT' => 1,
  551.                 'CHD' => 0,
  552.                 'INF' => 0,
  553.             ];
  554.             $postDataJson $session->get($transactionId.'[car][detail_data]');
  555.             $paymentData json_decode($postDataJson);
  556.             $conditions $em->getRepository(HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_hotels');
  557.             $first_name $paymentData->PI->first_name_1_1;
  558.             $last_name $paymentData->PI->last_name_1_1;
  559.             $nationality $em->getRepository(Country::class)->findOneByIatacode($paymentData->PI->nationality_1_1)->getDescription();
  560.             if (strpos($first_name'***') > 0) {
  561.                 $customer $em->getRepository(Customer::class)->find($paymentData->BD->id);
  562.                 $first_name $customer->getFirstname();
  563.                 $last_name $customer->getLastname();
  564.             }
  565.             $passangerInfo = [
  566.                 'first_name_1_1' => $first_name,
  567.                 'last_name_1_1' => $last_name,
  568.                 'doc_type_1_1' => $paymentData->PI->doc_type_1_1,
  569.                 'doc_num_1_1' => $paymentData->PI->doc_num_1_1,
  570.                 'born_date_1_1' => $paymentData->PI->birthday_1_1,
  571.                 'nationality_1_1_validate' => $nationality,
  572.                 'phone_1_1' => $customer->getPhone(),
  573.                 'email_1_1' => $customer->getEmail(),
  574.                 'person_count_1' => $paymentData->PI->person_count_1,
  575.                 'passanger_type_1_1' => $paymentData->PI->passanger_type_1_1,
  576.                 'gender_1_1' => $paymentData->PI->gender_1_1,
  577.                 'birthday_1_1' => $paymentData->PI->birthday_1_1,
  578.                 'nationality_1_1' => $paymentData->PI->nationality_1_1,
  579.             ];
  580.             $billingData = [
  581.                 'doc_type' => $paymentData->BD->doc_type,
  582.                 'doc_num' => $paymentData->BD->doc_num,
  583.                 'first_name' => $paymentData->BD->first_name,
  584.                 'last_name' => $paymentData->BD->last_name,
  585.                 'email' => $paymentData->BD->email,
  586.                 'address' => $paymentData->BD->address,
  587.                 'phone' => $paymentData->BD->phone,
  588.             ];
  589.             $contactData = [
  590.                 'phone' => $paymentData->CD->phone,
  591.             ];
  592.             $locations = [];
  593.             foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Info->LocationDetails as $location) {
  594.                 $locations[] = $location;
  595.             }
  596.             foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $VehVendorAvail) {
  597.                 if ((int) $VehVendorAvail->Info->TPA_Extensions->RPH == explode('-'$paymentData->SD->selection)[0]) {
  598.                     foreach ($VehVendorAvail->VehAvails as $VehAvails) {
  599.                         foreach ($VehAvails->VehAvail as $VehAvail) {
  600.                             if ((int) $VehAvail->VehAvailInfo->TPA_Extensions->RPH == explode('-'$paymentData->SD->selection)[1]) {
  601.                                 $carsInfo[] = $VehVendorAvail;
  602.                             }
  603.                         }
  604.                     }
  605.                 }
  606.             }
  607.             /* Se deberían comparar si tienen características básicas completamente iguales, para no permitir que se muestren repetidas */
  608.             //$this->reorderCarsInfo($carsInfo);
  609.             $carSelection $paymentData->SD->selection;
  610.             $selection json_decode($session->get($transactionId.'[car][selection]'), true);
  611.             $ProviderCarInfo json_decode($session->get($transactionId.'[car][ProviderCarInfo]'), true);
  612.             $vehicleCategory $session->get($transactionId.'[car][vehicleCategory]');
  613.             $list json_decode($session->get($transactionId.'[car][list]'), true);
  614.             if (isset($paymentData->cusPOptSelected)) {
  615.                 $customerLogin $tokenStorage->getToken()->getUser();
  616.                 if (is_object($customerLogin)) {
  617.                     $paymentsSaved $methodPaymentService->getMethodsByCustomer($customerLoginfalse);
  618.                 }
  619.             }
  620.             $paymentOptions = [];
  621.             $paymentMethodAgency $em->getRepository(PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  622.             $paymentMethodsPermitted = ['p2p''cybersource''world'];
  623.             foreach ($paymentMethodAgency as $payMethod) {
  624.                 $paymentCode $payMethod->getPaymentMethod()->getCode();
  625.                 if (!in_array($paymentCode$paymentOptions) && in_array($paymentCode$paymentMethodsPermitted)) {
  626.                     $paymentOptions[] = $paymentCode;
  627.                 }
  628.             }
  629.             $banks = [];
  630.             if (in_array('pse'$paymentOptions)) {
  631.                 $banks $em->getRepository(PseBank::class)->findAll();
  632.             }
  633.             $cybersource = [];
  634.             if (in_array('cybersource'$paymentOptions)) {
  635.                 $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  636.                 $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  637.             }
  638.             $financialValue json_decode($session->get('[car][finantial_rate_info]'), true);
  639.             $agencyFolder $twigFolder->twigFlux();
  640.             /* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
  641.             /* Necesitamos crear un arreglo que tenga todos los rangos de IIN asociados a su franquicia y a sus límites de número de tarjeta */
  642.             $iinRecordsArray $this->getIINRanges($em);
  643.             return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Car/Default/detail.html.twig'), [
  644.                 'payment_doc_type' => $documentPaymentType,
  645.                 'billingData' => $billingData,
  646.                 'banks' => $banks,
  647.                 'finantial_rate' => $financialValue,
  648.                 'carSelection' => $carSelection,
  649.                 'cybersource' => $cybersource,
  650.                 'cards' => $em->getRepository(Card::class)->findBy(['isactive' => 1]),
  651.                 'inactiveCards' => $em->getRepository(Card::class)->findBy(['isactive' => 0]),
  652.                 'contactData' => $contactData,
  653.                 'paymentOptions' => $paymentOptions,
  654.                 'baloto' => in_array('baloto'$paymentOptions) ? true false,
  655.                 'pse' => in_array('pse'$paymentOptions) ? true false,
  656.                 'safety' => in_array('safety'$paymentOptions) ? true false,
  657.                 'passanger_data' => $passangerInfo,
  658.                 'twig_readonly' => true,
  659.                 'doc_type' => $typeDocument,
  660.                 'gender' => $typeGender,
  661.                 'services' => $passangerTypes,
  662.                 'conditions' => $conditions,
  663.                 'transactionId' => base64_encode($transactionId),
  664.                 'CriteoTags' => null,
  665.                 'passengers' => $passangerInfo,
  666.                 'pickUpLocation' => $locations[0],
  667.                 'vendorPref' => $selection[0],
  668.                 'vehicleCategory' => $vehicleCategory,
  669.                 'returnLocation' => end($locations),
  670.                 'serviceResponse' => $response->Message->OTA_VehAvailRateRS,
  671.                 'carsInfo' => $carsInfo,
  672.                 'carsItems' => (null != $ProviderCarInfo) ? $ProviderCarInfo null,
  673.                 'carDescription' => $list,
  674.                 'payment_type_form_name' => $session->get($transactionId '[car][paymentType]'),
  675.                 'payment_form' => $session->get($transactionId '[car][payment_car_form]'),
  676.                 'referer' => $availabilityUrl,
  677.                 'total_amount' => $session->get($transactionId '[car][total_amount]'),
  678.                 'currency_code' => $session->get($transactionId '[car][currency]'),
  679.                 'total_amount_local' => $session->get($transactionId '[car][total_amount_local]'),
  680.                 'currency_code_local' => $session->get($transactionId '[car][currency_code_local]'),
  681.                 'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  682.                 'car_homologate_hertz_codes' => $car_homologate_hertz_codes,
  683.                 'ccranges' => $iinRecordsArray["ccranges"],
  684.                 'ccfranchises' => $iinRecordsArray["ccfranchises"],
  685.             ]);
  686.         } else {
  687.             if (true === $requestParams->has('referer')) {
  688.                 $session->set($transactionId.'[availability_url]'$requestParams->get('http_referer'));
  689.                 $session->set($transactionId.'[referer]'$requestParams->get('referer'));
  690.             } elseif (true !== $session->has($transactionId.'[availability_url]')) {
  691.                 $session->set($transactionId.'[availability_url]'$serverParams->get('HTTP_REFERER'));
  692.             }
  693.             $autoModel = new CarModel();
  694.             $xmlRequestAvail $autoModel->getXmlDetail();
  695.             $pickUpDate $requestParams->get('carPickUpDateTime');
  696.             $returnDate $requestParams->get('carReturnDateTime');
  697.             $pickUpLocation $requestParams->get('carPickUpLocation');
  698.             $returnLocation $requestParams->get('carReturnLocation');
  699.             $selection explode('-'$requestParams->get('carSelection'));
  700.             $vehicleCategory $requestParams->get('vehicleCategory');
  701.             $provider $em->getRepository(Provider::class)->findOneByProvideridentifier($requestParams->get('carProviderID'));
  702.             $ProviderCarInfo $em->getRepository(ProviderCarCode::class)->findOneBy(['codeProviderCar' => $selection[0], 'isActive' => 1]);
  703.             if (!$ProviderCarInfo) {
  704.                 $message 'Ha ocurrido un error inesperado del proveedor';
  705.                 $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  706.                 return $this->redirect($errorHandler->errorRedirect($returnUrl''$message));
  707.             }
  708.             $session->set($transactionId.'[car][selection]'json_encode($selection));
  709.             $session->set($transactionId.'[car][vehicleCategory]'$vehicleCategory);
  710.             $session->set($transactionId.'[car][ProviderCarInfo]'$ProviderCarInfo->getInfo());
  711.             $variable = [
  712.                 'pickUpDate' => date('Y-m-d\TH:i:s'strtotime($pickUpDate)),
  713.                 'returnDate' => date('Y-m-d\TH:i:s'strtotime($returnDate)),
  714.                 'pickUpLocation' => $pickUpLocation,
  715.                 'returnLocation' => $returnLocation,
  716.                 'vendorPref' => $selection[0],
  717.                 'ProviderId' => $provider->getProvideridentifier(),
  718.                 'transactionId' => $transactionId,
  719.                 'ProviderXml' => $autoModel->providers($ProviderCarInfo->getInfo(), $selection[0]),
  720.                 'vehicleCategory' => $vehicleCategory,
  721.             ];
  722.             $responseTemp $webService->callWebServiceAmadeus('SERVICIO_MPT''VehAvailRate''dummy|http://www.aviatur.com.co/dummy/'$xmlRequestAvail$variablefalse$transactionId);
  723.             if (!isset($responseTemp['error'])) {
  724.                 $response = \simplexml_load_string(str_replace('4.JPEG''9.JPEG'$responseTemp->asXml()));
  725.                 $session->set($transactionId.'[car][provider]'$provider->getProvideridentifier());
  726.                 $session->set($transactionId.'[car][detail]'$response->asXML());
  727.                 $session->set($transactionId.'[car][detail_time]'time());
  728.                 $session->set($transactionIdSessionName$transactionId);
  729.                 $session->set('[referer]'$serverParams->get('HTTP_REFERER'));
  730.                 if (!isset($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail) || !isset($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Notes)) {
  731.                     $message $response['error'] ?? 'Ha ocurrido un error inesperado en el servicio';
  732.                     $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  733.                     if (true === $requestParams->has('referer') && true === $requestParams->has('http_referer')) {
  734.                         $returnUrl $requestParams->get('http_referer');
  735.                     }
  736.                     return $this->redirect($errorHandler->errorRedirect($returnUrl''$message));
  737.                 }
  738.                 $twigVariables = [];
  739.                 $correlationId = (string) explode('='explode(';'$response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Notes)[0])[1];
  740.                 $session->set($transactionId.'[car]['.$correlationIdSessionName.']'$correlationId);
  741.                 $typeDocument $em->getRepository(DocumentType::class)->findAll();
  742.                 $typeGender $em->getRepository(Gender::class)->findAll();
  743.                 $repositoryDocumentType $managerRegistry->getRepository(DocumentType::class);
  744.                 $queryDocumentType $repositoryDocumentType
  745.                     ->createQueryBuilder('p')
  746.                     ->where('p.paymentcode != :paymentcode')
  747.                     ->setParameter('paymentcode''')
  748.                     ->getQuery();
  749.                 $documentPaymentType $queryDocumentType->getResult();
  750.                 $paymentMethodAgency $em->getRepository(PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  751.                 $paymentOptions = [];
  752.                 $paymentMethodsPermitted = ['p2p''cybersource''world'];
  753.                 foreach ($paymentMethodAgency as $payMethod) {
  754.                     $paymentCode $payMethod->getPaymentMethod()->getCode();
  755.                     if (!in_array($paymentCode$paymentOptions) && in_array($paymentCode$paymentMethodsPermitted)) {
  756.                         $paymentOptions[] = $paymentCode;
  757.                     }
  758.                 }
  759.                 $banks = [];
  760.                 if (in_array('pse'$paymentOptions)) {
  761.                     $banks $em->getRepository(PseBank::class)->findAll();
  762.                 }
  763.                 $cybersource = [];
  764.                 if (in_array('cybersource'$paymentOptions)) {
  765.                     $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  766.                     $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  767.                 }
  768.                 $twigVariables += [
  769.                     'cards' => $em->getRepository(Card::class)->findAll(),
  770.                     'paymentOptions' => $paymentOptions,
  771.                     'banks' => $banks,
  772.                     'cybersource' => $cybersource,
  773.                 ];
  774.                 $paymentType 'paymentForm';
  775.                 $session->set($transactionId.'[car][paymentType]'$paymentType);
  776.                 $passangerTypes[1] = [
  777.                     'ADT' => 1,
  778.                     'CHD' => 0,
  779.                     'INF' => 0,
  780.                 ];
  781.                 $conditions $em->getRepository(HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions_for_hotels');
  782.                 $agencyFolder $twigFolder->twigFlux();
  783.                 $list[0] = ['M' => 'Mini''N' => 'Mini Élite''E' => 'Económico''H' => 'Económico Élite''C' => 'Compacto''D' => 'Compacto Élite''I' => 'Intermedio''J' => 'Intermedio Élite''S' => 'Estándar''R' => 'Estándar Élite''F' => 'Fullsize''G' => 'Fullsize Elite''P' => 'Premium''U' => 'Premium Élite''L' => 'Lujoso''W' => 'Lujoso Élite''O' => 'Oversize''X' => 'Especial'];
  784.                 $list[1] = ['B' => '2-3 Puertas''C' => '2/4 Puertas''D' => '4-5 Puertas''W' => 'Vagón''V' => 'Van de pasajeros''L' => 'Limosina''S' => 'Deportivo''T' => 'Convertible''F' => 'SUV''J' => 'Todo Terreno''X' => 'Especial''P' => 'Pick up de Cabina Regular''Q' => 'Pick up de Cabina Extendida''Z' => 'Auto de Oferta Especial''E' => 'Coupe''M' => 'Minivan''R' => 'Vehículo recreacional''H' => 'Casa rodante''Y' => 'Vehículo de dos ruedas''N' => 'Roasted''G' => 'Crossover''K' => 'Van comercial / Camión'];
  785.                 $list[2] = ['M' => 'Transmisión Manual, Tracción sin especificar''N' => 'Transmisión Manual, Tracción 4WD''C' => 'Transmisión Manual, Tracción AWD''A' => 'Transmisión Automática, Tracción sin especificar''B' => 'Transmisión Automática, Tracción 4WD''D' => 'Transmisión Automática, Tracción AWD'];
  786.                 $list[3] = ['R' => 'Combustible no especificado, con aire acondicionado''N' => 'Combustible no especificado, sin aire acondicionado''D' => 'Diesel, con aire acondicionado''Q' => 'Diesel, sin aire acondicionado''H' => 'Híbrido, con aire acondicionado''I' => 'Híbrido, sin aire acondicionado''E' => 'Eléctrico, con aire acondicionado''C' => 'Eléctrico, sin aire acondicionado''L' => 'Gas comprimido, con aire acondicionado''S' => 'Gas comprimido, sin aire acondicionado''A' => 'Hidrógeno, con aire acondicionado''B' => 'Hidrógeno, sin aire acondicionado''M' => 'Multi combustible, con aire acondicionado''F' => 'Multi combustible, sin aire acondicionado''V' => 'Gasolina, con aire acondicionado''Z' => 'Gasolina, sin aire acondicionado''U' => 'Etanol, con aire acondicionado''X' => 'Etanol, sin aire acondicionado'];
  787.                 $session->set($transactionId.'[car][list]'json_encode($list));
  788.                 $locations = [];
  789.                 foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Info->LocationDetails as $location) {
  790.                     $locations[] = $location;
  791.                 }
  792.                 $session->set($transactionId.'[car][locations]'json_encode($locations));
  793.                 $isNational true;
  794.                 if ('CO' != $location->Address->CountryName) {
  795.                     $isNational false;
  796.                 }
  797.                 $args = (object)[
  798.                     'passangerTypes' => $passangerTypes,
  799.                     'isNational' => $isNational,
  800.                 ];
  801.                 $payoutExtras null;
  802.                 if (!$isFront) {
  803.                     $payoutExtras $extraService->loadPayoutExtras($agency$transactionId'Car'$args);
  804.                 }
  805.                 $pointRedemption $em->getRepository(PointRedemption::class)->findPointRedemptionWithAgency($agency);
  806.                 if (null != $pointRedemption) {
  807.                     $points 0;
  808.                     if ($requestParams->has('pointRedemptionValue')) {
  809.                         $points $requestParams->get('pointRedemptionValue');
  810.                         $session->set('point_redemption_value'$points);
  811.                     } elseif ($requestParams->has('pointRedeem')) {
  812.                         $points $requestParams->get('pointRedeem');
  813.                         $session->set('point_redemption_value'$points);
  814.                     } elseif ($session->has('point_redemption_value')) {
  815.                         $points $session->get('point_redemption_value');
  816.                     }
  817.                     $pointRedemption['Config']['Amount']['CurPoint'] = $points;
  818.                 }
  819.                 foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $key => $VehVendorAvail) {
  820.                     $carsInfo[] = $VehVendorAvail;
  821.                 }
  822.                 /* Se deberían comparar si tienen características básicas completamente iguales, para no permitir que se muestren repetidas */
  823.                 //$this->reorderCarsInfo($carsInfo);
  824.                 $financialValue $this->getCurrencyExchange($webService);
  825.                 $session->set('[car][finantial_rate_info]'json_encode($financialValue));
  826.                 $session->set($transactionId.'[car][carsInfo]'json_encode($carsInfo));
  827.                 $prueba $session->get($transactionId.'[availability_url]');
  828.                 $twigVariables += [
  829.                     'payment_doc_type' => $documentPaymentType,
  830.                     'twig_readonly' => false,
  831.                     'finantial_rate' => $financialValue,
  832.                     'doc_type' => $typeDocument,
  833.                     'gender' => $typeGender,
  834.                     'services' => $passangerTypes,
  835.                     'conditions' => $conditions,
  836.                     'transactionId' => base64_encode($transactionId),
  837.                     'CriteoTags' => null,
  838.                     'passanger_data' => [],
  839.                     'pickUpLocation' => $locations[0],
  840.                     'vendorPref' => $selection[0],
  841.                     'vehicleCategory' => $vehicleCategory,
  842.                     'returnLocation' => end($locations),
  843.                     'serviceResponse' => $response->Message->OTA_VehAvailRateRS,
  844.                     'carsInfo' => $carsInfo,
  845.                     'carsItems' => json_decode($ProviderCarInfo->getInfo(), true),
  846.                     'carDescription' => $list,
  847.                     'payment_type_form_name' => $paymentType,
  848.                     //'referer' => $serverParams->get('HTTP_REFERER'),
  849.                     'referer' => $availabilityUrl,
  850.                     'total_amount' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
  851.                     'currency_code' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['CurrencyCode'],
  852.                     'total_amount_local' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TPA_Extensions->LocalRate['RateTotalAmount'],
  853.                     'currency_code_local' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TPA_Extensions->LocalRate['CurrencyCode'],
  854.                     'car_homologate_hertz_codes' => $car_homologate_hertz_codes,
  855.                     'payoutExtras' => $payoutExtras,
  856.                     'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
  857.                     'pointRedemption' => $pointRedemption,
  858.                 ];
  859.                 $twigVariables['baloto'] ?? ($twigVariables['baloto'] = false);
  860.                 $twigVariables['pse'] ?? ($twigVariables['pse'] = true);
  861.                 $twigVariables['safety'] ?? ($twigVariables['safety'] = true);
  862.                 /* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
  863.                 /* Necesitamos crear un arreglo que tenga todos los rangos de IIN asociados a su franquicia y a sus límites de número de tarjeta */
  864.                 $iinRecordsArray $this->getIINRanges($em);
  865.                 $twigVariables["ccranges"] = $iinRecordsArray["ccranges"];
  866.                 $twigVariables["ccfranchises"] = $iinRecordsArray["ccfranchises"];
  867.                 return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/detail.html.twig'), $twigVariables);
  868.             } else {
  869.                 $message $response['error'] ?? 'Ha ocurrido un error inesperado';
  870.                 $returnUrl $twigFolder->pathWithLocale('aviatur_general_homepage');
  871.                 if (true === $requestParams->has('referer') && true === $requestParams->has('http_referer')) {
  872.                     $returnUrl $requestParams->get('http_referer');
  873.                 }
  874.                 return $this->redirect($errorHandler->errorRedirect($returnUrl''$message));
  875.             }
  876.         }
  877.     }
  878.     public function prePaymentStep1Action(Request $requestManagerRegistry $managerRegistryTokenStorageInterface $tokenStorageParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoderCustomerMethodPaymentService $methodPaymentServiceTokenizerService $tokenizerServiceAviaturErrorHandler $errorHandlerTwigFolder $twigFolder)
  879.     {
  880.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  881.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  882.         $session $request->getSession();
  883.         if ($request->isXmlHttpRequest()) {
  884.             $request $request->request;
  885.             $transactionId $session->get($transactionIdSessionName);
  886.             $billingData $request->get('BD');
  887.             $em $managerRegistry->getManager();
  888.             $postData $request->all();
  889.             $publicKey $aviaturEncoder->aviaturRandomKey();
  890.             if (isset($postData['PD']['card_num'])) {
  891.                 $postDataInfo $postData;
  892.                 if (isset($postDataInfo['PD']['cusPOptSelected'])) {
  893.                     $customerLogin $tokenStorage->getToken()->getUser();
  894.                     $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLogintrue);
  895.                     $cardToken $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
  896.                     $postDataInfo['PD']['card_num'] = $cardToken;
  897.                     $postData['PD']['card_num'] = $cardToken;
  898.                 } else {
  899.                     $postDataInfo['PD']['card_num'] = $tokenizerService->getToken($postData['PD']['card_num']);
  900.                 }
  901.                 $postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
  902.             }
  903.             $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
  904.             $formUserInfo = new FormUserInfo();
  905.             $formUserInfo->setInfo($encodedInfo);
  906.             $formUserInfo->setPublicKey($publicKey);
  907.             $em->persist($formUserInfo);
  908.             $em->flush();
  909.             $session->set($transactionId.'[car][user_info]'$formUserInfo->getId());
  910.             if (true !== $session->has($transactionId.'[car][order]')) {
  911.                 if (true === $session->has($transactionId.'[car][detail]')) {
  912.                     $session->set($transactionId.'[car][detail_data]'json_encode($postData));
  913.                     $passangersData $request->get('PI');
  914.                     $passangerNames = [];
  915.                     for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  916.                         $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  917.                         $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  918.                     }
  919.                     $nameWhitelist $em->getRepository(NameWhitelist::class)->findLikeWhitelist($passangerNames);
  920.                     if (== sizeof($nameWhitelist)) {
  921.                         $nameBlacklist $em->getRepository(NameBlacklist::class)->findLikeBlacklist($passangerNames);
  922.                         if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  923.                                 (sizeof($nameBlacklist)) ||
  924.                                 (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  925.                             return $this->json(['error' => 'error''message' => 'nombre inválido']);
  926.                         }
  927.                     }
  928.                     $isFront $session->has('operatorId');
  929.                     if ($isFront) {
  930.                         $customer null;
  931.                         $ordersProduct null;
  932.                     } else {
  933.                         $customer $em->getRepository(Customer::class)->find($billingData['id']);
  934.                         $ordersProduct $em->getRepository(OrderProduct::class)->getOrderProductsPending($customer);
  935.                     }
  936.                     if (null == $ordersProduct) {
  937.                         $session->set($transactionId.'[car][retry]'$aviaturPaymentRetryTimes);
  938.                         $ajaxUrl $this->generateUrl('aviatur_car_prepayment_step_2_secure');
  939.                         return $this->json(['ajax_url' => $ajaxUrl]);
  940.                     } else {
  941.                         $booking = [];
  942.                         $cus = [];
  943.                         foreach ($ordersProduct as $orderProduct) {
  944.                             $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  945.                             $paymentResponse json_decode($productResponse);
  946.                             array_push($booking'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
  947.                             if (isset($paymentResponse->x_approval_code)) {
  948.                                 array_push($cus$paymentResponse->x_approval_code);
  949.                             } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  950.                                 array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  951.                             }
  952.                         }
  953.                         return $this->json([
  954.                             'error' => 'pending payments',
  955.                             'message' => 'pending_payments',
  956.                             'booking' => $booking,
  957.                             'cus' => $cus,
  958.                         ]);
  959.                     }
  960.                 } else {
  961.                     return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo 1')]);
  962.                 }
  963.             } else {
  964.                 $paymentData $request->get('PD');
  965.                 $paymentData json_decode(json_encode($paymentData));
  966.                 $json json_decode($session->get($transactionId.'[car][order]'));
  967.                 if (!is_null($json)) {
  968.                     $json->ajax_url $this->generateUrl('aviatur_car_prepayment_step_2_secure');
  969.                     // reemplazar datos de pago por los nuevos.
  970.                     $oldPostData json_decode($session->get($transactionId.'[car][detail_data]'));
  971.                     if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
  972.                         if (isset($paymentData->cusPOptSelected)) {
  973.                             $customerLogin $tokenStorage->getToken()->getUser();
  974.                             $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLogintrue);
  975.                             $card_num_token $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
  976.                         } else {
  977.                             $card_num_token $tokenizerService->getToken($paymentData->card_num);
  978.                         }
  979.                         $card_values = ['card_num_token' => $card_num_token'card_num' => $paymentData->card_num];
  980.                     }
  981.                     unset($oldPostData->PD);
  982.                     $oldPostData->PD $paymentData;
  983.                     if (isset($card_num_token)) {
  984.                         $oldPostData->PD->card_values $card_values;
  985.                     }
  986.                     $session->set($transactionId.'[car][detail_data]'json_encode($oldPostData));
  987.                     $response = new Response(json_encode($json));
  988.                     $response->headers->set('Content-Type''application/json');
  989.                     return $response;
  990.                 } else {
  991.                     return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
  992.                 }
  993.             }
  994.         } else {
  995.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  996.         }
  997.     }
  998.     public function prePaymentStep2Action(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagAviaturErrorHandler $errorHandlerOrderController $orderControllerTwigFolder $twigFolder)
  999.     {
  1000.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1001.         $currency_code_local null;
  1002.         $total_amount null;
  1003.         $total_amount_local null;
  1004.         $currency null;
  1005.         $pickUpLocationCode null;
  1006.         $returnLocationCode null;
  1007.         $pickUpDate null;
  1008.         $returnDate null;
  1009.         $order = [];
  1010.         $session $request->getSession();
  1011.         if ($request->isXmlHttpRequest()) {
  1012.             $fullRequest $request;
  1013.             $request $request->request;
  1014.             $em $managerRegistry->getManager();
  1015.             $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  1016.             $billingData $request->get('BD');
  1017.             $transactionId $session->get($transactionIdSessionName);
  1018.             $session->set($transactionId.'[car][prepayment_check]'true);
  1019.             $postData json_decode($session->get($transactionId.'[car][detail_data]'));
  1020.             $detailInfo = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
  1021.             $selection json_decode($session->get($transactionId.'[car][selection]'));
  1022.             $car_homologate_hertz_codes json_decode($em->getRepository(Parameter::class)->findOneByName('car_homologate_hertz_codes')->getDescription(), true);
  1023.             $PaymentForm 0;
  1024.             $error true;
  1025.             foreach ($detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $VehVendorAvail) {
  1026.                 $pickUpLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
  1027.                 $returnLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
  1028.                 $pickUpDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['PickUpDateTime'];
  1029.                 $returnDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['ReturnDateTime'];
  1030.                 if ((int) $VehVendorAvail->Info->TPA_Extensions->RPH == (int) explode('-'$postData->SD->selection)[0]) {
  1031.                     foreach ($VehVendorAvail->VehAvails as $VehAvails) {
  1032.                         foreach ($VehAvails->VehAvail as $VehAvail) {
  1033.                             if ((int) $VehAvail->VehAvailInfo->TPA_Extensions->RPH == (int) explode('-'$postData->SD->selection)[1]) {
  1034.                                 $error false;
  1035.                                 $total_amount number_format((float) $VehAvail->VehAvailCore->RentalRate->VehicleCharges->VehicleCharge['Amount'], 0'''');
  1036.                                 $currency = (string) $VehAvail->VehAvailCore->RentalRate->VehicleCharges->VehicleCharge['CurrencyCode'];
  1037.                                 $total_amount_local = (float) $VehAvail->VehAvailCore->TPA_Extensions->LocalRate['RateTotalAmount'];
  1038.                                 $currency_code_local = (string) $VehAvail->VehAvailCore->TPA_Extensions->LocalRate['CurrencyCode'];
  1039.                                 $discountNumbers $VehAvail->VehAvailCore->TPA_Extensions->discountNumbers;
  1040.                                 if (isset($VehAvail->VehAvailCore->TPA_Extensions->LocalRate['ExtraAmount'])) {
  1041.                                     $extra_amount = (float) $VehAvail->VehAvailCore->RentalRate->TotalCharge['ExtraAmount'];
  1042.                                     $extra_amount_local = (float) $VehAvail->VehAvailCore->TPA_Extensions->LocalRate['ExtraAmount'];
  1043.                                 }
  1044.                             }
  1045.                         }
  1046.                     }
  1047.                 }
  1048.             }
  1049.             if ($error) {
  1050.                 return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo 3')]);
  1051.             }
  1052.             $ProviderCarInfo $em->getRepository(ProviderCarCode::class)->findOneBy(['codeProviderCar' => $postData->selectionVendor'isActive' => 1]);
  1053.             if (!$ProviderCarInfo) {
  1054.                 $message 'Ha ocurrido un error inesperado del proveedor';
  1055.                 return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), ''$message));
  1056.             }
  1057.             $PaymentComission json_decode($ProviderCarInfo->getPaymentComission(), true)[0]['comision'];
  1058.             foreach (json_decode($ProviderCarInfo->getInfo(), true) as $providerCar) {
  1059.                 foreach ($discountNumbers->customerReferenceInfo as $discount) {
  1060.                     $referenceNumber rtrim((string) $discount->referenceNumber);
  1061.                     if (isset($car_homologate_hertz_codes[$referenceNumber]) && == $car_homologate_hertz_codes[$referenceNumber]['status']) {
  1062.                         $referenceNumber $car_homologate_hertz_codes[$referenceNumber]['homologate'];
  1063.                     }
  1064.                     if ($referenceNumber == rtrim($providerCar['number']) && == $providerCar['isActive']) {
  1065.                         $PaymentForm = (int) $providerCar['payment'];
  1066.                     }
  1067.                 }
  1068.             }
  1069.             if (== $PaymentForm) {
  1070.                 if (isset($postData->selectionMethod)) {
  1071.                     if (== (int) $postData->selectionMethod) {
  1072.                         $PaymentForm = (int) 1;
  1073.                         $comission $PaymentComission['online'];
  1074.                         $typeRes 'online';
  1075.                     } else {
  1076.                         $PaymentForm = (int) 0;
  1077.                         $comission $PaymentComission['offline'];
  1078.                         $typeRes 'offline';
  1079.                     }
  1080.                 } else {
  1081.                     $PaymentForm = (int) 0;
  1082.                     $comission $PaymentComission['offline'];
  1083.                     $typeRes 'offline';
  1084.                 }
  1085.             } elseif (== $PaymentForm) {
  1086.                 $comission $PaymentComission['online'];
  1087.                 $typeRes 'online';
  1088.             } else {
  1089.                 $comission $PaymentComission['offline'];
  1090.                 $typeRes 'offline';
  1091.             }
  1092.             $rateInfo json_decode($session->get('[car][finantial_rate_info]'), true);
  1093.             if (isset($rateInfo[$currency_code_local])) {
  1094.                 $finantial_rate = ('COP' == $currency_code_local || empty($currency_code_local)) ? $rateInfo[$currency_code_local];
  1095.                 $exchangeValues = [
  1096.                     'MONEDA_ORIGEN' => (string) $currency_code_local,
  1097.                     'TIPO_TASA_CAMBIO' => (string) $rateInfo[$currency_code_local],
  1098.                 ];
  1099.                 $session->set('[car][finantial_rate]'$finantial_rate);
  1100.                 $session->set($transactionId.'[car][exchangeValues]'json_encode($exchangeValues));
  1101.             } elseif ($currency_code_local === 'COP') {
  1102.                 $finantial_rate 1;
  1103.                 $exchangeValues = [
  1104.                     'MONEDA_ORIGEN' => (string) $currency_code_local,
  1105.                     'TIPO_TASA_CAMBIO' => '1',
  1106.                 ];
  1107.                 $session->set('[car][finantial_rate]'$finantial_rate);
  1108.                 $session->set($transactionId.'[car][exchangeValues]'json_encode($exchangeValues));
  1109.             } else {
  1110.                 return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''Error en la conversión, vuelva a intentarlo')]);
  1111.             }
  1112.             // if (isset(json_decode($session->get('[car][finantial_rate_info]'), true)[$currency_code_local])) {
  1113.             //     $finantial_rate = ('COP' == $currency_code_local || empty($currency_code_local)) ? 1 : json_decode($session->get('[car][finantial_rate_info]'), true)[$currency_code_local];
  1114.             //     $exchangeValues = [
  1115.             //         'MONEDA_ORIGEN' => (string) $currency_code_local,
  1116.             //         'TIPO_TASA_CAMBIO' => (string) json_decode($session->get('[car][finantial_rate_info]'), true)[$currency_code_local],
  1117.             //     ];
  1118.             //     $session->set('[car][finantial_rate]', $finantial_rate);
  1119.             //     $session->set($transactionId.'[car][exchangeValues]', json_encode($exchangeValues));
  1120.             // } else {
  1121.             //     return $this->json(['error' => 'fatal', 'message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'Error en la conversi�n, vuelta a intentarlo')]);
  1122.             // }
  1123.             if ('COP' == $currency_code_local || empty($currency_code_local)) {
  1124.                 if (== $PaymentForm && isset($extra_amount)) {
  1125.                     $total_amount $total_amount $extra_amount;
  1126.                 }
  1127.                 $total_amount = ($total_amount $finantial_rate);
  1128.             } else {
  1129.                 if (== $PaymentForm && isset($extra_amount_local)) {
  1130.                     $total_amount_local $total_amount_local $extra_amount_local;
  1131.                 }
  1132.                 $total_amount = ($total_amount_local $finantial_rate);
  1133.             }
  1134.             $session->set($transactionId.'[car][payment_type_res]'$typeRes);
  1135.             $session->set($transactionId.'[car][payment_car_form]'$PaymentForm);
  1136.             $session->set($transactionId.'[car][payment_comission]'$comission);
  1137.             $session->set($transactionId.'[car][total_amount]'$total_amount);
  1138.             $session->set($transactionId.'[car][currency]'$currency);
  1139.             $session->set($transactionId.'[car][total_amount_local]'$total_amount_local);
  1140.             $session->set($transactionId.'[car][currency_code_local]'$currency_code_local);
  1141.             $session->set($transactionId.'[car][providerCarInfo]'$ProviderCarInfo->getInfo());
  1142.             $session->set($transactionId.'[car][pickUpLocationCode]'$pickUpLocationCode);
  1143.             $session->set($transactionId.'[car][returnLocationCode]'$returnLocationCode);
  1144.             $session->set($transactionId.'[car][pickUpDate]'$pickUpDate);
  1145.             $session->set($transactionId.'[car][returnDate]'$returnDate);
  1146.             $pickUpLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
  1147.             $returnLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
  1148.             $pickUpDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['PickUpDateTime'];
  1149.             $returnDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['ReturnDateTime'];
  1150.             if (true !== $session->has($transactionId.'[car][order]')) {
  1151.                 if (true === $session->has($transactionId.'[car][detail]')) {
  1152.                     if (isset($agency)) {
  1153.                         $session->set($transactionIdSessionName$transactionId);
  1154.                         $customerData $em->getRepository(Customer::class)->find($billingData['id']);
  1155.                         $isFront $session->has('operatorId');
  1156.                         if ($isFront) {
  1157.                             $customer $billingData;
  1158.                             $customer['isFront'] = true;
  1159.                             $status 'B2T';
  1160.                         } else {
  1161.                             $customer $customerData;
  1162.                             $status 'waiting';
  1163.                         }
  1164.                         $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('CAR');
  1165.                         $orderIdentifier '{order_product_num}';
  1166.                         $order $orderController->createAction($agency$customer$productType$orderIdentifier$status);
  1167.                         $orderId str_replace('ON'''$order['order']);
  1168.                         $orderEntity $em->getRepository(Order::class)->find($orderId);
  1169.                         $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[car][user_info]'));
  1170.                         $formUserInfo->setOrder($orderEntity);
  1171.                         $em->persist($formUserInfo);
  1172.                         $em->flush();
  1173.                         if ($isFront) {
  1174.                             $order['url'] = $this->generateUrl('aviatur_car_payment_secure');
  1175.                         } else {
  1176.                             $order['url'] = $this->generateUrl('aviatur_car_payment_secure');
  1177.                         }
  1178.                         return $this->json($order);
  1179.                     } else {
  1180.                         return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró la agencia con el dominio: '.$fullRequest->getHost()));
  1181.                     }
  1182.                 } else {
  1183.                     return $this->json(['error' => 'fatal''message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '''No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo 2')]);
  1184.                 }
  1185.             } else {
  1186.                 $order['url'] = $this->generateUrl('aviatur_car_payment_secure');
  1187.                 return $this->json($order);
  1188.             }
  1189.         } else {
  1190.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  1191.         }
  1192.     }
  1193.     public function paymentAction(Request $requestManagerRegistry $managerRegistryRouterInterface $routerParameterBagInterface $parameterBagPayoutExtraService $extraServiceAviaturCarService $carServiceP2PController $p2PControllerWorldPayController $worldPayControllerAviaturErrorHandler $errorHandlerTwigFolder $twigFolderPSEController $PSEControllerSafetypayController $safetypayController, \Swift_Mailer $mailerCashController $cashControllerOrderController $orderControllerExceptionLog $logSave,TokenizerService $tokenizerService,CustomerMethodPaymentService $methodPaymentServiceAviaturLogSave $aviaturlogSave)
  1194.     {
  1195.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1196.         $emailNotification $parameterBag->get('email_notification');
  1197.         $orderProduct = [];
  1198.         $paymentResponse null;
  1199.         $return null;
  1200.         //$safetyData = null;
  1201.         $safetyData = new \stdClass();
  1202.         $array = [];
  1203.         $emissionData = [];
  1204.         $em $managerRegistry->getManager();
  1205.         $session $request->getSession();
  1206.         $transactionId $session->get($transactionIdSessionName);
  1207.         $postData json_decode($session->get($transactionId.'[car][detail_data]'));
  1208.         $orderInfo json_decode($session->get($transactionId.'[car][order]'));
  1209.         $response $session->get($transactionId.'[car][detail]');
  1210.         $domain $request->getHost();
  1211.         $data json_decode($session->get($domain.'[parameters]'), true);
  1212.         $aviaturPaymentIva = (float) $data['aviatur_payment_iva'];
  1213.         $payoutExtrasValues null;
  1214.         $PaymentForm $session->get($transactionId.'[car][payment_car_form]');
  1215.         $amount $session->get($transactionId.'[car][total_amount]');
  1216.         $currency $session->get($transactionId.'[car][currency]');
  1217.         $xml simplexml_load_string((string) $response)->Message->OTA_VehAvailRateRS;
  1218.         if (isset($postData->payoutExtrasSelection)) {
  1219.             $payoutExtrasValues $extraService->getPayoutExtrasValues($postData->payoutExtrasSelection$transactionId);
  1220.         }
  1221.         if (== $PaymentForm || $session->has('operatorId')) {
  1222.             $orderProductId str_replace('PN'''$orderInfo->products);
  1223.             $orderProduct[] = $em->getRepository(OrderProduct::class)->find($orderProductId);
  1224.             $carService->carReservation($orderProduct[0], truetrue);
  1225.             return $this->redirect($this->generateUrl('aviatur_car_confirmation_secure'));
  1226.         } elseif (== $PaymentForm) {
  1227.             $retryCount = (int) $session->get($transactionId.'[car][retry]');
  1228.             if ($retryCount 0) {
  1229.                 //$paymentData = json_decode($session->get($transactionId.'[car][detail_data]'));
  1230.                 $pickUpLocationCode = (string) $xml->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
  1231.                 $returnLocationCode = (string) $xml->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
  1232.                 $pickUpDate = (string) $xml->VehAvailRSCore->VehRentalCore['PickUpDateTime'];
  1233.                 $returnDate = (string) $xml->VehAvailRSCore->VehRentalCore['ReturnDateTime'];
  1234.                 $description 'Autos - '.$pickUpLocationCode.' ('.date('d/m/Y'strtotime($pickUpDate)).') '.$returnLocationCode.' ('.date('d/m/Y'strtotime($returnDate)).') - ' /* . $idContext */;
  1235.                 $orderProductCode $session->get($transactionId.'[car][order]');
  1236.                 $orderProduct null;
  1237.                 if (isset($orderProductCode) && isset(json_decode($orderProductCode)->products)) {
  1238.                     $orderProductId str_replace('PN'''json_decode($orderProductCode)->products);
  1239.                     $orderProduct[] = $em->getRepository(OrderProduct::class)->find($orderProductId);
  1240.                     $paymentData $postData->PD;
  1241.                     $customer $em->getRepository(Customer::class)->find($postData->BD->id);
  1242.                     $carService->carReservation($orderProduct[0], truefalse);
  1243.                     if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
  1244.                         $array = [
  1245.                             'x_currency_code' => (string) $currency,
  1246.                             'x_amount' => round(number_format($amount2'.''')),
  1247.                             'x_tax' => number_format($amount $aviaturPaymentIva2'.'''),
  1248.                             'x_amount_base' => number_format($amount * ($aviaturPaymentIva), 2'.'''),
  1249.                             'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  1250.                             'x_first_name' => $customer->getFirstname(),
  1251.                             'x_last_name' => $customer->getLastname(),
  1252.                             'x_description' => $description,
  1253.                             'x_city' => $customer->getCity()->getIatacode(),
  1254.                             'x_country_id' => $customer->getCountry()->getIatacode(),
  1255.                             'x_cust_id' => $customer->getDocumentType()->getPaymentcode().' '.$customer->getDocumentnumber(),
  1256.                             'x_address' => $customer->getAddress(),
  1257.                             'x_phone' => $customer->getPhone(),
  1258.                             'x_email' => $customer->getEmail(),
  1259.                             'x_card_num' => $paymentData->card_num,
  1260.                             'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
  1261.                             'x_card_code' => $paymentData->card_code,
  1262.                             'x_differed' => $paymentData->differed,
  1263.                             'x_client_id' => $postData->BD->id,
  1264.                             'product_type' => 'car',
  1265.                             'x_cantidad' => $postData->PI->person_count_1,
  1266.                             'administrative_base' => 0,
  1267.                             'administrative_amount_tax' => 0,
  1268.                             'admin_amount' => 0,
  1269.                             'franchise' => $paymentData->franquise,
  1270.                             'worldpay_validate' => true,
  1271.                         ];
  1272.                         if (isset($paymentData->card_values)) {
  1273.                             $array['card_values'] = (array) $paymentData->card_values;
  1274.                         }
  1275.                         if ('p2p' == $paymentData->type) {
  1276.                             if (isset($paymentData->cusPOptSelected)) {
  1277.                                 $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  1278.                             }
  1279.                             if (isset($postData->PD->savePaymProc)) {
  1280.                                 $array['x_provider_id'] = 1;
  1281.                             } elseif (isset($paymentData->cusPOptSelected)) {
  1282.                                 if (isset($paymentData->cusPOptSelectedStatus)) {
  1283.                                     if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
  1284.                                         $array['x_provider_id'] = 1;
  1285.                                     } else {
  1286.                                         $array['x_provider_id'] = 2;
  1287.                                     }
  1288.                                 } else {
  1289.                                     $array['x_provider_id'] = 2;
  1290.                                 }
  1291.                             }
  1292.                         }
  1293.                         if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  1294.                             foreach ($payoutExtrasValues as $payoutExtraValues) {
  1295.                                 $array['x_amount'] += round((float) $payoutExtraValues->values->fare->total);
  1296.                                 $array['x_tax'] += round((float) $payoutExtraValues->values->fare->tax);
  1297.                                 $array['x_amount_base'] += round((float) $payoutExtraValues->values->fare->base);
  1298.                             }
  1299.                         }
  1300.                         $payoutExtrasValues $extraService->setPayoutExtrasAsProcessed($transactionId);
  1301.                         if ('p2p' == $paymentData->type) {
  1302.                             $paymentResponse $p2PController->placetopayAction($parameterBag,$tokenizerService,$methodPaymentService,$mailer,$aviaturlogSave$array);
  1303.                             $return $this->redirect($this->generateUrl('aviatur_car_payment_p2p_return_url_secure', [], true));
  1304.                         } elseif ('world' == $paymentData->type) {
  1305.                             $array['city'] = $customer->getCity()->getIatacode();
  1306.                             $array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
  1307.                             $paymentResponse $worldPayController->worldAction($request$mailer$aviaturlogSave$methodPaymentService$parameterBag$array);
  1308.                             $return $this->redirect($this->generateUrl('aviatur_car_payment_world_return_url_secure', [], true));
  1309.                         }
  1310.                         unset($array['x_client_id']);
  1311.                         if (null != $paymentResponse) {
  1312.                             return $return;
  1313.                         } else {
  1314.                             $orderProduct[0]->setStatus('pending');
  1315.                             $em->persist($orderProduct[0]);
  1316.                             $em->flush();
  1317.                             return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '''No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
  1318.                         }
  1319.                     } elseif ('pse' == $paymentData->type) {
  1320.                         $array = ['x_doc_num' => $customer->getDocumentnumber(),
  1321.                             'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  1322.                             'x_first_name' => $customer->getFirstname(),
  1323.                             'x_last_name' => $customer->getLastname(),
  1324.                             'x_company' => 'Aviatur',
  1325.                             'x_email' => $customer->getEmail(),
  1326.                             'x_address' => $customer->getAddress(),
  1327.                             'x_city' => $customer->getCity()->getDescription(),
  1328.                             'x_province' => $customer->getCity()->getDescription(),
  1329.                             'x_country' => $customer->getCountry()->getDescription(),
  1330.                             'x_phone' => $customer->getPhone(),
  1331.                             'x_mobile' => $customer->getCellphone(),
  1332.                             'x_bank' => $paymentData->pse_bank,
  1333.                             'x_type' => $paymentData->pse_type,
  1334.                             'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  1335.                             'x_description' => $description,
  1336.                             'x_currency' => (string) $currency,
  1337.                             'x_total_amount' => number_format($amount2'.'''),
  1338.                             'x_tax_amount' => number_format($amount $aviaturPaymentIva2'.'''),
  1339.                             'x_devolution_base' => number_format($amount * ($aviaturPaymentIva), 2'.'''),
  1340.                             'x_tax' => number_format(round((float) (0)), 2'.'''),
  1341.                             'x_tip_amount' => number_format(round((float) (0)), 2'.'''),
  1342.                             'x_cantidad' => $postData->PI->person_count_1,
  1343.                             'product_type' => 'car',
  1344.                         ];
  1345.                         if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  1346.                             foreach ($payoutExtrasValues as $payoutExtraValues) {
  1347.                                 $array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
  1348.                                 $array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
  1349.                                 $array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
  1350.                             }
  1351.                         }
  1352.                         $payoutExtrasValues $extraService->setPayoutExtrasAsProcessed($transactionId);
  1353.                         $paymentResponse $PSEController->sendPaymentAction($request$session$router$parameterBag$mailer$orderController$array$orderProduct);
  1354.                         if (!isset($paymentResponse->error)) {
  1355.                             switch ($paymentResponse->createTransactionResult->returnCode) {
  1356.                                 case 'SUCCESS':
  1357.                                     return $this->redirect($paymentResponse->createTransactionResult->bankURL);
  1358.                                 case 'FAIL_EXCEEDEDLIMIT':
  1359.                                     return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '');
  1360.                                 case 'FAIL_BANKUNREACHEABLE':
  1361.                                     return $this->redirect($this->generateUrl('aviatur_car_retry_secure'), '');
  1362.                                 default:
  1363.                                     return $this->redirect($this->generateUrl('aviatur_car_retry_secure'), '');
  1364.                             }
  1365.                         } else {
  1366.                             return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), 'Error al procesar el pago''Ocurrió un problema al intentar crear tu transacción, '.$paymentResponse->error));
  1367.                         }
  1368.                     } elseif ('safety' == $paymentData->type) {
  1369.                         $transactionUrl $this->generateUrl('aviatur_payment_safetypay', [], true);
  1370.                         $array = ['x_doc_num' => $customer->getDocumentnumber(),
  1371.                             'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  1372.                             'x_first_name' => $customer->getFirstname(),
  1373.                             'x_last_name' => $customer->getLastname(),
  1374.                             'x_company' => 'Aviatur',
  1375.                             'x_email' => $customer->getEmail(),
  1376.                             'x_address' => $customer->getAddress(),
  1377.                             'x_city' => $customer->getCity()->getDescription(),
  1378.                             'x_province' => $customer->getCity()->getDescription(),
  1379.                             'x_country' => $customer->getCountry()->getDescription(),
  1380.                             'x_phone' => $customer->getPhone(),
  1381.                             'x_mobile' => $customer->getCellphone(),
  1382.                             'x_reference' => $orderInfo->products,
  1383.                             'x_description' => $description,
  1384.                             'x_currency' => $currency,
  1385.                             'x_total_amount' => number_format($amount2'.'''),
  1386.                             'x_tax_amount' => number_format($amount $aviaturPaymentIva2'.'''),
  1387.                             'x_devolution_base' => number_format($amount * ($aviaturPaymentIva), 2'.'''),
  1388.                             'x_tip_amount' => number_format(round(0), 2'.'''),
  1389.                             'x_payment_data' => $paymentData->type,
  1390.                             'x_type_description' => 'car',
  1391.                             'x_cantidad' => $postData->PI->person_count_1,
  1392.                         ];
  1393.                         if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  1394.                             foreach ($payoutExtrasValues as $payoutExtraValues) {
  1395.                                 $array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
  1396.                                 $array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
  1397.                                 $array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
  1398.                             }
  1399.                         }
  1400.                         $payoutExtrasValues $extraService->setPayoutExtrasAsProcessed($transactionId);
  1401.                         $parametMerchant = [
  1402.                             'MerchantSalesID' => $array['x_reference'],
  1403.                             'Amount' => $array['x_total_amount'],
  1404.                             'transactionUrl' => $transactionUrl,
  1405.                             'dataTrans' => $array,
  1406.                         ];
  1407.                         $safeTyPay $safetypayController->safetyAction($router$parameterBag$mailer$parametMerchant$array);
  1408.                         if ('ok' == $safeTyPay['status']) {
  1409.                             return $this->redirect($safeTyPay['response']);
  1410.                         } else {
  1411.                             $safetyData->x_booking $array['x_booking'];
  1412.                             $safetyData->x_first_name $array['x_first_name'];
  1413.                             $safetyData->x_last_name $array['x_last_name'];
  1414.                             $safetyData->x_doc_num $array['x_doc_num'];
  1415.                             $safetyData->x_reference $array['x_reference'];
  1416.                             $safetyData->x_description $array['x_description'];
  1417.                             $safetyData->x_total_amount $array['x_total_amount'];
  1418.                             $safetyData->x_email $array['x_email'];
  1419.                             $safetyData->x_address $array['x_address'];
  1420.                             $safetyData->x_phone $array['x_phone'];
  1421.                             $safetyData->x_type_description $array['x_type_description'];
  1422.                             $safetyData->x_resultSafetyPay $safeTyPay;
  1423.                             $mailInfo print_r($safetyDatatrue).'<br>'.print_r($responsetrue);
  1424.                             $message = (new \Swift_Message())
  1425.                                     ->setContentType('text/html')
  1426.                                     ->setFrom($session->get('emailNoReply'))
  1427.                                     ->setTo($emailNotification)
  1428.                                     ->setSubject('Error Creación Token SafetyPay Car'.$safetyData->x_reference)
  1429.                                     ->setBody($mailInfo);
  1430.                             $mailer->send($message);
  1431.                             return $this->redirect($this->generateUrl('aviatur_Car_payment_rejected_secure'));
  1432.                         }
  1433.                     } elseif ('cash' == $paymentData->type) {
  1434.                         $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  1435.                         $agencyName $agency->getOfficeId();
  1436.                         $orderInfo json_decode($session->get($transactionId.'[car][order]'));
  1437.                         $array['x_officeId'] = $agencyName;
  1438.                         $array['x_doc_num'] = $customer->getDocumentnumber();
  1439.                         $array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
  1440.                         $array['x_first_name'] = $this->unaccent($customer->getFirstname());
  1441.                         $array['x_last_name'] = $this->unaccent($customer->getLastname());
  1442.                         $array['x_company'] = 'Aviatur';
  1443.                         $array['x_email'] = $customer->getEmail();
  1444.                         $array['x_address'] = $customer->getAddress();
  1445.                         $array['x_city'] = $customer->getCity()->getDescription();
  1446.                         $array['x_province'] = $customer->getCity()->getDescription();
  1447.                         $array['x_country'] = $customer->getCountry()->getDescription();
  1448.                         $array['x_phone'] = $customer->getPhone();
  1449.                         $array['x_mobile'] = $customer->getCellphone();
  1450.                         $array['x_payment_data'] = $paymentData->type;
  1451.                         $array['x_reference'] = $orderInfo->products;
  1452.                         $array['x_description'] = $description;
  1453.                         $array['x_booking'] = $orderProduct[0]->getBooking();
  1454.                         $array['x_total_amount'] = number_format(round((float) $amount), 0'.''');
  1455.                         $array['x_tax_amount'] = number_format(round((float) (0)), 2'.''');
  1456.                         $array['x_devolution_base'] = number_format(round((float) (0)), 2'.''');
  1457.                         $array['x_tip_amount'] = number_format(round(0), 0'.''');
  1458.                         $array['x_currency'] = $currency;
  1459.                         $array['x_type_description'] = $orderProduct[0]->getDescription();
  1460.                         $array['x_cantidad'] = $postData->PI->person_count_1;
  1461.                         if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
  1462.                             foreach ($payoutExtrasValues as $payoutExtraValues) {
  1463.                                 $array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
  1464.                             }
  1465.                         }
  1466.                         $payoutExtrasValues $extraService->setPayoutExtrasAsProcessed($transactionId);
  1467.                         $fecha $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
  1468.                         $fechalimite $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
  1469.                         $nuevafecha strtotime('+2 hour'strtotime($fecha));
  1470.                         $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  1471.                         if (strcmp($fechavigencia$fechalimite) > 0) {
  1472.                             $fechavigencia $fechalimite;
  1473.                         }
  1474.                         $array['x_fechavigencia'] = $fechavigencia;
  1475.                         $cashPay $cashController->cashAction($aviaturlogSave$array);
  1476.                         $orderController->updatePaymentAction($orderProduct[0]);
  1477.                         if ('ok' == $cashPay->status) {
  1478.                             $session->set($transactionId.'[car][cash_result]'json_encode($cashPay));
  1479.                             return $this->redirect($this->generateUrl('aviatur_car_payment_success_secure'));
  1480.                         } else {
  1481.                             $toEmails = ['soportepagoelectronico@aviatur.com.co''soptepagelectronic@aviatur.com'$emailNotification];
  1482.                             $emissionData['x_booking'] = $array['x_booking'];
  1483.                             $emissionData['x_first_name'] = $array['x_first_name'];
  1484.                             $emissionData['x_last_name'] = $array['x_last_name'];
  1485.                             $emissionData['x_doc_num'] = $array['x_doc_num'];
  1486.                             $emissionData['x_reference'] = $array['x_reference'];
  1487.                             $emissionData['x_description'] = $array['x_description'];
  1488.                             $emissionData['x_total_amount'] = $array['x_total_amount'];
  1489.                             $emissionData['x_email'] = $array['x_email'];
  1490.                             $emissionData['x_address'] = $array['x_address'];
  1491.                             $emissionData['x_phone'] = $array['x_phone'];
  1492.                             $emissionData['x_type_description'] = $array['x_type_description'];
  1493.                             $emissionData['x_error'] = $cashPay->status;
  1494.                             $mailInfo print_r($emissionDatatrue).'<br>'.print_r($cashPaytrue);
  1495.                             $message = (new \Swift_Message())
  1496.                                     ->setContentType('text/html')
  1497.                                     ->setFrom($session->get('emailNoReply'))
  1498.                                     ->setTo($toEmails)
  1499.                                     ->setBcc('arthur.picerna@aviatur.com')
  1500.                                     ->setSubject('Error Creación Transacción Baloto'.$emissionData['x_reference'].' - '.$orderProduct[0]->getOrder()->getAgency()->getName())
  1501.                                     ->setBody($mailInfo);
  1502.                             $mailer->send($message);
  1503.                             $session->set($transactionId.'[car][retry]'$retryCount 1);
  1504.                             return $this->redirect($this->generateUrl('aviatur_car_payment_rejected_secure'));
  1505.                         }
  1506.                     } else {
  1507.                         return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '''El tipo de pago es invalido'));
  1508.                     }
  1509.                 } else {
  1510.                     $logSave->log(
  1511.                         'Error fatal',
  1512.                         'No se encontró un order product en sesión',
  1513.                         null,
  1514.                         false
  1515.                     );
  1516.                 }
  1517.             } else {
  1518.                 return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''No hay mas intentos permitidos'));
  1519.             }
  1520.         }
  1521.     }
  1522.     public function p2pCallbackAction(Request $requestManagerRegistry $managerRegistryTokenStorageInterface $tokenStorageParameterBagInterface $parameterBagPayoutExtraService $extraServiceAviaturMailer $aviaturMailerCustomerMethodPaymentService $methodPaymentServiceAviaturEncoder $aviaturEncoderAviaturCarService $carServiceValidateSanctions $validateSanctionsAviaturErrorHandler $errorHandlerOrderController $orderController)
  1523.     {
  1524.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1525.         $response = [];
  1526.         $em $managerRegistry->getManager();
  1527.         $session $request->getSession();
  1528.         $transactionId $session->get($transactionIdSessionName);
  1529.         $orderProductCode $session->get($transactionId.'[car][order]');
  1530.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1531.         $orderProduct $em->getRepository(OrderProduct::class)->find($productId);
  1532.         $agency $orderProduct->getOrder()->getAgency();
  1533.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1534.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1535.         $jsonSendEmail $em->getRepository(Parameter::class)->findOneByName('send_email');
  1536.         if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
  1537.             $email json_decode($jsonSendEmail->getDescription())->email->CallBack;
  1538.         }
  1539.         $reference str_replace('{"order":"'''$orderProductCode);
  1540.         $reference str_replace('","products":"''-'$reference);
  1541.         $reference str_replace('"}'''$reference);
  1542.         $references $reference;
  1543.         $bookings $orderProduct->getBooking();
  1544.         if (null != $decodedResponse) {
  1545.             $twig '';
  1546.             $additionalQS '';
  1547.             $retryCount = (int) $session->get($transactionId.'[car][retry]');
  1548.             switch ($decodedResponse->x_response_code) {
  1549.                 case isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber):
  1550.                     //rechazado cybersource
  1551.                     $parameters $em->getRepository(Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  1552.                     if ($parameters) {
  1553.                         if (== $parameters->getValue()) {
  1554.                             if (== $decodedResponse->x_response_code) {
  1555.                                 $postData json_decode($session->get($transactionId.'[car][detail_data]'));
  1556.                                 if (isset($postData->PD->cusPOptSelected)) {
  1557.                                     if (isset($postData->PD->cusPOptSelectedStatus)) {
  1558.                                         if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  1559.                                             $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  1560.                                             $customerLogin $tokenStorage->getToken()->getUser();
  1561.                                             $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1562.                                         }
  1563.                                     }
  1564.                                 }
  1565.                                 if (isset($postData->PD->savePaymProc)) {
  1566.                                     $customerLogin $tokenStorage->getToken()->getUser();
  1567.                                     $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1568.                                 }
  1569.                             }
  1570.                         }
  1571.                     }
  1572.                     $twig 'aviatur_car_payment_rejected_secure';
  1573.                     // no break
  1574.                 case 3:// pendiente p2p
  1575.                     $twig '' != $twig $twig 'aviatur_car_payment_pending_secure';
  1576.                     $updateOrder $orderController->updatePaymentAction($orderProduct);
  1577.                     $orderProduct->setUpdatingdate(new \DateTime());
  1578.                     $em->persist($orderProduct);
  1579.                     $em->flush();
  1580.                     $retryCount 1;
  1581.                     break;
  1582.                 case 0:// error p2p
  1583.                     $twig 'aviatur_car_payment_error_secure'//no existe?
  1584.                     if (isset($email)) {
  1585.                         $from $session->get('emailNoReply');
  1586.                         $error $twig;
  1587.                         $subject $orderProduct->getDescription().':Error en el proceso de pago';
  1588.                         $body '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  1589.                         $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  1590.                     }
  1591.                     // no break
  1592.                 case 2:// rechazada p2p
  1593.                     $twig '' != $twig $twig 'aviatur_car_payment_rejected_secure';
  1594.                     $orderProduct->setResume('No reservation');
  1595.                     if (isset($email)) {
  1596.                         $from $session->get('emailNoReply');
  1597.                         $error $twig;
  1598.                         $subject $orderProduct->getDescription().':Transacción rechazada';
  1599.                         $body '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
  1600.                         $aviaturMailer->sendEmailGeneral($from$email$subject$body);
  1601.                     }
  1602.                     break;
  1603.                 case 1:// aprobado p2p
  1604.                     $decodedRequest->product_type 'car';
  1605.                     $decodedResponse->product_type 'car';
  1606.                     $encodedRequest $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
  1607.                     $encodedResponse $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
  1608.                     $orderProduct->setPayrequest($encodedRequest);
  1609.                     $orderProduct->setPayresponse($encodedResponse);
  1610.                     $updateOrder $orderController->updatePaymentAction($orderProduct);
  1611.                     $postData json_decode($session->get($transactionId.'[car][detail_data]'));
  1612.                     if (isset($postData->PD->cusPOptSelected)) {
  1613.                         if (isset($postData->PD->cusPOptSelectedStatus)) {
  1614.                             if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
  1615.                                 $postData->PD->cusPOptSelectedStatus 'ACTIVE';
  1616.                                 $customerLogin $tokenStorage->getToken()->getUser();
  1617.                                 $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1618.                             }
  1619.                         }
  1620.                     }
  1621.                     if (isset($postData->PD->savePaymProc)) {
  1622.                         $customerLogin $tokenStorage->getToken()->getUser();
  1623.                         $methodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($postData), true));
  1624.                     }
  1625.                     $twig 'aviatur_car_payment_success_secure';
  1626.                     //aviatur_car_payment_success_secure
  1627.                     //aviatur_car_confirmation_secure
  1628.                     if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
  1629.                         $additionalQS '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
  1630.                     }
  1631.                     $carService->carReservation($orderProductfalsetrue);
  1632.                     if (isset($response['error'])) {
  1633.                         $orderProduct->setResume('Book_in_basket');
  1634.                     }
  1635.                     $em->persist($orderProduct);
  1636.                     $em->flush();
  1637.                     break;
  1638.             }
  1639.             $extraService->payoutExtrasCallback($twig$transactionId'car'$agency);
  1640.             $session->set($transactionId.'[car][retry]'$retryCount 1);
  1641.             $urlResume $this->generateUrl($twig);
  1642.             $urlResume .= $additionalQS;
  1643.             //////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
  1644.             if ($session->has('Marked_name') && $session->has('Marked_document')) {
  1645.                 $product 'Autos';
  1646.                 $validateSanctions->sendMarkedEmail($orderProductCode$session$agency$orderProduct$transactionId$product);
  1647.             }
  1648.             ////////////////////////////////////////////////////////////////////////////////////
  1649.             return $this->redirect($urlResume);
  1650.         } else {
  1651.             $orderProduct->setStatus('pending');
  1652.             $em->persist($orderProduct);
  1653.             $em->flush();
  1654.             return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  1655.         }
  1656.     }
  1657.     public function pseCallbackAction(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagPayoutExtraService $extraServiceAviaturEncoder $aviaturEncoderAviaturCarService $carServiceAviaturErrorHandler $errorHandlerTwigFolder $twigFolderPSEController $PSEControllerOrderController $orderController$transaction)
  1658.     {
  1659.         $status null;
  1660.         $twig null;
  1661.         $em $managerRegistry->getManager();
  1662.         $session $request->getSession();
  1663.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1664.         $transactionId $session->get($transactionIdSessionName);
  1665.         $orderProductCode $session->get($transactionId.'[car][order]');
  1666.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1667.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1668.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1669.         if ($session->has('agencyId')) {
  1670.             $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  1671.         } else {
  1672.             $agency $em->getRepository(Agency::class)->find(1);
  1673.         }
  1674.         $paymentMethod $em->getRepository(PaymentMethod::class)->findOneByCode('pse');
  1675.         $paymentMethodAgency $em->getRepository(PaymentMethodAgency::class)->findOneBy(['agency' => $agency'paymentMethod' => $paymentMethod]);
  1676.         $tranKey $paymentMethodAgency->getTrankey();
  1677.         $decodedUrl json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
  1678.         $transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
  1679.         $orders $decodedUrl['x_orders'];
  1680.         if (isset($orders['car'])) {
  1681.             $carOrders explode('+'$orders['car']);
  1682.             $orderProductCode $carOrders[0];
  1683.             $productId $carOrders[0];
  1684.             $retryCount 1;
  1685.         } else {
  1686.             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontro identificador de la transacción'));
  1687.         }
  1688.         //$orderProduct = $em->getRepository(OrderProduct::class)->find($productId);
  1689.         if (empty($orderProduct)) {
  1690.             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1691.         } else {
  1692.             if ('approved' == $orderProduct->getStatus()) {
  1693.                 return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  1694.             } else {
  1695.                 $agency $orderProduct->getOrder()->getAgency();
  1696.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1697.                 if (isset($decodedResponse->createTransactionResult)) {
  1698.                     $additionalQS '';
  1699.                     $pseTransactionId $decodedResponse->createTransactionResult->transactionID;
  1700.                     $paymentResponse $PSEController->pseCallbackAction($pseTransactionId);
  1701.                     if (!isset($paymentResponse->error)) {
  1702.                         if (!$session->has($transactionId.'[car][detail_data]')) {
  1703.                             $message 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
  1704.                             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra'$message));
  1705.                         }
  1706.                         $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  1707.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1708.                         $orderProduct->setUpdatingdate(new \DateTime());
  1709.                         $em->persist($orderProduct);
  1710.                         $em->flush();
  1711.                         if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
  1712.                             switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
  1713.                                 case 'OK':
  1714.                                     $twig 'aviatur_car_payment_success_secure';
  1715.                                     //aviatur_car_confirmation_secure
  1716.                                     $status 'approved';
  1717.                                     if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
  1718.                                         $additionalQS '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->totalAmount;
  1719.                                     }
  1720.                                     break;
  1721.                                 case 'PENDING':
  1722.                                     $twig 'aviatur_car_payment_pending_secure';
  1723.                                     $status 'pending';
  1724.                                     break;
  1725.                                 case 'NOT_AUTHORIZED':
  1726.                                     $twig 'aviatur_car_payment_error_secure';
  1727.                                     $status 'rejected';
  1728.                                     break;
  1729.                                 case 'FAILED':
  1730.                                     $twig 'aviatur_car_payment_error_secure';
  1731.                                     $status 'failed';
  1732.                                     break;
  1733.                             }
  1734.                             $orderProduct->setStatus($status);
  1735.                             $orderProduct->getOrder()->setStatus($status);
  1736.                             $orderProduct->setUpdatingdate(new \DateTime());
  1737.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1738.                             $em->persist($orderProduct);
  1739.                             $em->flush();
  1740.                             $extraService->payoutExtrasCallback($twig$transactionId'car'$agency);
  1741.                             if ('approved' == $status) {
  1742.                                 $orderController->updatePaymentAction($orderProductfalsenull);
  1743.                                 $carService->carReservation($orderProductfalsetrue);
  1744.                             }
  1745.                         } elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
  1746.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1747.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1748.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1749.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1750.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1751.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1752.                             transacción <#CUS> .';
  1753.                             $orderProduct->setUpdatingdate(new \DateTime());
  1754.                             $em->persist($orderProduct);
  1755.                             $em->flush();
  1756.                             $twig 'aviatur_car_payment_error_secure';
  1757.                         }
  1758.                         if ($session->has($transactionId.'[car][retry]')) {
  1759.                             $session->set($transactionId.'[car][retry]'$retryCount 1);
  1760.                         }
  1761.                         $urlResume $this->generateUrl($twig);
  1762.                         $urlResume .= $additionalQS;
  1763.                         return $this->redirect($urlResume);
  1764.                     } else {
  1765.                         $decodedResponse->getTransactionInformationResult $paymentResponse;
  1766.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1767.                         $orderProduct->setUpdatingdate(new \DateTime());
  1768.                         $em->persist($orderProduct);
  1769.                         $em->flush();
  1770.                         return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  1771.                     }
  1772.                 } else {
  1773.                     return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción'));
  1774.                 }
  1775.             }
  1776.         }
  1777.     }
  1778.     public function safetyCallbackOkAction(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagPayoutExtraService $extraServiceAviaturEncoder $aviaturEncoderAviaturCarService $carServiceTwigFolder $twigFolderAviaturErrorHandler $errorHandlerOrderController $orderController)
  1779.     {
  1780.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1781.         $em $managerRegistry->getManager();
  1782.         $session $request->getSession();
  1783.         $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  1784.         if (true === $session->has($transactionIdSessionName)) {
  1785.             $transactionId $session->get($transactionIdSessionName);
  1786.             if (true === $session->has($transactionId.'[car][order]')) {
  1787.                 $orderProductCode $session->get($transactionId.'[car][order]');
  1788.                 $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1789.                 $orderProduct $em->getRepository(OrderProduct::class)->find($productId);
  1790.                 $postData json_decode($session->get($transactionId.'[car][detail_data]'));
  1791.                 $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1792.                 $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1793.                 $payError $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
  1794.                 $notifyError $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
  1795.                 if (isset($decodedResponse->payResponse->OperationResponse)) {
  1796.                     $additionalQS '';
  1797.                     if (=== $payError) {
  1798.                         $retryCount = (int) $session->get($transactionId.'[car][retry]');
  1799.                         if (== $notifyError) {
  1800.                             $twig 'aviatur_car_payment_success_secure';
  1801.                             $status 'approved';
  1802.                             if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
  1803.                                 $additionalQS '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
  1804.                             }
  1805.                             $orderProduct->setStatus($status);
  1806.                             $orderProduct->getOrder()->setStatus($status);
  1807.                             $orderProduct->setUpdatingdate(new \DateTime());
  1808.                             $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1809.                             $em->persist($orderProduct);
  1810.                             $em->flush();
  1811.                             $orderController->updatePaymentAction($orderProduct);
  1812.                             $extraService->payoutExtrasCallback($twig$transactionId'car'$agency);
  1813.                             if ('approved' == $status) {
  1814.                                 $carService->carReservation($orderProductfalsetrue);
  1815.                             }
  1816.                         } else {
  1817.                             echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1818.                             PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1819.                             unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1820.                             forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1821.                             comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1822.                             inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1823.                             transacción <#CUS> .';
  1824.                             $orderProduct->setUpdatingdate(new \DateTime());
  1825.                             $em->persist($orderProduct);
  1826.                             $em->flush();
  1827.                             $twig 'aviatur_car_payment_error_secure';
  1828.                         }
  1829.                         $session->set($transactionId.'[car][retry]'$retryCount 1);
  1830.                         $urlResume $this->generateUrl($twig);
  1831.                         $urlResume .= $additionalQS;
  1832.                         return $this->redirect($urlResume);
  1833.                     } else {
  1834.                         $decodedResponse->payResponse->OperationResponse->ListOfOperations $paymentResponse;
  1835.                         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1836.                         $orderProduct->setUpdatingdate(new \DateTime());
  1837.                         $em->persist($orderProduct);
  1838.                         $em->flush();
  1839.                         return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Ocurrió un error al consultar el estado de la transacción'));
  1840.                     }
  1841.                 } else {
  1842.                     return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró información de la transacción, por favor comuniquese con nosotros'));
  1843.                 }
  1844.             } else {
  1845.                 return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1846.             }
  1847.         } else {
  1848.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró identificador de la transacción'));
  1849.         }
  1850.     }
  1851.     public function safetyCallbackErrorAction(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoderAviaturErrorHandler $errorHandlerTwigFolder $twigFolder)
  1852.     {
  1853.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1854.         $status null;
  1855.         $fullRequest $request;
  1856.         $em $managerRegistry->getManager();
  1857.         $session $fullRequest->getSession();
  1858.         $transactionId $session->get($transactionIdSessionName);
  1859.         $retryCount = (int) $session->get($transactionId.'[car][retry]');
  1860.         $orderProductCode json_decode($session->get($transactionId.'[car][order]'));
  1861.         $productId str_replace('PN'''$orderProductCode->products);
  1862.         $orderProduct $em->getRepository(OrderProduct::class)->find($productId);
  1863.         $payResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  1864.         $payRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
  1865.         $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
  1866.         if ('baloto' == $payRequest->dataTransf->x_payment_data) {
  1867.             $status 'pending';
  1868.             $payResponse->dataTransf->x_response_code 100;
  1869.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
  1870.         } elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
  1871.             $status 'rejected';
  1872.             $payResponse->dataTransf->x_response_code 100;
  1873.             $payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
  1874.         }
  1875.         $orderProduct->setStatus($status);
  1876.         $orderProduct->setUpdatingdate(new \DateTime());
  1877.         $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1878.         $order $em->getRepository(Order::class)->find($orderProduct->getOrder()->getId());
  1879.         $order->setStatus($status);
  1880.         $em->persist($order);
  1881.         $em->persist($orderProduct);
  1882.         $em->flush();
  1883.         if (!$session->has($transactionId.'[car][order]')) {
  1884.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''No se encontró orden asociada a este pago'));
  1885.         }
  1886.         $session->set($transactionId.'[car][retry]'$retryCount 1);
  1887.         return $this->redirect($this->generateUrl('aviatur_car_payment_rejected_secure'));
  1888.     }
  1889.     public function worldCallbackAction(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoderAviaturCarService $carServiceOrderController $orderControllerAviaturErrorHandler $errorHandler)
  1890.     {
  1891.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1892.         $response = [];
  1893.         $em $managerRegistry->getManager();
  1894.         $session $request->getSession();
  1895.         $transactionId $session->get($transactionIdSessionName);
  1896.         $orderProductCode $session->get($transactionId.'[car][order]');
  1897.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1898.         $orderProduct $em->getRepository(OrderProduct::class)->find($productId);
  1899.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1900.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  1901.         if (null != $decodedResponse) {
  1902.             $twig 'aviatur_car_payment_rejected_secure';
  1903.             $retryCount = (int) $session->get($transactionId.'[car][retry]');
  1904.             if (isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber)) {
  1905.                 $decodedResponse->x_response_code_case 99;
  1906.             } else {
  1907.                 if (isset($decodedResponse->resultado->reply->orderStatus->payment->lastEvent)) {
  1908.                     $decodedResponse->x_response_code_case = (string) $decodedResponse->resultado->reply->orderStatus->payment->lastEvent;
  1909.                 } elseif (isset($decodedResponse->resultado->reply->orderStatusEvent->payment->lastEvent)) {
  1910.                     $decodedResponse->x_response_code_case 'REFUSED';
  1911.                 } elseif (isset($decodedResponse->resultado->reply->error)) {
  1912.                     $decodedResponse->x_response_code_case 'REFUSED';
  1913.                 }
  1914.             }
  1915.             switch ($decodedResponse->x_response_code_case) {
  1916.                 case 'ERROR':
  1917.                     $twig 'aviatur_car_payment_error_secure';
  1918.                     break;
  1919.                 case 'AUTHORISED':
  1920.                     $decodedRequest->product_type 'car';
  1921.                     $decodedResponse->product_type 'car';
  1922.                     $encodedRequest $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
  1923.                     $encodedResponse $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
  1924.                     $orderProduct->setPayrequest($encodedRequest);
  1925.                     $orderProduct->setPayresponse($encodedResponse);
  1926.                     $twig 'aviatur_car_payment_success_secure';
  1927.                     if (isset($response['error'])) {
  1928.                         $orderProduct->setResume('Book_in_basket');
  1929.                     }
  1930.                     $em->persist($orderProduct);
  1931.                     $em->flush();
  1932.                     $carService->carReservation($orderProductfalsetrue);
  1933.                     break;
  1934.                 case 'REFUSED':
  1935.                     $twig '' != $twig $twig 'aviatur_car_payment_rejected_secure';
  1936.                     $orderProduct->setResume('No reservation');
  1937.                     break;
  1938.                 default:
  1939.                     $twig '' != $twig $twig 'aviatur_car_payment_pending_secure';
  1940.                     $updateOrder $orderController->updatePaymentAction($orderProduct);
  1941.                     $orderProduct->setUpdatingdate(new \DateTime());
  1942.                     $em->persist($orderProduct);
  1943.                     $em->flush();
  1944.                     $retryCount 1;
  1945.                     break;
  1946.             }
  1947.             $session->set($transactionId.'[car][retry]'$retryCount 1);
  1948.             return $this->redirect($this->generateUrl($twig));
  1949.         } else {
  1950.             $orderProduct->setStatus('pending');
  1951.             $em->persist($orderProduct);
  1952.             $em->flush();
  1953.             return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '''No hay respuesta por parte del servicio de pago'));
  1954.         }
  1955.     }
  1956.     /**
  1957.      * @param Request $request
  1958.      * @param ManagerRegistry $managerRegistry
  1959.      * @param ParameterBagInterface $parameterBag
  1960.      * @param TwigFolder $twigFolder
  1961.      * @param AviaturEncoder $aviaturEncoder
  1962.      * @param \Swift_Mailer $mailer
  1963.      * @param Pdf $pdf
  1964.      * @param ExceptionLog $exceptionLog
  1965.      * @return Response
  1966.      */
  1967.     public function paymentOutputAction(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagTwigFolder $twigFolderAviaturEncoder $aviaturEncoder, \Swift_Mailer $mailerPdf $pdfExceptionLog $exceptionLog)
  1968.     {
  1969.         $projectDir $parameterBag->get('kernel.project_dir');
  1970.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1971.         $list = [];
  1972.         $clientFranquice = [];
  1973.         $renderResumeView = [];
  1974.         $session $request->getSession();
  1975.         $em $managerRegistry->getManager();
  1976.         $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  1977.         $transactionId $session->get($transactionIdSessionName);
  1978.         $agencyFolder $twigFolder->twigFlux();
  1979.         $postDataJson $session->get($transactionId.'[car][detail_data]');
  1980.         $PaymentForm $session->get($transactionId.'[car][payment_car_form]');
  1981.         $detail = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
  1982.         $total_amount_local $session->get($transactionId.'[car][total_amount_local]');
  1983.         $currency_code_local $session->get($transactionId.'[car][currency_code_local]');
  1984.         $total_amount $session->get($transactionId.'[car][total_amount]');
  1985.         $currency $session->get($transactionId.'[car][currency]');
  1986.         $orderProductCode $session->get($transactionId.'[car][order]');
  1987.         $providerCarInfo $session->get($transactionId.'[car][providerCarInfo]');
  1988.         $car_homologate_hertz_codes json_decode($em->getRepository(Parameter::class)->findOneByName('car_homologate_hertz_codes')->getDescription(), true);
  1989.         $prepayment null;
  1990.         $paymentData json_decode($postDataJson);
  1991.         if ($session->has($transactionId.'[car][vehReservation]')) {
  1992.             $prepayment = \simplexml_load_string($session->get($transactionId.'[car][vehReservation]'));
  1993.         }
  1994.         $customer $em->getRepository(Customer::class)->find($paymentData->BD->id);
  1995.         if (false !== strpos($paymentData->BD->first_name'***')) {
  1996.             $facturationResume = [
  1997.                 'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  1998.                 'customer_address' => $customer->getAddress(),
  1999.                 'customer_doc_num' => $customer->getDocumentnumber(),
  2000.                 'customer_phone' => $customer->getPhone(),
  2001.                 'customer_email' => $customer->getEmail(),
  2002.             ];
  2003.         } else {
  2004.             $facturationResume = [
  2005.                 'customer_names' => $paymentData->BD->first_name.' '.$paymentData->BD->last_name,
  2006.                 'customer_address' => $paymentData->BD->address ?? null,
  2007.                 'customer_doc_num' => $paymentData->BD->doc_num,
  2008.                 'customer_phone' => $paymentData->BD->phone,
  2009.                 'customer_email' => $paymentData->BD->email ?? null,
  2010.             ];
  2011.         }
  2012.         $orderProductId str_replace('PN'''json_decode($orderProductCode)->products);
  2013.         $orderProduct $em->getRepository(OrderProduct::class)->find($orderProductId);
  2014.         $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  2015.         $opResponse json_decode($productResponse);
  2016.         $productRequest $aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey());
  2017.         $opRequest json_decode($productRequest);
  2018.         $isFront $session->has('operatorId');
  2019.         if ($isFront) {
  2020.             $userFront simplexml_load_string($session->get('front_user'));
  2021.             $customerEmail = (string) $userFront->CORREO_ELECTRONICO;
  2022.         } else {
  2023.             $customer $em->getRepository(Customer::class)->find($paymentData->BD->id);
  2024.             $customerEmail $customer->getEmail();
  2025.         }
  2026.         $list[0] = ['M' => 'Mini''N' => 'Mini Élite''E' => 'Económico''H' => 'Económico Élite''C' => 'Compacto''D' => 'Compacto Élite''I' => 'Intermedio''J' => 'Intermedio Élite''S' => 'Estándar''R' => 'Estándar Élite''F' => 'Fullsize''G' => 'Fullsize Elite''P' => 'Premium''U' => 'Premium Élite''L' => 'Lujoso''W' => 'Lujoso Élite''O' => 'Oversize''X' => 'Especial'];
  2027.         $list[1] = ['B' => '2-3 Puertas''C' => '2/4 Puertas''D' => '4-5 Puertas''W' => 'Vagón''V' => 'Van de pasajeros''L' => 'Limosina''S' => 'Deportivo''T' => 'Convertible''F' => 'SUV''J' => 'Todo Terreno''X' => 'Especial''P' => 'Pick up de Cabina Regular''Q' => 'Pick up de Cabina Extendida''Z' => 'Auto de Oferta Especial''E' => 'Coupe''M' => 'Minivan''R' => 'Vehículo recreacional''H' => 'Casa rodante''Y' => 'Vehículo de dos ruedas''N' => 'Roasted''G' => 'Crossover''K' => 'Van comercial / Camión'];
  2028.         $list[2] = ['M' => 'Transmisión Manual, Tracción sin especificar''N' => 'Transmisión Manual, Tracción 4WD''C' => 'Transmisión Manual, Tracción AWD''A' => 'Transmisión Automática, Tracción sin especificar''B' => 'Transmisión Automática, Tracción 4WD''D' => 'Transmisión Automática, Tracción AWD'];
  2029.         $list[3] = ['R' => 'Combustible no especificado, con aire acondicionado''N' => 'Combustible no especificado, sin aire acondicionado''D' => 'Diesel, con aire acondicionado''Q' => 'Diesel, sin aire acondicionado''H' => 'Híbrido, con aire acondicionado''I' => 'Híbrido, sin aire acondicionado''E' => 'Eléctrico, con aire acondicionado''C' => 'Eléctrico, sin aire acondicionado''L' => 'Gas comprimido, con aire acondicionado''S' => 'Gas comprimido, sin aire acondicionado''A' => 'Hidrógeno, con aire acondicionado''B' => 'Hidrógeno, sin aire acondicionado''M' => 'Multi combustible, con aire acondicionado''F' => 'Multi combustible, sin aire acondicionado''V' => 'Gasolina, con aire acondicionado''Z' => 'Gasolina, sin aire acondicionado''U' => 'Etanol, con aire acondicionado''X' => 'Etanol, sin aire acondicionado'];
  2030.         $carsInfo = [];
  2031.         $selection json_decode($session->get($transactionId.'[car][selection]'));
  2032.         foreach ($detail->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $VehVendorAvail) {
  2033.             if ((int) $VehVendorAvail->Info->TPA_Extensions->RPH == explode('-'$paymentData->SD->selection)[0]) {
  2034.                 foreach ($VehVendorAvail->VehAvails as $VehAvails) {
  2035.                     foreach ($VehAvails->VehAvail as $VehAvail) {
  2036.                         if ((int) $VehAvail->VehAvailInfo->TPA_Extensions->RPH == explode('-'$paymentData->SD->selection)[1]) {
  2037.                             $carsInfo[] = $VehAvail;
  2038.                         }
  2039.                     }
  2040.                 }
  2041.             }
  2042.         }
  2043.         $locations = [];
  2044.         foreach ($detail->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Info->LocationDetails as $location) {
  2045.             $locations[] = $location;
  2046.         }
  2047.         $carImg = (string) $detail->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->Vehicle->PictureURL;
  2048.         $agencyData = [
  2049.             'agency_name' => $agency->getName(),
  2050.             'agency_nit' => $agency->getNit(),
  2051.             'agency_phone' => $agency->getPhone(),
  2052.             'agency_email' => $agency->getMailContact(),
  2053.         ];
  2054.         $journeySummary = [
  2055.             'serviceResponse' => $detail->Message->OTA_VehAvailRateRS,
  2056.             'carsInfo' => $carsInfo,
  2057.             'reservationInfo' => $prepayment->Message->OTA_VehResRS ?? null,
  2058.             'carDescription' => $list,
  2059.             'pickUpLocation' => $locations[0],
  2060.             'returnLocation' => end($locations),
  2061.             'carsItems' => (null != $providerCarInfo) ? json_decode($providerCarInfotrue) : null,
  2062.             'carImg' => str_replace('9.JPEG''4.JPEG'$carImg),
  2063.             'total_amount' => $total_amount,
  2064.             'currency_code' => $currency,
  2065.             'total_amount_local' => $total_amount_local,
  2066.             'currency_code_local' => $currency_code_local,
  2067.             'order' => json_decode($orderProductCode)->products,
  2068.         ];
  2069.         if ($session->has($transactionId.'[car][voucher_num]')) {
  2070.             $journeySummary['voucher_num'] = $session->get($transactionId.'[car][voucher_num]');
  2071.         }
  2072.         $emailData = [
  2073.             'agencyData' => $agencyData,
  2074.             'journeySummary' => $journeySummary,
  2075.             'car_homologate_hertz_codes' => $car_homologate_hertz_codes,
  2076.             'paymentForm' => $session->get($transactionId.'[car][payment_car_form]'),
  2077.         ];
  2078.         if (isset($opResponse->x_description)) {
  2079.             $paymentResume = [
  2080.                 'transaction_state' => $opResponse->x_response_code,
  2081.                 'ta_transaction_state' => $opResponse->x_ta_response_code,
  2082.                 'id' => $orderProduct->getBooking(),
  2083.                 'id_context' => $opRequest->x_invoice_num,
  2084.                 'total_amount' => $opResponse->x_amount,
  2085.                 'currency' => $opResponse->x_bank_currency,
  2086.                 'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  2087.                 'iva' => $opRequest->x_tax,
  2088.                 'ip_address' => $opRequest->x_customer_ip,
  2089.                 'bank_name' => $opResponse->x_bank_name,
  2090.                 'client_franquice' => ['description' => ''],
  2091.                 'cuotas' => $opRequest->x_differed,
  2092.                 'card_num' => '************'.substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  2093.                 'reference' => $opResponse->x_transaction_id,
  2094.                 'auth' => $opResponse->x_approval_code,
  2095.                 'transaction_date' => $opResponse->x_transaction_date,
  2096.                 'description' => $opResponse->x_description,
  2097.                 'reason_code' => $opResponse->x_response_reason_code,
  2098.                 'reason_description' => $opResponse->x_response_reason_text,
  2099.                 'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  2100.                 'customer_address' => $customer->getAddress(),
  2101.                 'customer_doc_num' => $customer->getDocumentnumber(),
  2102.                 'customer_phone' => $customer->getPhone(),
  2103.                 'customer_email' => $customer->getEmail(),
  2104.                 'agency_name' => $agency->getName(),
  2105.                 'agency_nit' => $agency->getNit(),
  2106.                 'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
  2107.                 'client_email' => $opResponse->x_email,
  2108.             ];
  2109.             $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  2110.         } elseif (isset($opRequest->dataTransf)) {
  2111.             if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})) {
  2112.                 $state $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
  2113.                 if (102 == $state) {
  2114.                     $state 1;
  2115.                     $reason_description 'SafetyPay recibe la confirmación del pago de un Banco Asociado';
  2116.                 } elseif (101 == $state) {
  2117.                     $state 2;
  2118.                     $reason_description 'Transacción creada';
  2119.                 }
  2120.                 $paymentResume = [
  2121.                     'transaction_state' => $state,
  2122.                     'id' => $orderProduct->getBooking(),
  2123.                     'currency' => $opRequest->dataTransf->x_currency,
  2124.                     'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
  2125.                     'amount' => null,
  2126.                     'iva' => null,
  2127.                     'ip_address' => $opRequest->dataTransf->dirIp,
  2128.                     'airport_tax' => null,
  2129.                     'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
  2130.                     'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
  2131.                     'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
  2132.                     'description' => $opRequest->dataTransf->x_description,
  2133.                     'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
  2134.                     'reason_description' => $reason_description ?? null,
  2135.                     'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  2136.                     'client_franquice' => ['description' => 'SafetyPay'],
  2137.                     'customer_names' => $customer->getFirstname() . ' ' $customer->getLastname(),
  2138.                     'customer_address' => $customer->getAddress(),
  2139.                     'customer_doc_num' => $customer->getDocumentnumber(),
  2140.                     'customer_phone' => $customer->getPhone(),
  2141.                     'customer_email' => $customer->getEmail(),
  2142.                     'agency_name' => $agency->getName(),
  2143.                     'agency_nit' => $agency->getNit(),
  2144.                     'client_names' => $opResponse->x_first_name ' ' $opResponse->x_last_name,
  2145.                     'client_email' => $opResponse->x_email,
  2146.                 ];
  2147.             } else {
  2148.                 $paymentResume = [
  2149.                     'transaction_state' => 2,
  2150.                     'id' => $orderProduct->getBooking(),
  2151.                     'currency' => $opRequest->dataTransf->x_currency,
  2152.                     'total_amount' => $opRequest->dataTransf->x_total_amount,
  2153.                     'amount' => null,
  2154.                     'iva' => null,
  2155.                     'ip_address' => $opRequest->dataTransf->dirIp,
  2156.                     'airport_tax' => null,
  2157.                     'reference' => $opRequest->dataTransf->x_reference,
  2158.                     'auth' => null,
  2159.                     'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
  2160.                     'description' => $opRequest->dataTransf->x_description,
  2161.                     'reason_code' => 101,
  2162.                     'reason_description' => 'Transacción creada',
  2163.                     'x_payment_data' => $opRequest->dataTransf->x_payment_data,
  2164.                     'customer_names' => $customer->getFirstname() . ' ' $customer->getLastname(),
  2165.                     'customer_address' => $customer->getAddress(),
  2166.                     'customer_doc_num' => $customer->getDocumentnumber(),
  2167.                     'customer_phone' => $customer->getPhone(),
  2168.                     'customer_email' => $customer->getEmail(),
  2169.                     'agency_name' => $agency->getName(),
  2170.                     'agency_nit' => $agency->getNit(),
  2171.                     'client_names' => $opResponse->x_first_name ' ' $opResponse->x_last_name,
  2172.                     'client_email' => $opResponse->x_email,
  2173.                 ];
  2174.             }
  2175.             if ('baloto' == $opRequest->dataTransf->x_payment_data) {
  2176.                 $paymentResume['transaction_state'] = 3;
  2177.             }
  2178.             $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  2179.         } elseif (isset($opRequest->infoCash)) {
  2180.             $paymentResume = [
  2181.                 'id' => $orderProduct->getBooking(),
  2182.                 'id_context' => $opRequest->infoCash->x_reference,
  2183.                 'currency' => $opRequest->infoCash->x_currency,
  2184.                 'total_amount' => $opRequest->infoCash->x_total_amount,
  2185.                 'client_franquice' => ['description' => 'Efectivo'],
  2186.                 'amount' => null,
  2187.                 'iva' => null,
  2188.                 'ip_address' => $opRequest->infoCash->dirIp,
  2189.                 'airport_tax' => null,
  2190.                 'reference' => $opRequest->infoCash->x_reference,
  2191.                 'auth' => null,
  2192.                 'transaction_date' => $opRequest->infoCash->x_fechavigencia,
  2193.                 'description' => $opRequest->infoCash->x_description,
  2194.                 'reason_code' => 101,
  2195.                 'reason_description' => 'Transacción creada',
  2196.                 'client_email' => $opRequest->infoCash->x_email,
  2197.                 'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
  2198.                 'customer_names' => $customer->getFirstname() . ' ' $customer->getLastname(),
  2199.                 'customer_address' => $customer->getAddress(),
  2200.                 'customer_doc_num' => $customer->getDocumentnumber(),
  2201.                 'customer_phone' => $customer->getPhone(),
  2202.                 'customer_email' => $customer->getEmail(),
  2203.                 'agency_name' => $agency->getName(),
  2204.                 'agency_nit' => $agency->getNit(),
  2205.                 'client_names' => $opRequest->infoCash->x_first_name ' ' $opRequest->infoCash->x_last_name,
  2206.             ];
  2207.             $cash_result json_decode($session->get($transactionId '[car][cash_result]'));
  2208.             $paymentResume['transaction_state'] = 3;
  2209.             if ('' == $cash_result) {
  2210.                 $paymentResume['transaction_state'] = 2;
  2211.             }
  2212.             $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  2213.         } else {
  2214.             if ((empty($opResponse) && empty($opRequest) && == $session->get($transactionId.'[car][payment_car_form]')) || $isFront) {
  2215.                 $paymentResume = [];
  2216.             } else {
  2217.                 $bank_info $em->getRepository(PseBank::class)->findOneByCode($opRequest->bankCode);
  2218.                 $bank_name $bank_info->getName();
  2219.                 $clientFranquice['description'] = 'PSE';
  2220.                 $paymentResume = [
  2221.                     'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
  2222.                     'id' => $orderProduct->getBooking(),
  2223.                     'id_context' => $opRequest->reference,
  2224.                     'currency' => $opRequest->currency,
  2225.                     'total_amount' => $opRequest->totalAmount,
  2226.                     'amount' => $opRequest->devolutionBase,
  2227.                     'iva' => $opRequest->taxAmount,
  2228.                     'ip_address' => $opRequest->ipAddress,
  2229.                     'bank_name' => $bank_name,
  2230.                     'client_franquice' => $clientFranquice,
  2231.                     'reference' => $opResponse->createTransactionResult->transactionID,
  2232.                     'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
  2233.                     'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
  2234.                     'description' => $opRequest->description,
  2235.                     'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
  2236.                     'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
  2237.                     'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  2238.                     'customer_address' => $customer->getAddress(),
  2239.                     'customer_doc_num' => $customer->getDocumentnumber(),
  2240.                     'customer_phone' => $customer->getPhone(),
  2241.                     'customer_email' => $customer->getEmail(),
  2242.                     'agency_name' => $agency->getName(),
  2243.                     'agency_nit' => $agency->getNit(),
  2244.                     'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
  2245.                     'client_email' => $opRequest->payer->emailAddress,
  2246.                 ];
  2247.             }
  2248.         }
  2249.         if ($session->has($transactionId.'[car][vehReservation]') && !$session->has($transactionId.'[car][emission_email]')) {
  2250.             $emailData['paymentResume'] = $paymentResume;
  2251.             //return $this->render($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Car/Default/email.html.twig'), $emailData);
  2252.             if (!file_exists($projectDir.'/app/serviceLogs/carReservation')) {
  2253.                 mkdir($projectDir.'/app/serviceLogs/carReservation');
  2254.             }
  2255.             $urlResume $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/email.html.twig');
  2256.             $carFile $projectDir.'/app/serviceLogs/carReservation/'.$orderProduct->getBooking().'.pdf';
  2257.             if (!file_exists($carFile)) {
  2258.                 try {
  2259.                     $pdf->generateFromHtml($this->renderView($urlResume$emailData), $carFile, ['encoding' => 'utf-8']);
  2260.                 } catch (\Exception $e) {
  2261.                 }
  2262.             }
  2263.             $setBcc = ['sergio.amaya@aviatur.com''sara.calderon@aviatur.com'];
  2264.             $setTo $customerEmail;
  2265.             if ($isFront && == $PaymentForm) {
  2266.                 $setBcc = ['sergio.amaya@aviatur.com'];
  2267.                 $setTo 'sara.calderon@aviatur.com';
  2268.             }
  2269.             $message = (new \Swift_Message())
  2270.                 ->setContentType('text/html')
  2271.                 ->setFrom($session->get('emailNoReply'))
  2272.                 ->setTo($setTo)
  2273.                 ->setBcc($setBcc)
  2274.                 ->attach(\Swift_Attachment::fromPath($carFile))
  2275.                 ->setSubject($session->get('agencyShortName') . (($isFront) ? ' B2T ' '') . ' - [Autos] Gracias por su compra')
  2276.                 ->setBody(
  2277.                     $this->renderView($urlResume$emailData)
  2278.                 );
  2279.             if ($session->has($transactionId.'[car][vehReservation]')) {
  2280.                 try {
  2281.                     $mailer->send($message);
  2282.                     $session->set($transactionId.'[car][emission_email]''emailed');
  2283.                 } catch (\Exception $ex) {
  2284.                     $exceptionLog->log(
  2285.                         $message,
  2286.                         $ex
  2287.                     );
  2288.                 }
  2289.             }
  2290.         }
  2291.         if ($session->has($transactionId.'[car][cash_result]')) {
  2292.             $renderResumeView['infos'][0]['agencyData']['agency_nit'] = $agency->getNit();
  2293.             $renderResumeView['infos'][0]['agencyData']['agency_name'] = $agency->getName();
  2294.             $renderResumeView['infos'][0]['agencyData']['agency_phone'] = $agency->getPhone();
  2295.             $renderResumeView['infos'][0]['agencyData']['agency_email'] = $agency->getMailContact();
  2296.             $renderResumeView['infos'][0]['paymentResume'] = $paymentResume;
  2297.             $voucherFile $projectDir.'/app/serviceLogs/CashTransaction/ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  2298.             if (file_exists($voucherFile)) {
  2299.                 $renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  2300.             }
  2301.             $emailData['cash_result'] = json_decode($session->get($transactionId.'[car][cash_result]'), true);
  2302.             $renderResumeView['cash_result'] = json_decode($session->get($transactionId.'[car][cash_result]'), true);
  2303.             $renderResumeView['exportPDF'] = true;
  2304.             $ruta '@AviaturTwig/'.$agencyFolder.'/General/Templates/email_cash.html.twig';
  2305.             if (!file_exists($voucherFile)) {
  2306.                 $pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $renderResumeView), $voucherFile);
  2307.                 $renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
  2308.             }
  2309.             $paymentResume['NameArchive'] = $renderResumeView['NameArchive'];
  2310.             $paymentResume['exportPDF'] = false;
  2311.             if (!$session->has($transactionId.'[car][emission_baloto_email]')) {
  2312.                 $setTo $paymentResume['client_email'];
  2313.                 $message = (new \Swift_Message())
  2314.                         ->setContentType('text/html')
  2315.                         ->setFrom($session->get('emailNoReply'))
  2316.                         ->setTo($setTo)
  2317.                         //->setBcc(array('soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co', 'gustavo.hincapie@aviatur.com'))
  2318.                         ->setSubject($session->get('agencyShortName').' - Transacción Efectivo Creada '.$paymentResume['id_context'])
  2319.                         ->attach(\Swift_Attachment::fromPath($voucherFile))
  2320.                         ->setBody(
  2321.                             $this->renderView($twigFolder->twigExists($ruta), $renderResumeView)
  2322.                         );
  2323.                 try {
  2324.                     $mailer->send($message);
  2325.                     $session->set($transactionId.'[car][emission_baloto_email]''emailed');
  2326.                 } catch (\Exception $ex) {
  2327.                     $exceptionLog->log($message$ex);
  2328.                 }
  2329.             }
  2330.         }
  2331.         $paymentResume['finantial_rate'] = json_decode($session->get('[car][finantial_rate_info]'), true);
  2332.         $paymentResume['facturationResume'] = $facturationResume;
  2333.         $paymentResume['serviceResponse'] = $detail->Message->OTA_VehAvailRateRS;
  2334.         $paymentResume['carsInfo'] = $carsInfo;
  2335.         $paymentResume['car_homologate_hertz_codes'] = $car_homologate_hertz_codes;
  2336.         $paymentResume['reservationInfo'] = $prepayment->Message->OTA_VehResRS ?? null;
  2337.         $paymentResume['order'] = 'PN'.$orderProduct->getId();
  2338.         $paymentResume['carDescription'] = $list;
  2339.         $paymentResume['pickUpLocation'] = $locations[0];
  2340.         $paymentResume['returnLocation'] = end($locations);
  2341.         $paymentResume['transactionID'] = $transactionId;
  2342.         $paymentResume['carsItems'] = (null != $providerCarInfo) ? json_decode($providerCarInfotrue) : null;
  2343.         $paymentResume['emailData'] = $emailData;
  2344.         $paymentResume['backDetail'] = $this->generateUrl('aviatur_car_retry_secure');
  2345.         $paymentResume['passengerData'] = ($session->has($transactionId.'[car][passengerData]')) ? json_decode($session->get($transactionId.'[car][passengerData]'), true) : false;
  2346.         if (!isset($paymentResume['total_amount'])) {
  2347.             $paymentResume['total_amount'] = $total_amount;
  2348.             $paymentResume['currency_code'] = $currency;
  2349.         }
  2350.         if (!isset($paymentResume['retry_count'])) {
  2351.             $paymentResume['retry_count'] = $session->get($transactionId.'[car][retry]');
  2352.         }
  2353.         $resumeOrderProduct $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/confirmation.html.twig'), $paymentResume);
  2354.         if (null == $orderProduct->getResume()) {
  2355.             $orderProduct->setEmail(json_encode($emailData));
  2356.             $orderProduct->setResume($resumeOrderProduct);
  2357.             $orderProduct->setUpdatingdate(new \DateTime());
  2358.             $em->persist($orderProduct);
  2359.             $em->flush();
  2360.         }
  2361.         return $resumeOrderProduct;
  2362.     }
  2363.     private function unaccent($string)
  2364.     {
  2365.         return preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i''$1'htmlentities($stringENT_QUOTES'UTF-8'));
  2366.     }
  2367.     public function indexAction(Request $requestManagerRegistry $managerRegistryAuthorizationCheckerInterface $authorizationCheckerTwigFolder $twigFolderAviaturErrorHandler $errorHandlerPaginatorInterface $paginator$page$active$search null)
  2368.     {
  2369.         $em $managerRegistry->getManager();
  2370.         $fullRequest $request;
  2371.         $routeParams $fullRequest->attributes->get('_route_params');
  2372.         $requestUrl $this->generateUrl($fullRequest->attributes->get('_route'), $routeParams);
  2373.         $session $request->getSession();
  2374.         $agencyId $session->get('agencyId');
  2375.         $agency $em->getRepository(Agency::class)->find($agencyId);
  2376.         $agencyFolder $twigFolder->twigFlux();
  2377.         if ($request->isXmlHttpRequest()) {
  2378.             //BUSCADOR
  2379.             $query $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  2380.             $query $query->setParameter('agency'$agency);
  2381.             $query $query->setParameter('id'$search);
  2382.             $queryIn $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  2383.             $queryIn $queryIn->setParameter('agency'$agency);
  2384.             $queryIn $queryIn->setParameter('id'$search);
  2385.             $path '/Car/Default/Ajaxindex_car.html.twig';
  2386.             $urlReturn '@AviaturTwig/'.$agencyFolder.$path;
  2387.             if ('activo' == $active) {
  2388.                 $articulos $query->getResult();
  2389.             } elseif ('inactivo' == $active) {
  2390.                 if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
  2391.                     $articulos $queryIn->getResult();
  2392.                 } else {
  2393.                     return $twigFolder->pathWithLocale('aviatur_general_homepage');
  2394.                 }
  2395.             }
  2396.             $actualArticles = [];
  2397.             foreach ($articulos as $articulo) {
  2398.                 $description json_decode($articulo->getDescription(), true);
  2399.                 if ($description && is_array($description)) {
  2400.                     $actualArticles[] = $articulo;
  2401.                 }
  2402.             }
  2403.             if (empty($actualArticles)) {
  2404.                 return $this->redirect($errorHandler->errorRedirectNoEmail('/''''No existen contenidos para esta agencia.'));
  2405.             }
  2406.             $cantdatos count($actualArticles);
  2407.             $cantRegis 10;
  2408.             $totalRegi ceil($cantdatos $cantRegis);
  2409.             $pagination $paginator->paginate($actualArticles$fullRequest->query->get('page'$page), $cantRegis);
  2410.             return $this->render($twigFolder->twigExists($urlReturn), ['agencyId' => $agencyId'articulo' => $pagination'page' => $page'active' => $active'totalRegi' => $totalRegi'ajaxUrl' => $requestUrl]);
  2411.         } else {
  2412.             //INDEX
  2413.             $query $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  2414.             $query $query->setParameter('agency'$agency);
  2415.             $queryIn $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
  2416.             $queryIn $queryIn->setParameter('agency'$agency);
  2417.             $path '/Car/Default/index_car.html.twig';
  2418.             $urlReturn '@AviaturTwig/'.$agencyFolder.$path;
  2419.         }
  2420.         if ('activo' == $active) {
  2421.             $articulos $query->getResult();
  2422.         } elseif ('inactivo' == $active) {
  2423.             if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
  2424.                 $articulos $queryIn->getResult();
  2425.             } else {
  2426.                 return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'));
  2427.             }
  2428.         }
  2429.         $actualArticles = [];
  2430.         foreach ($articulos as $articulo) {
  2431.             $description json_decode($articulo->getDescription(), true);
  2432.             if ($description && is_array($description)) {
  2433.                 if ('autos' == $description['type']) {
  2434.                     $actualArticles[] = $articulo;
  2435.                 }
  2436.             }
  2437.         }
  2438.         if (empty($actualArticles)) {
  2439.             return $this->redirect($errorHandler->errorRedirectNoEmail('/''''No existen contenidos para esta agencia.'));
  2440.         }
  2441.         $cantdatos count($actualArticles);
  2442.         $cantRegis 9;
  2443.         $totalRegi ceil($cantdatos $cantRegis);
  2444.         $pagination $paginator->paginate($actualArticles$fullRequest->query->get('page'$page), $cantRegis);
  2445.         return $this->render($twigFolder->twigExists($urlReturn), ['agencyId' => $agencyId'articulo' => $pagination'page' => $page'active' => $active'totalRegi' => $totalRegi'ajaxUrl' => $requestUrl]);
  2446.     }
  2447.     public function viewAction(SessionInterface $sessionTwigFolder $twigFolder$id)
  2448.     {
  2449.         $em $this->getDoctrine()->getManager();
  2450.         $agencyId $session->get('agencyId');
  2451.         $agency $em->getRepository(Agency::class)->find($agencyId);
  2452.         $articulo $em->getRepository(\Aviatur\ContentBundle\Entity\Content::class)->findByAgencyNull($session->get('agencyId'), $id);
  2453.         $promoType '';
  2454.         if (isset($articulo[0]) && (null != $articulo[0])) {
  2455.             $agencyFolder $twigFolder->twigFlux();
  2456.             $description json_decode($articulo[0]->getDescription(), true);
  2457.             // determine content type based on eventual json encoded description
  2458.             $carPromoList $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => '__rent-autos'.$promoType'agency' => $agency]);
  2459.             if (null != $carPromoList) {
  2460.                 $carPromos $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($carPromoList, ['date' => 'DESC']);
  2461.             } else {
  2462.                 $carPromos = [];
  2463.             }
  2464.             if ($description && is_array($description)) {
  2465.                 $cookieArray = [];
  2466.                 foreach ($description as $key => $value) {
  2467.                     $cookieArray[$key] = $value;
  2468.                 }
  2469.                 if (isset($cookieArray['origin1']) && preg_match('/^[A-Z]{3}$/'$cookieArray['origin1'])) {
  2470.                     $ori $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['origin1']]);
  2471.                     $cookieArray['originLabel1'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
  2472.                 } else {
  2473.                     $cookieArray['originLabel1'] = '';
  2474.                 }
  2475.                 if (isset($cookieArray['destination1']) && preg_match('/^[A-Z]{3}$/'$cookieArray['destination1'])) {
  2476.                     $dest $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination1']]);
  2477.                     $cookieArray['destinationLabel1'] = $dest->getCity().', '.$dest->getCountry().' ('.$dest->getIata().')';
  2478.                 } else {
  2479.                     $cookieArray['destinationLabel1'] = '';
  2480.                 }
  2481.                 return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/view_car.html.twig'), ['articulo' => $articulo[0], 'cookieLastSearchC' => $cookieArray'carPromos' => $carPromos'promoType' => '__rent-autos']);
  2482.             }
  2483.             return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/view_car.html.twig'), ['articulo' => $articulo[0], 'carPromos' => $carPromos'promoType' => '__rent-autos']);
  2484.         } else {
  2485.             throw $this->createNotFoundException('Contenido no encontrado');
  2486.         }
  2487.     }
  2488.     public function searchRentalsAction(Request $requestManagerRegistry $managerRegistry)
  2489.     {
  2490.         $em $managerRegistry->getManager();
  2491.         $session $request->getSession();
  2492.         if ($request->isXmlHttpRequest()) {
  2493.             $agencyId $session->get('agencyId');
  2494.             $agency $em->getRepository(Agency::class)->find($agencyId);
  2495.             $term $request->query->get('term');
  2496.             $url $request->query->get('url');
  2497.             $queryIn $em->createQuery('SELECT a.id, a.title, a.url, a.description, a.isactive FROM AviaturContentBundle:Content a WHERE a.title LIKE :title AND a.description LIKE :description AND (a.agency = :agency OR a.agency IS NULL)');
  2498.             $queryIn $queryIn->setParameter('title''%'.$term.'%');
  2499.             $queryIn $queryIn->setParameter('description''%\"autos\"%');
  2500.             $queryIn $queryIn->setParameter('agency'$agency);
  2501.             $articulos $queryIn->getResult();
  2502.             $type '';
  2503.             $json_template '<value>:<label>*';
  2504.             $json '';
  2505.             if ($articulos) {
  2506.                 foreach ($articulos as $contenidos) {
  2507.                     $description json_decode($contenidos['description'], true);
  2508.                     if (null == $description || is_array($description)) {
  2509.                         if (isset($description['type'])) {
  2510.                             $type $description['type'];
  2511.                         }
  2512.                     }
  2513.                     $json .= str_replace(['<value>''<label>'], [$contenidos['id'].'|'.$type.'|'.$contenidos['url'], $contenidos['title']], $json_template);
  2514.                 }
  2515.                 $json = \rtrim($json'-');
  2516.             } else {
  2517.                 $json 'NN:No hay Resultados';
  2518.             }
  2519.             $response = \rtrim($json'*');
  2520.             return new Response($response);
  2521.         } else {
  2522.             return new Response('Acceso Restringido');
  2523.         }
  2524.     }
  2525.     public function quotationAction(Request $requestManagerRegistry $managerRegistryParameterBagInterface $parameterBagAviaturWebService $webServiceAviaturLogSave $logSaveTwigFolder $twigFolder, \Swift_Mailer $mailerAbstractGenerator $pdf)
  2526.     {
  2527.         $projectDir $parameterBag->get('kernel.project_dir');
  2528.         $list = [];
  2529.         $codImg null;
  2530.         $fullRequest $request;
  2531.         $session $fullRequest->getSession();
  2532.         $isFront $session->has('operatorId');
  2533.         $em $managerRegistry->getManager();
  2534.         $agency $em->getRepository(Agency::class)->find($session->get('agencyId'));
  2535.         $agencyFolder $twigFolder->twigFlux();
  2536.         $transactionId $session->get('transactionId');
  2537.         $additionalUserFront simplexml_load_string($session->get('front_user_additionals'));
  2538.         $response = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
  2539.         $detailCarRaw $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails;
  2540.         $locationCar $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore;
  2541.         $dateIn strtotime((string) $locationCar['PickUpDateTime']);
  2542.         $dateOut strtotime((string) $locationCar['ReturnDateTime']);
  2543.         $postDataJson $session->get($transactionId.'[car][carsInfo]');
  2544.         if ($session->has($transactionId.'[crossed]'.'[url-car]')) {
  2545.             $urlAvailability $session->get($transactionId.'[crossed]'.'[url-car]');
  2546.         } elseif ($session->has($transactionId.'[car][availability_url]')) {
  2547.             $urlAvailability $session->get($transactionId.'[car][availability_url]');
  2548.         } else {
  2549.             $urlAvailability $session->get($transactionId.'[availability_url]');
  2550.         }
  2551.         $list[0] = ['M' => 'Mini''N' => 'Mini Élite''E' => 'Económico''H' => 'Económico Élite''C' => 'Compacto''D' => 'Compacto Élite''I' => 'Intermedio''J' => 'Intermedio Élite''S' => 'Estándar''R' => 'Estándar Élite''F' => 'Fullsize''G' => 'Fullsize Elite''P' => 'Premium''U' => 'Premium Élite''L' => 'Lujoso''W' => 'Lujoso Élite''O' => 'Oversize''X' => 'Especial'];
  2552.         $list[1] = ['B' => '2-3 Puertas''C' => '2/4 Puertas''D' => '4-5 Puertas''W' => 'Vagón''V' => 'Van de pasajeros''L' => 'Limosina''S' => 'Deportivo''T' => 'Convertible''F' => 'SUV''J' => 'Todo Terreno''X' => 'Especial''P' => 'Pick up de Cabina Regular''Q' => 'Pick up de Cabina Extendida''Z' => 'Auto de Oferta Especial''E' => 'Coupe''M' => 'Minivan''R' => 'Vehículo recreacional''H' => 'Casa rodante''Y' => 'Vehículo de dos ruedas''N' => 'Roasted''G' => 'Crossover''K' => 'Van comercial / Camión'];
  2553.         $list[2] = ['M' => 'Transmisión Manual, Tracción sin especificar''N' => 'Transmisión Manual, Tracción 4WD''C' => 'Transmisión Manual, Tracción AWD''A' => 'Transmisión Automática, Tracción sin especificar''B' => 'Transmisión Automática, Tracción 4WD''D' => 'Transmisión Automática, Tracción AWD'];
  2554.         $list[3] = ['R' => 'Combustible no especificado, con aire acondicionado''N' => 'Combustible no especificado, sin aire acondicionado''D' => 'Diesel, con aire acondicionado''Q' => 'Diesel, sin aire acondicionado''H' => 'Híbrido, con aire acondicionado''I' => 'Híbrido, sin aire acondicionado''E' => 'Eléctrico, con aire acondicionado''C' => 'Eléctrico, sin aire acondicionado''L' => 'Gas comprimido, con aire acondicionado''S' => 'Gas comprimido, sin aire acondicionado''A' => 'Hidrógeno, con aire acondicionado''B' => 'Hidrógeno, sin aire acondicionado''M' => 'Multi combustible, con aire acondicionado''F' => 'Multi combustible, sin aire acondicionado''V' => 'Gasolina, con aire acondicionado''Z' => 'Gasolina, sin aire acondicionado''U' => 'Etanol, con aire acondicionado''X' => 'Etanol, sin aire acondicionado'];
  2555.         $session->set($transactionId.'[car][list]'json_encode($list));
  2556.         $html $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/quotation.html.twig');
  2557.         $namefilepdf 'Aviatur_cotizacion_auto_'.$transactionId.'.pdf';
  2558.         $voucherCruiseFile $projectDir.'/app/quotationLogs/carQuotation/'.$namefilepdf.'.pdf';
  2559.         if ('N' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
  2560.             $codImg $additionalUserFront->EMPRESA;
  2561.         } elseif ('S' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
  2562.             $codImg $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
  2563.         }
  2564.         $imgAgency 'assets/common_assets/img/offices/'.$codImg.'.png';
  2565.         if (!file_exists($imgAgency)) {
  2566.             $codImg 10;
  2567.         }
  2568.         if (!file_exists($voucherCruiseFile)) {
  2569.             $pdf->setOption('page-size''Legal');
  2570.             $pdf->setOption('margin-top'0);
  2571.             $pdf->setOption('margin-right'0);
  2572.             $pdf->setOption('margin-bottom'0);
  2573.             $pdf->setOption('margin-left'0);
  2574.             $pdf->setOption('orientation''portrait');
  2575.             $pdf->setOption('enable-javascript'true);
  2576.             $pdf->setOption('no-stop-slow-scripts'true);
  2577.             $pdf->setOption('no-background'false);
  2578.             $pdf->setOption('lowquality'false);
  2579.             $pdf->setOption('encoding''utf-8');
  2580.             $pdf->setOption('images'true);
  2581.             $pdf->setOption('dpi'300);
  2582.             $pdf->setOption('enable-external-links'true);
  2583.             $pdf->setOption('enable-internal-links'true);
  2584.             $pdf->generateFromHtml($this->renderView($html, [
  2585.                 'dateIn' => $dateIn,
  2586.                 'dateOut' => $dateOut,
  2587.                 'dateInStr' => (string) $locationCar['PickUpDateTime'],
  2588.                 'dateOutStr' => (string) $locationCar['ReturnDateTime'],
  2589.                 'nights' => floor(($dateOut $dateIn) / (24 60 60)),
  2590.                 'total' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
  2591.                 'priceCurrency' => (string) $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->TotalCharge['CurrencyCode'],
  2592.                 'category' => (string) $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle->VehMakeModel['Name'],
  2593.                 'TransmissionType' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle['TransmissionType'],
  2594.                 'AirConditionInd' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle['AirConditionInd'],
  2595.                 'PassengerQuantity' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle['PassengerQuantity'],
  2596.                 'description' => '',
  2597.                 'vendor' => (string) $detailCarRaw->VehVendorAvail->Vendor,
  2598.                 'email' => '',
  2599.                 'services' => '',
  2600.                 'photo' => (string) $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle->PictureURL,
  2601.                 'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  2602.                 'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
  2603.                 'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
  2604.                 'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
  2605.                 'prepaymentsInfo' => '',
  2606.                 'namesClient' => $fullRequest->request->get('quotationName'),
  2607.                 'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
  2608.                 'emailClient' => $fullRequest->request->get('quotationEmail'),
  2609.                 'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
  2610.                 'infoTerms' => $fullRequest->request->get('quotationTerms'),
  2611.                 'infoComments' => $fullRequest->request->get('quotationComments'),
  2612.                 'codImg' => $codImg,
  2613.             ]), $voucherCruiseFile);
  2614.         }
  2615.         $subject 'Cotización de Auto';
  2616.         $messageEmail = (new \Swift_Message())
  2617.                         ->setContentType('text/html')
  2618.                         ->setFrom('noreply@aviatur.com')
  2619.                         ->setTo($additionalUserFront->CORREO_ELECTRONICO)
  2620.                         ->setSubject($session->get('agencyShortName').' - '.$subject)
  2621.                         ->attach(\Swift_Attachment::fromPath($voucherCruiseFile))
  2622.                         ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
  2623.                             'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
  2624.                             'codImg' => $codImg,
  2625.                         ]), 'text/html');
  2626.         $mailer->send($messageEmail);
  2627.         chmod($projectDir.'/app/quotationLogs/carQuotation/'777);
  2628.         $this->saveInformationCGS($request$webService$errorhandler$logSave$response$additionalUserFront$fullRequest->request);
  2629.         unlink($voucherCruiseFile);
  2630.         return $this->redirect($this->generateUrl('aviatur_car_search'));
  2631.     }
  2632.     public function saveInformationCGS(Request $requestManagerRegistry $managerRegistryAviaturWebService $webServiceAviaturErrorHandler $errorHandlerAviaturLogSave $logSave$data$customer$agency)
  2633.     {
  2634.         $em $managerRegistry->getManager();
  2635.         $parametersLogin =$em->getRepository(Parameter::class)->findParameters($agency'aviatur_service_login_cgs');
  2636.         $urlLoginCGS $parametersLogin[0]['value'];
  2637.         $parametersProduct $em->getRepository(Parameter::class)->findParameters($agency'aviatur_service_car_cgs');
  2638.         $urlAddProductCar $parametersProduct[0]['value'];
  2639.         /*
  2640.          * get token api autentication
  2641.          * PENDIENTE: Validar si se puede obtener el token, si no entonces no hacer este proceso
  2642.          */
  2643.         $userLoginCGS $webService->encryptUser(trim(strtolower($customer->CODIGO_USUARIO)), 'AviaturCGSMTK');
  2644.         $jsonReq json_encode(['username' => $userLoginCGS]); //j_acosta (encriptado)
  2645.         $curl curl_init();
  2646.         curl_setopt_array($curl, [
  2647.             CURLOPT_URL => $urlLoginCGS,
  2648.             CURLOPT_RETURNTRANSFER => true,
  2649.             CURLOPT_SSL_VERIFYPEER => false,
  2650.             CURLOPT_ENCODING => '',
  2651.             CURLOPT_MAXREDIRS => 10,
  2652.             CURLOPT_TIMEOUT => 0,
  2653.             CURLOPT_FOLLOWLOCATION => true,
  2654.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  2655.             CURLOPT_CUSTOMREQUEST => 'POST',
  2656.             CURLOPT_POSTFIELDS => $jsonReq,
  2657.             CURLOPT_HTTPHEADER => [
  2658.                 'Content-Type: application/json',
  2659.             ],
  2660.         ]);
  2661.         $response curl_exec($curl);
  2662.         $httpcode curl_getinfo($curlCURLINFO_HTTP_CODE);
  2663.         curl_close($curl);
  2664.         if (200 != $httpcode) {
  2665.             $logSave->logSave('HTTPCODE: '.$httpcode.' Error usuario: '.strtolower($customer->CODIGO_USUARIO), 'CGS''CGSCAR_ERRORLOGIN');
  2666.             $logSave->logSave(print_r($responsetrue), 'CGS''responseCarCGS');
  2667.             return $this->redirect($errorHandler->errorRedirectNoEmail('/buscar/autos''Error Login''Error Login'));
  2668.         } else {
  2669.             $tokenInfoApiQuotation json_decode($response);
  2670.             $tokenApiQuotation $tokenInfoApiQuotation->TOKEN;
  2671.         }
  2672.         if ($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'] == $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode']) {
  2673.             $dataCity $em->getRepository(City::class)->findOneByIatacode($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode']);
  2674.             $sameCity true;
  2675.         } else {
  2676.             $dataCity1 $em->getRepository(City::class)->findOneByIatacode($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode']);
  2677.             $dataCity2 $em->getRepository(City::class)->findOneByIatacode($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode']);
  2678.             $sameCity false;
  2679.         }
  2680.         $emails_arr = [
  2681.             'active' => true,
  2682.             'dateCreated' => '0001-01-01T00:00:00',
  2683.             'emailAddress' => (string) $request->get('quotationEmail'),
  2684.             'id' => 0,
  2685.             'lastUpdated' => '0001-01-01T00:00:00',
  2686.             'version' => 0,
  2687.         ];
  2688.         $phones_arr = [
  2689.             'active' => false,
  2690.             'dateCreated' => '0001-01-01T00:00:00',
  2691.             'id' => 0,
  2692.             'lastUpdated' => '0001-01-01T00:00:00',
  2693.             'number' => null,
  2694.             'type' => null,
  2695.             'version' => 0,
  2696.         ];
  2697.         $data_send = [
  2698.             'customer' => [
  2699.                 'firstName' => (string) $request->get('quotationName'),
  2700.                 'lastName' => (string) $request->get('quotationLastname'),
  2701.                 'mothersName' => null,
  2702.                 'fullName' => trim($request->get('quotationName')).' '.trim($request->get('quotationLastname')),
  2703.                 'birthDate' => 'true',
  2704.                 'billingInformations' => null,
  2705.                 'emails' => [$emails_arr],
  2706.                 'phones' => [$phones_arr],
  2707.                 'city' => null,
  2708.                 ],
  2709.             'selectedProduct' => [
  2710.                 'airExists' => false,
  2711.                 'associatedProductIndex' => null,
  2712.                 'complementPackageList' => null,
  2713.                 'deleteInfo' => null,
  2714.                 'description' => null,
  2715.                 'discount' => null,
  2716.                 'duration' => 10,
  2717.                 'emit' => false,
  2718.                 'fareData' => [
  2719.                     'aditionalFee' => 0.0,
  2720.                     'airpotService' => null,
  2721.                     'baseFare' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
  2722.                     'cO' => 0.0,
  2723.                     'commission' => 0.0,                //Consultar esto
  2724.                     'commissionPercentage' => 0.0,      //Consultar esto
  2725.                     'complements' => null,
  2726.                     'currency' => [
  2727.                         'type' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['CurrencyCode'],
  2728.                     ],
  2729.                     'equivFare' => 0.0,
  2730.                     'iva' => 0.0,
  2731.                     'otherDebit' => null,
  2732.                     'otherTax' => null,
  2733.                     'price' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
  2734.                     'providerPrice' => 0.0,
  2735.                     'qSe' => 0.0,                       //Consultar esto
  2736.                     'qSeIva' => 0.0,
  2737.                     'qse' => null,
  2738.                     'revenue' => 0.0,
  2739.                     'serviceCharge' => 0.0,
  2740.                     'sureCancel' => null,
  2741.                     'tA' => 0.0,
  2742.                     'taIva' => 0.0,
  2743.                     'tax' => 0.0,
  2744.                     'total' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
  2745.                     'yQ' => 0.0,
  2746.                     'yQiva' => 0.0,
  2747.                     'originalNationalCurrencyTotal' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
  2748.                 ],
  2749.                 'passengerDataList' => [
  2750.                     [
  2751.                         'age' => 0,
  2752.                         'birthday' => '0001-01-01T00:00:00',
  2753.                         'fareData' => null,
  2754.                         'gender' => '',
  2755.                         'id' => '',
  2756.                         'lastName' => (string) $request->get('quotationLastname'),
  2757.                         'mail' => (string) $request->get('quotationEmail'),
  2758.                         'mothersName' => '',
  2759.                         'name' => (string) $request->get('quotationName'),
  2760.                         'passengerCode' => [
  2761.                             'accountCode' => '',
  2762.                             'promo' => false,
  2763.                             'realType' => 'ADT',
  2764.                             'type' => 'ADT',
  2765.                         ],
  2766.                         'passengerContact' => null,
  2767.                         'passengerInsuranceInfo' => null,
  2768.                         'phone' => null,
  2769.                         'document' => null,
  2770.                         'typeDocument' => null,
  2771.                     ],
  2772.                 ],
  2773.                 'passengerNumber' => null,
  2774.                 'priceForPassenger' => false,
  2775.                 'priceType' => null,
  2776.                 'priority' => '',
  2777.                 'productType' => [
  2778.                     'description' => 'Vehiculo Renta de Automovil',
  2779.                     'typeProduct' => 'Vehicle',
  2780.                 ],
  2781.                 'provider' => [
  2782.                     'category' => null,
  2783.                     'claveProveedor' => null,
  2784.                     'commissionPercentage' => 0,
  2785.                     'descripcionProveedor' => null,
  2786.                     'idProviders' => 0,
  2787.                     'name' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Vendor['CompanyShortName'],
  2788.                     'nuevoProveedor' => false,
  2789.                     'providerRef' => null,
  2790.                     'utilityMax' => 0,
  2791.                     'utilityMin' => 0,
  2792.                 ],
  2793.                 'route' => [
  2794.                     'arrivalDate' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['ReturnDateTime'],
  2795.                     'arrivalDateString' => null,
  2796.                     'arrivalDescription' => ($sameCity) ? $dataCity->getDescription() : $dataCity2->getDescription(),
  2797.                     'arrivalIATA' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'],
  2798.                     'departureDate' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['PickUpDateTime'],
  2799.                     'departureDateString' => null,
  2800.                     'departureDescription' => ($sameCity) ? (string) $dataCity->getDescription() : (string) $dataCity1->getDescription(),
  2801.                     'departureIATA' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'],
  2802.                     'destination' => null,
  2803.                     'flightTime' => null,
  2804.                     'origin' => null,
  2805.                     'providerCode' => null,
  2806.                     'subRoutes' => null,
  2807.                 ],
  2808.                 'savedPassenger' => false,
  2809.                 'searchHost' => null,
  2810.                 'selected' => false,
  2811.                 'serviceProvider' => null,
  2812.                 'specialRequirements' => null,
  2813.                 'subcategory' => null,
  2814.                 'taxExists' => false,
  2815.                 'travelInsuranceExists' => false,
  2816.                 'vehicleData' => [
  2817.                     'departureAddress' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'],
  2818.                     'arrivalAddress' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'],
  2819.                 ],
  2820.                 'visaInformationQuestion' => false,
  2821.                 'visaValidityQuestion' => false,
  2822.                 'productName' => 'Renta de Automovil',
  2823.                 'itinerary' => [
  2824.                     'accountCode' => null,
  2825.                     'bookingClass' => null,
  2826.                     'currency' => null,
  2827.                     'europeanFlight' => false,
  2828.                     'fareType' => null,
  2829.                     'gdsType' => null,
  2830.                     'insuranceCancelationExits' => false,
  2831.                     'insuranceCancelationValue' => 0,
  2832.                     'internationalFlight' => false,
  2833.                     'price' => null,
  2834.                     'promo' => false,
  2835.                     'requieredVisa' => false,
  2836.                     'seatsRemaining' => 0,
  2837.                     'segments' => null,
  2838.                     'ticketTimeLimit' => null,
  2839.                     'validatingCarrier' => null,
  2840.                     'txPrice' => null,
  2841.                     'txZone' => '',
  2842.                     'txDestination' => '',
  2843.                     'txDescription' => '',
  2844.                 ],
  2845.                 'packageName' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Vendor['CompanyShortName'],
  2846.             ],
  2847.             'quote' => [
  2848.                 'channel' => 'B2C WEB',
  2849.             ],
  2850.         ];
  2851.         $authorization 'Authorization: Bearer '.$tokenApiQuotation;
  2852.         //API URL
  2853.         $url $urlAddProductCar;
  2854.         //create a new cURL resource
  2855.         $ch curl_init($url);
  2856.         //setup request to send json via POST
  2857.         $payload json_encode($data_send);
  2858.         $logSave->logSave(print_r($payloadtrue), 'CGS''RQCarCGS');
  2859.         // print_r($payload);die;
  2860.         //attach encoded JSON string to the POST fields
  2861.         curl_setopt($chCURLOPT_POSTFIELDS$payload);
  2862.         //set the content type to application/json
  2863.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2864.             'accept: application/json',
  2865.             'authorization: Bearer '.$tokenApiQuotation,
  2866.             'content-type: application/json',
  2867.         ]);
  2868.         curl_setopt($chCURLOPT_CUSTOMREQUEST'POST');
  2869.         curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  2870.         curl_setopt($chCURLOPT_MAXREDIRS10);
  2871.         curl_setopt($chCURLOPT_TIMEOUT0);
  2872.         curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  2873.         curl_setopt($chCURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_1);
  2874.         //return response instead of outputting
  2875.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2876.         //execute the POST request
  2877.         $result curl_exec($ch);
  2878.         $logSave->logSave(print_r($resulttrue), 'CGS''RSCarCGS');
  2879.         //print_r($result);
  2880.         //die;
  2881.         //close CURL resource
  2882.         curl_close($ch);
  2883.         /*
  2884.          * End API data send
  2885.          */
  2886.     }
  2887.     protected function authenticateUser(UserInterface $userLoginManagerInterface $loginManager)
  2888.     {
  2889.         try {
  2890.             $loginManager->loginUser(
  2891.                 'main',
  2892.                 $user
  2893.             );
  2894.         } catch (AccountStatusException $ex) {
  2895.             // We simply do not authenticate users which do not pass the user
  2896.             // checker (not enabled, expired, etc.).
  2897.         }
  2898.     }
  2899.     protected function getCurrencyExchange(AviaturWebService $webService) {
  2900.         $financialValue = [];
  2901.         $productInfo = new PackageModel();
  2902.         $hoy date('Y-m-d');
  2903.         $xmlTemplate $productInfo->getTasaCambio($hoy);
  2904.         $financial $webService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  2905.         $validate false;
  2906.         foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
  2907.             if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
  2908.                 $financialValue[mb_strtoupper($tasa->MONEDA_ORIGEN)] = number_format((float) (($tasa->VALOR)), 2'.''');
  2909.                 $validate true;
  2910.             }
  2911.         }
  2912.         if (!$validate) {
  2913.             $hoy date('Y-m-d'strtotime('-1 day'strtotime(date('Y-m-d'))));
  2914.             $xmlTemplate $productInfo->getTasaCambio($hoy);
  2915.             $financial $webService->callWebService('GENERALLAVE''dummy|http://www.aviatur.com.co/dummy/'$xmlTemplate);
  2916.             foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
  2917.                 if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
  2918.                     $financialValue[mb_strtoupper($tasa->MONEDA_ORIGEN)] = number_format((float) (($tasa->VALOR)), 2'.''');
  2919.                 }
  2920.             }
  2921.         }
  2922.         return $financialValue;
  2923.     }
  2924.     private function reorderCarsInfo($carsInfo){
  2925.         foreach ($carsInfo as $key1 => $carInfo) {
  2926.             $sizeCarInfo sizeof($carInfo->VehAvails->VehAvail);
  2927.             if($sizeCarInfo 1){
  2928.                 for ($ii $sizeCarInfo 1$ii 0$ii--) {
  2929.                     for ($jj $ii 1$jj >= 0$jj--) {
  2930.                         /* Para ir aplicando que no estén vacíos y que estén definidos */
  2931.                         if(isset($carsInfo[$key1]->VehAvails->VehAvail[$ii]) && isset($carsInfo[$key1]->VehAvails->VehAvail[$jj])){
  2932.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Vehicle) != json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Vehicle)){
  2933.                                 continue;
  2934.                             }
  2935.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->VehicleCharges) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->VehicleCharges)){
  2936.                                 continue;
  2937.                             }
  2938.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier->RateComments) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier->RateComments)){
  2939.                                 continue;
  2940.                             }
  2941.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier['RateCategory']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier['RateCategory'])){
  2942.                                 continue;
  2943.                             }
  2944.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier['RateQualifier']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier['RateQualifier'])){
  2945.                                 continue;
  2946.                             }
  2947.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier->RateRestrictions) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier->RateRestrictions)){
  2948.                                 continue;
  2949.                             }
  2950.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TotalCharge) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TotalCharge)){
  2951.                                 continue;
  2952.                             }
  2953.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Fees) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Fees)){
  2954.                                 continue;
  2955.                             }
  2956.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Reference['Type']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Reference['Type'])){
  2957.                                 continue;
  2958.                             }
  2959.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Reference['ID_Context']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Reference['ID_Context'])){
  2960.                                 continue;
  2961.                             }
  2962.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Reference['DateTime']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Reference['DateTime'])){
  2963.                                 continue;
  2964.                             }
  2965.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->VendorLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->VendorLocation)){
  2966.                                 continue;
  2967.                             }
  2968.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->DropOffLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->DropOffLocation)){
  2969.                                 continue;
  2970.                             }
  2971.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->LocalRate) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->LocalRate)){
  2972.                                 continue;
  2973.                             }
  2974.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->RateText) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->RateText)){
  2975.                                 continue;
  2976.                             }
  2977.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->VendorLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->VendorLocation)){
  2978.                                 continue;
  2979.                             }
  2980.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->DropOffLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->DropOffLocation)){
  2981.                                 continue;
  2982.                             }
  2983.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->rateType) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->rateType)){
  2984.                                 continue;
  2985.                             }
  2986.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->terms) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->terms)){
  2987.                                 continue;
  2988.                             }
  2989.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->freeText) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->freeText)){
  2990.                                 continue;
  2991.                             }
  2992.                             if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailInfo->PricedCoverages) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailInfo->PricedCoverages)){
  2993.                                 continue;
  2994.                             }
  2995.                             /* Al no cumplir con ninguno de los if, se determina que es igual y se elimina el objeto del índice ii */
  2996.                             unset($carsInfo[$key1]->VehAvails->VehAvail[$ii]);
  2997.                             break;
  2998.                         }
  2999.                     }
  3000.                 }
  3001.             }
  3002.         }
  3003.     }
  3004.     /**
  3005.      * getIINRanges()
  3006.      * Para obtener todos los rangos asociados a IIN de las franquicias activas, y estas se manejarán en variables globales con arrays de javascript
  3007.      * Author: Ing. David Rincon
  3008.      * Email: david.rincon@aviatur.com
  3009.      * Date: 2025/03/06
  3010.      * @param $em (Object of DB manager).
  3011.      * @return array
  3012.      */
  3013.     public function getIINRanges($em){
  3014.         $iinRecords $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findByActiveFranchises();
  3015.         $iinRecordsArray = [];
  3016.         $ccranges = [];
  3017.         $ccfranchises = [];
  3018.         foreach ($iinRecords as $key => $iinRecord) {
  3019.             $paymentGatewayCode $iinRecord["paymentgatewaycode"];
  3020.             $description $iinRecord["description"];
  3021.             $description strtoupper(str_replace(' '''trim($description)));
  3022.             $stringRanges $iinRecord["ranges"];
  3023.             $ranges json_decode($stringRangestrue);
  3024.             $stringLengths $iinRecord["lengths"];
  3025.             $lengths json_decode($stringLengthstrue);
  3026.             $luhn $iinRecord["luhn"];
  3027.             $cvvDigits $iinRecord["cvvdigits"];
  3028.             $tempLengths = [];
  3029.             foreach ($lengths["lengths"] as $length) {
  3030.                 $tempLengths[] = array(=> $length[0], => (isset($length[1]) ? $length[1] : $length[0]));
  3031.             }
  3032.             $tempRecordArrayFranchises = [];
  3033.             $tempRecordArrayFranchises["code"] = $paymentGatewayCode;
  3034.             $tempRecordArrayFranchises["codename"] = $description;
  3035.             $tempRecordArrayFranchises["luhn"] = $luhn;
  3036.             $tempRecordArrayFranchises["length"] = $tempLengths;
  3037.             $tempRecordArrayFranchises["cvvd"] = $cvvDigits;
  3038.             $ccfranchises[$paymentGatewayCode] = $tempRecordArrayFranchises;
  3039.             foreach ($ranges["ranges"] as $range) {
  3040.                 $tempRecordArrayRanges = [];
  3041.                 $tempRecordArrayRanges["range"][0] = $range[0];
  3042.                 $tempRecordArrayRanges["range"][1] = (isset($range[1]) ? $range[1] : $range[0]);
  3043.                 $tempRecordArrayRanges["minimum"] = strlen($range[0]);
  3044.                 $tempRecordArrayRanges["code"] = $paymentGatewayCode;
  3045.                 $ccranges[] = $tempRecordArrayRanges;
  3046.             }
  3047.         }
  3048.         $iinRecordsArray = array("ccranges" => $ccranges"ccfranchises" => $ccfranchises);
  3049.         return $iinRecordsArray;
  3050.     }
  3051. }