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

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