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

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