src/Controller/Front/Product/HotelController.php line 653

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front\Product;
  3. use App\Config\FaqRouteEnum;
  4. use App\Config\ModuleEnum;
  5. use App\Entity\ApiLog;
  6. use App\Entity\CustomerMoral;
  7. use App\Entity\HotelAvailabilityRequest;
  8. use App\Module\Attribute\RequiresModule;
  9. use App\Repository\CityRepository;
  10. use App\Repository\FrontThemeRepository;
  11. use App\Repository\HotelXmlPriceRepository;
  12. use App\Repository\HotelXmlRepository;
  13. use App\Repository\OrderLineRepository;
  14. use App\Repository\OrderRepository;
  15. use App\Repository\UserRepository;
  16. use App\Service\Api3TAuthenticationService;
  17. use App\Service\ApiLogService;
  18. use App\Service\CartService;
  19. use App\Service\CurrencyService;
  20. use App\Service\FrontRecentSearchService;
  21. use App\Service\FrontService;
  22. use App\Service\Helpers;
  23. use App\Service\HotelApiService;
  24. use App\Service\HotelOfferDetailsService;
  25. use App\Service\HotelSearchStreamService;
  26. use App\Service\ParameterService;
  27. use DateTime;
  28. use Exception;
  29. use Gedmo\Translatable\TranslatableListener;
  30. use Psr\Log\LoggerInterface;
  31. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  32. use Symfony\Component\HttpClient\HttpClient;
  33. use Symfony\Component\HttpFoundation\JsonResponse;
  34. use Symfony\Component\HttpFoundation\RedirectResponse;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpFoundation\Response;
  37. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  38. use Symfony\Component\HttpFoundation\StreamedResponse;
  39. use Symfony\Component\Routing\Annotation\Route;
  40. use Psr\Cache\CacheItemPoolInterface;
  41. use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
  42. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  43. use Symfony\Contracts\HttpClient\HttpClientInterface;
  44. use Symfony\Contracts\Translation\TranslatorInterface;
  45. use App\Service\CacheResolverService;
  46. #[Route('/hotel')]
  47. #[RequiresModule(ModuleEnum::hotel)]
  48. class HotelController extends AbstractController
  49. {
  50.     private const UNNORMALIZED_CACHE_PREFIX = 'hub_unnormalized_rooms_';
  51.     private const UNNORMALIZED_CACHE_TTL = 600; // 10 min
  52.     private const PAGES_COUNT_TTL = 604800;         // 7 jours
  53.     private const PAGES_COUNT_REFRESH_AFTER = 3600; // rafraîchir en fin de stream si > 1h
  54.     public function __construct(
  55.         private readonly Api3TAuthenticationService $apiAuthenticationService,
  56.         private readonly HotelApiService            $hotelApiService,
  57.         private readonly CurrencyService            $currencyService,
  58.         private readonly FrontService               $frontService,
  59.         private readonly ParameterService           $parameterService,
  60.         private readonly Helpers                    $helpers,
  61.         private readonly LoggerInterface            $logger,
  62.         private readonly CacheItemPoolInterface     $searchCachePool,
  63.         private readonly translatorInterface        $translator,
  64.         private readonly CacheResolverService $cacheResolverService,
  65.         private readonly ApiLogService $apiLogService,
  66.         private readonly UserRepository $userRepository,
  67.     )
  68.     {
  69.     }
  70.     #[Route('/hotelcity/{name}', name: 'app_front_hotel_city')]
  71.     public function hotelByCity(
  72.         string                  $name,
  73.         CityRepository          $cityRepository,
  74.         HotelXmlPriceRepository $hotelXmlPriceRepository,
  75.         FrontService            $frontService
  76.     ): Response
  77.     {
  78.         $hotels = [];
  79.         $city = $cityRepository->findOneBy(['name' => $name]);
  80.         $description = "";
  81.         $country = "";
  82.         if ($city) {
  83.             $description = $city->getDescription();
  84.             $country = $city->getCountry()->getName();
  85.         }
  86.         $hotelXmlPrices = $hotelXmlPriceRepository->getHotelXmlPriceByCriterias(['cities' => [$name]]);
  87.         foreach ($hotelXmlPrices as $HotelXmlPrice) {
  88.             $hotels[] = $frontService->getItemHotel($HotelXmlPrice);
  89.         }
  90.         return $this->render('front/hotel/hotel_by_city.html.twig', [
  91.             'hotels' => $hotels,
  92.             'city' => $city,
  93.             'name' => $name,
  94.             'country' => $country,
  95.             'society' => $this->parameterService->getSocietyParameters(),
  96.             'social_networks' => $this->frontService->getSocialNetworks(),
  97.             'agencies' => $this->frontService->getAgencies(),
  98.             'currencies' => $this->frontService->getCurrencies(),
  99.             'currencySwitcher' => true,
  100.             'tracking_tools' => $this->frontService->getTrackingTools(),
  101.             'faqs' => $this->frontService->getFaqs(FaqRouteEnum::APP_FRONT_HOTEL_CITY, strtolower($name)),
  102.         ]);
  103.     }
  104.     #[Route('/hoteltheme/{name}', name: 'app_front_hotel_theme')]
  105.     public function hotelByTheme(
  106.         string                  $name,
  107.         FrontThemeRepository    $frontThemeRepository,
  108.         HotelXmlPriceRepository $hotelXmlPriceRepository,
  109.         FrontService            $frontService
  110.     ): Response
  111.     {
  112.         $hotels = [];
  113.         $theme = $frontThemeRepository->findOneBy(['name' => $name]);
  114.         $description = "";
  115.         if ($theme) {
  116.             $description = $theme->getDescription();
  117.         }
  118.         $hotelXmlPrices = $hotelXmlPriceRepository->getHotelXmlPriceByCriterias(['themes' => $name]);
  119.         foreach ($hotelXmlPrices as $HotelXmlPrice) {
  120.             $hotels[] = $frontService->getItemHotel($HotelXmlPrice);
  121.         }
  122.         return $this->render('front/hotel/hotel_by_theme.html.twig', [
  123.             'hotels' => $hotels,
  124.             'description' => $description,
  125.             'name' => $name,
  126.             'society' => $this->parameterService->getSocietyParameters(),
  127.             'social_networks' => $this->frontService->getSocialNetworks(),
  128.             'agencies' => $this->frontService->getAgencies(),
  129.             'currencies' => $this->frontService->getCurrencies(),
  130.             'tracking_tools' => $this->frontService->getTrackingTools()
  131.         ]);
  132.     }
  133.     #[Route('/search', name: 'hotel_search', methods: ['GET', 'POST'])]
  134.     public function hotelSearch(Request $request, FrontRecentSearchService $frontRecentSearchService): Response
  135.     {
  136.         $data = $request->get("data"); // data : JSON request
  137.         $requestData = json_decode($data, true);
  138.         $date = new DateTime();
  139.         // Output the date in default format
  140.         $currentDate = $date->format('Y-m-d'); // Example: 2025-01-02 15:30:45
  141.         if ($requestData['checkIn'] < $currentDate || $requestData['checkOut'] < $currentDate) {
  142.             return $this->redirectToRoute('app_main');
  143.         }
  144.         $user = $this->getUser();
  145.         $customer = $this->apiAuthenticationService->getCustomer($this->getUser());
  146.         if (is_null($customer)) {
  147.             $this->addFlash('info', $this->translator->trans(
  148.                 'Pages.Common.Messages.SELECT_CUSTOMER_TO_CONTINUE_BOOKING',
  149.                 [],
  150.                 'messages_front'
  151.             ));
  152.             return $this->redirectToRoute('front_info_message');
  153.         }
  154.         $auth_data = $this->apiAuthenticationService->getAuthenticationArray($user);
  155.         if (is_null($auth_data)) {
  156.             $this->addFlash('info', $this->translator->trans(
  157.                 'Pages.Common.Messages.SELECT_CUSTOMER_TO_CONTINUE_BOOKING',
  158.                 [],
  159.                 'messages_front'
  160.             ));
  161.             return $this->redirectToRoute('front_info_message');
  162.         }
  163.         $hotel_search_history = $frontRecentSearchService->updateHotelSearchHistory($requestData, $data);
  164.         $isSearchByMap = $this->parameterService->isSearchMap();
  165.         return $this->render('front/hotel/search.html.twig', [
  166.             'requestData' => $requestData,
  167.             'customer' => $customer,
  168.             'society' => $this->parameterService->getSocietyParameters(),
  169.             'social_networks' => $this->frontService->getSocialNetworks(),
  170.             'agencies' => $this->frontService->getAgencies(),
  171.             'currencies' => $this->frontService->getCurrencies(),
  172.             'hotel_search_history' => $hotel_search_history,
  173.             'sections' => $this->frontService->getSections(),
  174.             'currencySwitcher' => true,
  175.             'tracking_tools' => $this->frontService->getTrackingTools(),
  176.             'isSearchByMap' => $isSearchByMap,
  177.         ]);
  178.     }
  179.     #[Route('/formsearch/{city_label}/{hotel_label}/{hotel_id}', name: 'hotel_form_search', defaults: ['hotel_id' => null], methods: ['GET', 'POST'])]
  180.     public function hotelFormSearch(Request $request, string $city_label, string $hotel_label,?string $hotel_id): Response
  181.     {
  182.         $requestData = json_decode($request->get("data"), true);
  183.         return $this->render('front/hotel/form_search.html.twig', [
  184.             'requestData' => $requestData,
  185.             'hotel_label' => $hotel_label,
  186.             'city_label' => $city_label,
  187.             'hotel_id' => $hotel_id
  188.             /* 'society' => $this->parameterService->getSocietyParameters(),
  189.              'social_networks' => $this->frontService->getSocialNetworks(),
  190.              'agencies' => $this->frontService->getAgencies(),
  191.              'currencies' => $this->frontService->getCurrencies(),*/
  192.         ]);
  193.     }
  194.     #[Route('/search_json', name: 'hotel_search_json', methods: ['GET', 'POST'])]
  195.     public function hotelSearchJson(Request $request, HotelApiService $hotelApiService): JsonResponse
  196.     {
  197.         // ----- PREPARE the HttpRequestCall ----- //
  198.         // Get auth_data : user, timestamp, signature
  199.         $user = $this->getUser();
  200.         $auth_data = $this->apiAuthenticationService->getAuthenticationArray($user);
  201.         $customer = $this->apiAuthenticationService->getCustomer($user);
  202.         $showResellingRates = false;
  203.         if ($customer instanceof CustomerMoral) {
  204.             if ($customer->getResellerMargin() > 0 && (in_array('ROLE_B2B_ADMIN', $user->getRoles()) || in_array('ROLE_B2B_AGENT', $user->getRoles()))) {
  205.                 $showResellingRates = true;
  206.             }
  207.         }
  208.         $requestJson = json_decode($request->getContent(), true);
  209.         $xmlSourceId = $request->headers->get('xmlSourceId') ?? 0;
  210.         $base_uri = $request->getSchemeAndHttpHost();
  211.         // ----- PERFORM the HttpRequestCall ----- //
  212.         $data = $hotelApiService->query_ApiHotel_Availability($auth_data, $requestJson, $xmlSourceId, $base_uri, true);
  213.         $today = DateTime::createFromFormat("Y-m-d", date("Y-m-d"));
  214.         if (count($data['content']) > 0) { // Re-format data to fit the FRONT-B2C :::: VIEW_BY_BOARD ::::
  215.             $nbRooms = count($requestJson['occupancies']);
  216.             $content_front = []; // prepare data to fit the front design
  217.             foreach ($data['content'] as $hotel) {
  218.                 $hotel_key = strtoupper($hotel['hotel']['name']); // HOTEL_ITEM_IDENTIFIER TO GROUP MULTIPLE HOTELS WITH SAME NAME
  219.                 $hotel_offer_count = 0;
  220.                 if (isset($content_front[$hotel_key]['offersCount'])) {
  221.                     $hotel_offer_count = $content_front[$hotel_key]['offersCount'];
  222.                 }
  223.                 $content_front[$hotel_key]['hotel'] = $hotel['hotel'];
  224.                 $content_front[$hotel_key]['hotel']['customRating'] = $this->hotelApiService->getHotelCustomRating($hotel['hotel']['name']);
  225.                 // TODO Add function getReviewRating(hotelName, reviewsSource);
  226.                 $content_front[$hotel_key]['hotel']['reviewRating'] = null;//rand(4, 10); // TODO GET RATING FROM External src like Tripadvisor
  227.                 if (count($hotel['sources']) > 0) {
  228.                     $content_front[$hotel_key]['hotel']['facilities'] = $hotel['sources'][0]['facilities'];
  229.                 }
  230.                 $content_front[$hotel_key]['hotel']['promos'] = [];
  231.                 $content_front[$hotel_key]['hotel']['discounts'] = [];
  232.                 $content_front[$hotel_key]['hotel']['infos'] = [];
  233.                 foreach ($hotel['sources'] as $hotel_source) {
  234.                     $sourceKey = $hotel['hotel']['id']; // considering the full-hotel-id as the sourceKey (string containing the end-source-id)
  235.                     $content_front[$hotel_key]['sources'][$sourceKey]['sourceKey'] = $sourceKey;
  236.                     $hotelSourcePrice = 0;
  237.                     $hotelSourceAvailable = false;
  238.                     $hotelSourceFreeCancellation = false;
  239.                     $tab_boards = [];
  240.                     foreach ($hotel_source['rooms'] as $index => $index_hrts) { // room_index
  241.                         // SORT hrts for current hotel-source by salePromoRate
  242.                         usort($index_hrts, function ($a, $b) {
  243.                             return $a['salePromoRate'] <=> $b['salePromoRate']; // Ascending
  244.                         });
  245.                         foreach ($index_hrts as $hrt) {
  246.                             // freeCancellation FLAG to use in React Filter (i.e. is there a possibility to cancel without fees )
  247.                             if ($hrt['NRF']) {
  248.                                 $hrt['freeCancellation'] = false;
  249.                             } else {
  250.                                 if (is_null($hrt['deadline'])) {
  251.                                     $hrt['freeCancellation'] = true;
  252.                                 } else {
  253.                                     $deadline = new DateTime($hrt['deadline']);
  254.                                     $difference = date_diff($today, $deadline); // Interval before deadline.
  255.                                     if ($difference->invert) { // deadline is exceeded
  256.                                         $hrt['freeCancellation'] = false;
  257.                                     } else {
  258.                                         $hrt['freeCancellation'] = true;
  259.                                     }
  260.                                 }
  261.                             }
  262.                             $hotelSourceFreeCancellation = $hotelSourceFreeCancellation || $hrt['freeCancellation'];
  263.                             // END freeCancellation FLAG
  264.                             // SHOW SaleResellingRates rather thant saleRate applied to the customer
  265.                             if ($showResellingRates) {
  266.                                 $hrt['salePromoRate'] = $hrt['salePromoRate'] * (100.0 + $customer->getResellerMargin()) / 100.0;
  267.                                 $hrt['saleRate'] = $hrt['saleRate'] * (100.0 + $customer->getResellerMargin()) / 100.0;
  268.                             }
  269.                             $content_front[$hotel_key]['sources'][$sourceKey]['hrts'][$hrt['boardName']][$index][] = $hrt;
  270.                             $tab_boards[$hrt['boardName']] = $hrt['boardXmlName'];
  271.                             // Increment the number of available-offers
  272.                             if ($hrt['available']) {
  273.                                 $hotel_offer_count++;
  274.                                 $hotelSourceAvailable = true;
  275.                             }
  276.                         }
  277.                     } // END Room Indexes
  278.                     // HOTEL BADGES (Promos, Discounts, Infos)
  279.                     foreach ($hotel_source['promos'] as $item) {
  280.                         $content_front[$hotel_key]['hotel']['promos'][] = $item;
  281.                     }
  282.                     foreach ($hotel_source['discounts'] as $item) {
  283.                         $content_front[$hotel_key]['hotel']['discounts'][] = $item;
  284.                     }
  285.                     foreach ($hotel_source['infos'] as $item) {
  286.                         $content_front[$hotel_key]['hotel']['infos'][] = $item;
  287.                     }
  288.                     $bestOffers = $this->hotelApiService->getBestPriceBoard($content_front[$hotel_key], $sourceKey);
  289.                     $content_front[$hotel_key]['sources'][$sourceKey]['bestPrice'] = $bestOffers['bestPrice_currentSourceKey'];
  290.                     $content_front[$hotel_key]['bestPrice'] = $bestOffers['bestPrice'];
  291.                     $content_front[$hotel_key]['bestBoard'] = $bestOffers['bestBoard'];
  292.                     $content_front[$hotel_key]['bestRooms'] = !empty($sourceBest['bestRooms'])
  293.                         ? $this->helpers->formatArrayCounts($sourceBest['bestRooms'])
  294.                         : '';
  295.                     $content_front[$hotel_key]['offersCount'] = $hotel_offer_count;
  296.                     foreach ($content_front[$hotel_key]['sources'][$sourceKey]['hrts'] as $board_key => $board_hrts) {
  297.                         if (count($board_hrts) < $nbRooms) {
  298.                             unset($content_front[$hotel_key]['sources'][$sourceKey]['hrts'][$board_key]);
  299.                         }
  300.                     }
  301.                     foreach ($tab_boards as $board_key => $board_value) {
  302.                         $content_front[$hotel_key]['sources'][$sourceKey]['boards'][] =
  303.                             [
  304.                                 'key' => $board_value,
  305.                                 'value' => $board_value,
  306.                             ];
  307.                     }
  308.                     // set general stock
  309.                     $content_front[$hotel_key]['sources'][$sourceKey]['generalStock'] = $hotel_source['generalStock'];
  310.                     // set search code
  311.                     $content_front[$hotel_key]['sources'][$sourceKey]['searchCode'] = $hotel_source['searchCode'];
  312.                     // set source id
  313.                     $content_front[$hotel_key]['sources'][$sourceKey]['xmlSourceId'] = $hotel_source['xmlSourceId'];
  314.                     // set xml source name
  315.                     $content_front[$hotel_key]['sources'][$sourceKey]['xmlSourceName'] = $hotel_source['xmlSourceName'];
  316.                     // set hotel Source available
  317.                     $content_front[$hotel_key]['sources'][$sourceKey]['available'] = $hotelSourceAvailable;
  318.                     // set hotel Source available
  319.                     $content_front[$hotel_key]['sources'][$sourceKey]['freeCancellation'] = $hotelSourceFreeCancellation;
  320.                     // set hotel Source available
  321.                     $content_front[$hotel_key]['sources'][$sourceKey]['associationRequired'] = $hotel_source['associationRequired'];
  322.                 }
  323.             }
  324.             // array values hotels
  325.             $data['content'] = array_values($content_front);
  326.             // array values sources
  327.             foreach ($data['content'] as &$hotel) {
  328.                 usort($hotel['sources'], function ($a, $b) {
  329.                     return $a['bestPrice'] <=> $b['bestPrice']; // Ascending
  330.                 });
  331.                 $hotel['sources'] = array_values($hotel['sources']);
  332.                 foreach ($hotel['sources'] as &$source) {
  333.                     $source['hrts'] = array_values($source['hrts']);
  334.                 }
  335.             }
  336.         }
  337.         return $this->json($data);
  338.     }
  339.     #[Route('/autocomplete', name: 'hotel_autocomplete', methods: ['GET'])]
  340.     public function autoComplete(Request $request): JsonResponse
  341.     {
  342.         $query = $request->query->get('query');
  343.         if ($query == null) {
  344.             return $this->json([]);
  345.         }
  346.         $query_trim = trim($query);
  347.         $headers = [
  348.             'Accept' => 'application/json',
  349.             'Content-Type' => 'application/json',
  350.         ];
  351.         try {
  352.             $httpClient = HttpClient::create();
  353.             $response = $httpClient->request('GET', $request->getSchemeAndHttpHost() . '/api/hotel/autocomplete', [
  354.                 'headers' => $headers,
  355.                 'query' => ['query' => $query_trim]
  356.             ]);
  357.             $data = json_decode($response->getContent(), true);
  358.             return $this->json($data['response']);
  359.         } catch (Exception $e) {
  360.             return $this->json(['error' => $e->getMessage()]);
  361.         }
  362.     }
  363.     /**
  364.      * The detail of selected offer from the front : hotel search results page. --- Check-Rate ---
  365.      * Supposed to be called either from "hotel/search or "orderline_add_room"
  366.      */
  367.     #[Route('/offer-detail', name: 'hotel_offer_detail', methods: ['GET', 'POST'])]
  368.     public function hotelOfferDetail(
  369.         Request             $request,
  370.         OrderLineRepository $orderLineRepository,
  371.         OrderRepository     $orderRepository,
  372.     ): Response
  373.     {
  374.         $guestData = [];
  375.         if ($request->isMethod('POST')) {
  376.             $guestData = [
  377.                 'first_name' => $request->request->get('first_name'),
  378.                 'last_name' => $request->request->get('last_name'),
  379.                 'phone' => $request->request->get('phone'),
  380.                 'email' => $request->request->get('email'),
  381.             ];
  382.             $request->getSession()->set('guestData', $guestData);
  383.         }
  384.         $customer = $this->apiAuthenticationService->getCustomer($this->getUser());
  385.         $auth_data = $this->apiAuthenticationService->getAuthenticationArray($this->getUser());
  386.         $rooms_rate_keys = [];
  387.         for ($i = 0; $i < $request->get('nbRooms'); $i++) {
  388.             $rooms_rate_keys[] = ["rateKey" => $request->get("room-" . $i)];
  389.         }
  390.         $checkRateRequest = [
  391.             'rooms' => $rooms_rate_keys,
  392.             'searchCode' => $request->get('searchCode')
  393.         ];
  394.         $saleCurrency = $this->currencyService->getSessionCurrency();
  395.         $product_fee = $this->frontService->getProductFee(ModuleEnum::hotel->getValue(), $customer);
  396.         /** call api/hotel/checkrate */
  397.         $httpClient = HttpClient::create();
  398.         $response = $httpClient->request(
  399.             'POST', $request->getUriForPath('/') . 'api/hotel/checkrate',
  400.             [
  401.                 'headers' => [
  402.                     'Accept' => 'application/json',
  403.                     'Content-Type' => 'application/json',
  404.                     'currency' => $saleCurrency,
  405.                     'user' => $auth_data['user'],
  406.                     'timestamp' => $auth_data['timestamp'],
  407.                     'signature' => hash('sha256', $auth_data['signature'])
  408.                 ],
  409.                 'json' => $checkRateRequest
  410.             ]
  411.         );
  412.         $responseData = json_decode($response->getContent(), true);
  413.         $searchCriteriaArray = json_decode($request->get("searchCriteria"), true);
  414.         $twig_parameters = [
  415.             'searchCriteriaArray' => $searchCriteriaArray,
  416.             'searchCode' => null,
  417.             'checkRateData' => null,
  418.             "social_networks" => $this->frontService->getSocialNetworks(),
  419.             'menu_front' => $this->frontService->getFrontMenu(),
  420.             "currencies" => $this->frontService->getCurrencies(),
  421.             "agencies" => $this->frontService->getAgencies(),
  422.             "society" => $this->parameterService->getSocietyParameters(),
  423.             "referenceCurrency" => $this->parameterService->getReferenceCurrency(),
  424.             'guestData' => $guestData,
  425.             'action' => '',
  426.             'customer' => $customer
  427.         ];
  428.         $template = "";
  429.         if (is_null($responseData) or $responseData['error']) {
  430.             // CASE 0 : Template for Error
  431.             return $this->render("front/hotel/offer_error.html.twig", $twig_parameters);
  432.         } else {
  433.             $checkRateData = reset($responseData['content']);
  434.             $checkRateData['available'] = $this->hotelApiService->isAvailable($checkRateData) ? "true" : "false";
  435.             $rooms = [];
  436.             foreach ($checkRateData['sources'][0]['rooms'] as $room_index) {
  437.                 $rooms[] = $room_index[0]; // the selected room for the index.
  438.             }
  439.             //$checkRateData['cancellation'] = $this->hotelApiService->getDeadlineFromRooms($rooms);
  440.             $twig_parameters['checkRateData'] = $checkRateData;
  441.             $twig_parameters['searchCode'] = $responseData['searchCode'];
  442.             $twig_parameters['product_fee'] = $product_fee;
  443.             $twig_parameters['META_PIXEL_ID'] = $this->parameterService->getTrackerMetaId();
  444.             // CASE 1 : Template to add something to an existing orderline
  445.             if ($request->get('orderlineId')) {
  446.                 $orderlineID = $request->get('orderlineId');
  447.                 $twig_parameters['orderLine'] = $orderLineRepository->find($orderlineID);
  448.                 $twig_parameters['action'] = $this->generateUrl("orderline_add_room", ['id' => $orderlineID]);
  449.             }
  450.             // CASE 2 : new Order and new OrderLine
  451.             if (empty($request->get('orderlineId')) && empty($request->get('orderId'))) { //
  452.                 $twig_parameters['action'] = $this->generateUrl("app_admin_add_cart_line_hotel");
  453.             }
  454.             // CASE 3 : Add new OrderLine into an existing Order
  455.             if (empty($request->get('orderlineId')) && $request->get('orderId')) { //
  456.                 $orderID = $request->get('orderId');
  457.                 $twig_parameters['order'] = $orderRepository->find($orderID);
  458.                 $twig_parameters['action'] = $this->generateUrl("order_add_orderline_hotel_book", ['id' => $orderID]);
  459.             }
  460.             return $this->render("front/hotel/offer_detail.html.twig", $twig_parameters);
  461.         }
  462.     }
  463.     #[Route('/chatbot/hotelBook', name: 'chatbot_hotel_book', methods: ['GET', 'POST'])]
  464.     public function chatbotHotelBook(
  465.         Request             $request,
  466.         OrderLineRepository $orderLineRepository,
  467.         OrderRepository     $orderRepository,
  468.         HttpClientInterface $httpClient,
  469.     ): Response
  470.     {
  471.         $customer = $this->apiAuthenticationService->getCustomer($this->getUser());
  472.         $auth_data = $this->apiAuthenticationService->getAuthenticationArray($this->getUser());
  473.         $saleCurrency = $this->currencyService->getSessionCurrency();
  474.         $product_fee = $this->frontService->getProductFee(ModuleEnum::hotel->getValue(), $customer);
  475.         // Was hardcoded as "azerty" in two places (decrypt key + generateSearchCode arg).
  476.         // Pull from parameters/env instead of literal strings in code.
  477.         $secretKey = $this->getParameter('app.hotel_ratekey_secret');
  478.         $ratekeysParam = $request->query->get('ratekeys', '');
  479.         $rawRateKeys = array_filter(array_map('trim', explode('@@@@', $ratekeysParam)));
  480.         try {
  481.             $parsed = $this->parseRateKeys($rawRateKeys, $secretKey);
  482.         } catch (\Throwable $e) {
  483.             // Any malformed rate key (bad format, missing segments, bad date) lands here
  484.             // instead of throwing a raw ErrorException back to the client.
  485.             return $this->renderOfferError();
  486.         }
  487.         if (empty($parsed['rooms_rate_keys'])) {
  488.             return $this->renderOfferError();
  489.         }
  490.         $searchCode = $this->generateSearchCode($secretKey, $saleCurrency);
  491.         $checkRateRequest = [
  492.             'rooms' => $parsed['rooms_rate_keys'],
  493.             'searchCode' => $searchCode,
  494.         ];
  495.         $response = $httpClient->request(
  496.             'POST',
  497.             $request->getUriForPath('/') . 'api/hotel/checkrate',
  498.             [
  499.                 'headers' => [
  500.                     'Accept' => 'application/json',
  501.                     'Content-Type' => 'application/json',
  502.                     'currency' => $saleCurrency,
  503.                     'user' => $auth_data['user'],
  504.                     'timestamp' => $auth_data['timestamp'],
  505.                     'signature' => hash('sha256', $auth_data['signature']),
  506.                 ],
  507.                 'json' => $checkRateRequest,
  508.             ]
  509.         );
  510.         $responseData = json_decode($response->getContent(), true);
  511.         if (!is_array($responseData) || !empty($responseData['error'] ?? null) || empty($responseData['content'])) {
  512.             return $this->renderOfferError();
  513.         }
  514.         $searchCriteriaArray = [
  515.             'destination' => [
  516.                 'id' => $parsed['cityId'],
  517.                 'name' => $responseData['content'][0]['hotel']['name'] ?? '',
  518.                 'type' => 'hotel',
  519.             ],
  520.             'checkIn' => $parsed['checkIn'],
  521.             'checkOut' => $parsed['checkOut'],
  522.             'rooms' => $parsed['jsonOccupation'],
  523.         ];
  524.         $twig_parameters = [
  525.             'searchCriteriaArray' => $searchCriteriaArray,
  526.             'searchCode' => null,
  527.             'checkRateData' => null,
  528.             'social_networks' => $this->frontService->getSocialNetworks(),
  529.             'menu_front' => $this->frontService->getFrontMenu(),
  530.             'currencies' => $this->frontService->getCurrencies(),
  531.             'agencies' => $this->frontService->getAgencies(),
  532.             'society' => $this->parameterService->getSocietyParameters(),
  533.             'referenceCurrency' => $this->parameterService->getReferenceCurrency(),
  534.             'guestData' => [],
  535.             'action' => '',
  536.             'customer' => $customer,
  537.         ];
  538.         $checkRateData = reset($responseData['content']);
  539.         $checkRateData['available'] = $this->hotelApiService->isAvailable($checkRateData) ? 'true' : 'false';
  540.         $twig_parameters['checkRateData'] = $checkRateData;
  541.         $twig_parameters['searchCode'] = $responseData['searchCode'] ?? $searchCode;
  542.         $twig_parameters['product_fee'] = $product_fee;
  543.         $twig_parameters['META_PIXEL_ID'] = $this->parameterService->getTrackerMetaId();
  544.         $twig_parameters['action'] = $this->generateUrl('app_admin_add_cart_line_hotel');
  545.         return $this->render('front/hotel/offer_detail.html.twig', $twig_parameters);
  546.     }
  547.     /**
  548.      *  The detail of a given hotelId
  549.      */
  550.     #[Route('/{country_label}/{city_label}/{hotel_label}/{id}', name: 'hotel_detail', methods: ['GET'])]
  551.     public function hotelDetail(
  552.         Request            $request,
  553.                            $id,
  554.         string             $city_label,
  555.         string             $hotel_label,
  556.         HotelXmlRepository $hotelXmlRepository
  557.     ): Response
  558.     {
  559.         $uid = $id; // source@uid
  560.         $hotel_source = strstr($uid, '@', true); // left subString before @
  561.         $hotel_uid = substr(strstr($uid, '@'), 1); // right subString after -
  562.         if ($hotel_source == 0) {
  563.             $hotelDetails = $this->hotelApiService->hotelDetails($hotel_uid, $request->getLocale());
  564.         } else {
  565.             $hotelDetails = $this->hotelApiService->hotelDetailsHUB($hotel_uid);
  566.         }
  567.         // hotelDetailsHUB renvoie [message] en cas d'erreur : on le traite comme « hôtel introuvable »
  568.         if (!isset($hotelDetails['name'])) {
  569.             $hotelDetails = [];
  570.         }
  571.         //$recommendedHotels = $hotelXmlRepository->getRecommendedHotels($city_label, $hotel_uid);
  572.         $recommendedHotels = [];
  573.         //dd(count($recommendedHotels));
  574.         // Dates du moteur « Vérifier la disponibilité » : ?checkIn=&checkOut= (Y-m-d) si valides, sinon aujourd'hui / demain
  575.         $arrivalDate = (new DateTime())->format('Y-m-d');
  576.         $departureDate = (new DateTime('tomorrow'))->format('Y-m-d');
  577.         $requestedCheckIn = DateTime::createFromFormat('!Y-m-d', (string)$request->query->get('checkIn'));
  578.         $requestedCheckOut = DateTime::createFromFormat('!Y-m-d', (string)$request->query->get('checkOut'));
  579.         if ($requestedCheckIn && $requestedCheckOut
  580.             && $requestedCheckIn->format('Y-m-d') >= $arrivalDate
  581.             && $requestedCheckOut > $requestedCheckIn) {
  582.             $arrivalDate = $requestedCheckIn->format('Y-m-d');
  583.             $departureDate = $requestedCheckOut->format('Y-m-d');
  584.         }
  585.         return $this->render('front/hotel/hotel_detail.html.twig', [
  586.             'hotel_data' => $hotelDetails,
  587.             'society' => $this->parameterService->getSocietyParameters(),
  588.             'social_networks' => $this->frontService->getSocialNetworks(),
  589.             'currencies' => $this->frontService->getCurrencies(),
  590.             'agencies' => $this->frontService->getAgencies(),
  591.             'menu_front' => $this->frontService->getFrontMenu(),
  592.             'recommendedHotels' => $recommendedHotels,
  593.             "arrivalDate" => $arrivalDate,
  594.             "departureDate" => $departureDate,
  595.             "city_label" => $city_label,
  596.             "hotel_label" => $hotel_label,
  597.             "META_PIXEL_ID" => $this->parameterService->getTrackerMetaId(),
  598.             'faqs' => $this->frontService->getFaqs(FaqRouteEnum::HOTEL_DETAIL, $uid),
  599.         ]);
  600.     }
  601.     #[Route('/{id}/gallery', name: 'hotel_gallery_json', methods: ['GET'])]
  602.     public function hotelGallery(
  603.         Request $request,
  604.                 $id
  605.     ): JsonResponse
  606.     {
  607.         $auth_data = $this->apiAuthenticationService->getAuthenticationArray($this->getUser());
  608.         // call hotel detail and get images
  609.         $hotelDetailsRequest = [
  610.             'hotelId' => $id
  611.         ];
  612.         $httpClient = HttpClient::create();
  613.         $response = $httpClient->request(
  614.             'POST', $request->getUriForPath('/') . 'api/hotel/details',
  615.             [
  616.                 'headers' => [
  617.                     'Accept' => 'application/json',
  618.                     'Content-Type' => 'application/json',
  619.                     'user' => $auth_data['user'],
  620.                     'timestamp' => $auth_data['timestamp'],
  621.                     'signature' => hash('sha256', $auth_data['signature'])
  622.                 ],
  623.                 'json' => $hotelDetailsRequest
  624.             ]
  625.         );
  626.         $responseData = json_decode($response->getContent(), true);
  627.         if (is_null($responseData) || !key_exists('content', $responseData)) {
  628.             return $this->json([]);
  629.         }
  630.         $hotel_data_array = $responseData['content']['images'];
  631.         return $this->json($hotel_data_array);
  632.     }
  633.     /**
  634.      * @throws Exception
  635.      */
  636.     #[Route('/promo', name: 'app_front_hotel_promo', methods: ['GET'])]
  637.     public function hotelPromo(HotelXmlPriceRepository $hotelXmlPriceRepository,
  638.                                FrontService            $frontService
  639.     ): Response
  640.     {
  641.         $hotels = [];
  642.         $hotelXmlPricesWithPromos = $hotelXmlPriceRepository->getHotelXmlPriceWithPromos();
  643.         foreach ($hotelXmlPricesWithPromos as $hotelXmlPricesWithPromo) {
  644.             $hotels[] = $frontService->getItemHotel($hotelXmlPricesWithPromo);
  645.         }
  646.         return $this->render('front/hotel/hotel_promo.html.twig', [
  647.             'hotelsWithPromos' => $hotels,
  648.             'social_networks' => $this->frontService->getSocialNetworks(),
  649.             'currencies' => $this->frontService->getCurrencies(),
  650.             'agencies' => $this->frontService->getAgencies(),
  651.             'society' => $this->parameterService->getSocietyParameters(),
  652.             'currencySwitcher' => true,
  653.             'META_PIXEL_ID' => $this->parameterService->getTrackerMetaId()
  654.         ]);
  655.     }
  656.     #[Route('/cart/addProductHotel', name: 'app_admin_add_cart_line_hotel', methods: ['POST'])]
  657.     public function addProductHotel(
  658.         Request          $request,
  659.         SessionInterface $session,
  660.         CartService      $cartService,
  661.     ): RedirectResponse
  662.     {
  663.         $cart_array = $cartService->initCart($this->getUser(), $request);
  664.         /* 2- add a line into cart_array['products'] */
  665.         $nbRooms = $request->get("nbRooms"); // quantity : nbRooms
  666.         $cart_line_label = $request->get('product_label');
  667.         $cart_line_date = $request->get('product_date');
  668.         $beneficiaryName = $request->get('beneficiary_name');
  669.         if (empty($beneficiaryName)) {
  670.             $beneficiaryFirstName = trim((string)$request->get('beneficiary_first_name', ''));
  671.             $beneficiaryLastName = trim((string)$request->get('beneficiary_last_name', ''));
  672.             $beneficiaryName = trim($beneficiaryFirstName . ' ' . $beneficiaryLastName);
  673.         }
  674.         if (empty($beneficiaryName)) {
  675.             $beneficiaryName = trim(
  676.                 (string)$request->get('room_0_pax_0_firstName', '') . ' ' .
  677.                 (string)$request->get('room_0_pax_0_lastName', '')
  678.             );
  679.         }
  680.         $beneficiaryEmail = $request->get('beneficiary_email');
  681.         $product_price = $request->get("totalAmount");
  682.         $productFee = $request->get('product_fee') ?? 0;
  683.         $dates = explode('-', $cart_line_date);
  684.         $date1 = DateTime::createFromFormat('d/m/Y', $dates[0]);
  685.         $date2 = DateTime::createFromFormat('d/m/Y', $dates[1]);
  686.         $interval = $date1->diff($date2);
  687.         $nbNights = $interval->days;
  688.         $hotel_with_party = false;
  689.         $product_elements = null;
  690.         for ($room_idx = 0; $room_idx < $nbRooms; $room_idx++) {
  691.             /* guests */
  692.             $room_guests = [];
  693.             $room_adults_count = $request->get("room_" . $room_idx . "_adults_count");
  694.             $room_children_count = $request->get("room_" . $room_idx . "_children_count");
  695.             $room_guest_count = $room_adults_count + $room_children_count;
  696.             for ($guest_index = 0; $guest_index < $room_guest_count; $guest_index++) {
  697.                 $paxCivility = $request->get("room_" . $room_idx . "_pax_" . $guest_index . "_civility");
  698.                 $paxFirstName = $request->get("room_" . $room_idx . "_pax_" . $guest_index . "_firstName");
  699.                 $paxLastName = $request->get("room_" . $room_idx . "_pax_" . $guest_index . "_lastName");
  700.                 $paxAge = $request->get("room_" . $room_idx . "_pax_" . $guest_index . "_age");
  701.                 if (!empty($paxFirstName) || !empty($paxLastName)) {
  702.                     // Use the detailed per-pax data
  703.                     $guest = [
  704.                         'civility' => $paxCivility ?? '',
  705.                         'firstName' => $paxFirstName ?? '',
  706.                         'lastName' => $paxLastName ?? '',
  707.                         'age' => $paxAge,
  708.                     ];
  709.                 } else {
  710.                     // Fallback: use the primary beneficiary name (backward compatibility)
  711.                     $guest = [
  712.                         'civility' => '',
  713.                         'firstName' => $beneficiaryName,
  714.                         'lastName' => '-',
  715.                     ];
  716.                 }
  717.                 $room_guests[] = $guest;
  718.             }
  719.             $room = [
  720.                 'rateKey' => $request->get("room_" . $room_idx . "_key"),
  721.                 'label' => $request->get("room_" . $room_idx . "_label"),
  722.                 'isAvailable' => $request->get("room_" . $room_idx . "_available"),
  723.                 'price' => $request->get("room_" . $room_idx . "_price"),
  724.                 'adultsCount' => $room_adults_count,
  725.                 'childrenCount' => $room_children_count,
  726.                 'guests' => $room_guests,
  727.                 'cancellations_fees' => $request->get("room_" . $room_idx . "_cancellations_fees"),
  728.                 'isNFR' => $request->get("room_" . $room_idx . "_nfr"),
  729.             ];
  730.             $room_nb_parties = $request->get("room_" . $room_idx . "_nbParties");
  731.             $room_parties_zones = [];
  732.             if (!is_null($room_nb_parties)) { // if there is parties associated to the current room
  733.                 $hotel_with_party = true;
  734.                 for ($party_index = 0; $party_index < $room_nb_parties; $party_index++) {
  735.                     $room_parties_zones[] = $request->get("room_" . $room_idx . "_party_" . $party_index);
  736.                 }
  737.                 $room['parties'] = $room_parties_zones;
  738.                 //$product_price+= $request->get("partyPrice_".$party_index);
  739.             }
  740.             $product_elements[] = $room;
  741.         }
  742.         if ($request->isMethod('POST')) {
  743.             $guestData = [
  744.                 'first_name' => $request->request->get('first_name'),
  745.                 'last_name' => $request->request->get('last_name'),
  746.                 'phone' => $request->request->get('phone'),
  747.                 'email' => $request->request->get('email'),
  748.             ];
  749.             $request->getSession()->set('guestData', $guestData);
  750.         }
  751.         $cart_line_hotel = [
  752.             'module' => ModuleEnum::hotel->getValue(),
  753.             'elements' => $product_elements,
  754.             'label' => $cart_line_label,
  755.             'date' => $cart_line_date,
  756.             'checkIn' => $dates[0],
  757.             'checkOut' => $dates[1],
  758.             'nbNights' => $nbNights,
  759.             'quantity' => $nbRooms,
  760.             'options' => $request->get("options"),
  761.             'comment' => $request->get("comment"),
  762.             'price' => $product_price,
  763.             'fee' => $productFee,
  764.             'available' => $request->get('available'),
  765.             'searchCode' => $request->get('searchCode'),
  766.             'tokenForBook' => $request->get('tokenForBook'),
  767.             'beneficiary' => [
  768.                 'name' => $beneficiaryName,
  769.                 'email' => $beneficiaryEmail
  770.             ],
  771.             'image' => $request->get('hotel_image'),
  772.             'address' => $request->get('hotel_address'),
  773.             'phone' => $request->get('hotel_phone'),
  774.             'city' => $request->get('city'),
  775.             'country' => $request->get('country'),
  776.             'rating' => $request->get('rating'),
  777.             'guestData' => $guestData,
  778.         ];
  779.         $cart_array['products'][] = $cart_line_hotel; // add a cart line ( a product )
  780.         $session->set("cart", $cart_array);
  781.         //return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
  782.         return $this->redirectToRoute('app_shared_cart_hotel_product_index', [], Response::HTTP_SEE_OTHER);
  783.     }
  784.     #[Route('/search_stream', name: 'hotel_search_stream', methods: ['POST'])]
  785.     public function hotelSearchStream(Request $request, HotelSearchStreamService $searchService): StreamedResponse|JsonResponse
  786.     {
  787.         $ctx = $searchService->buildContext($this->getUser(), $request);
  788.         $request->getSession()?->save(); // libère le verrou de session avant le stream
  789.         try {
  790.             return $searchService->createStreamedResponse(
  791.                 $ctx,
  792.                 $request->getContent(),
  793.                 (int)($request->headers->get('xmlSourceId') ?? 0),
  794.                 (int)($request->headers->get('isAllowedPagination') ?? 0) !== 0,
  795.                 $request->query->get('idSearch'),
  796.             );
  797.         } catch (\InvalidArgumentException $e) {
  798.             return $this->json($this->helpers->getArrayError($e->getMessage()), 400);
  799.         }
  800.     }
  801.     /**
  802.      * @throws Exception
  803.      */
  804.     #[Route('/getOfferDetails', name: 'hotel_offer_details', methods: ['POST'])]
  805.     public function getRateDetail(
  806.         Request $request,
  807.         HotelSearchStreamService $searchService,
  808.         HotelOfferDetailsService $offerService,bool $isMobile = false
  809.     ): JsonResponse {
  810.         $body = json_decode($request->getContent(), true);
  811.         if (!is_array($body)) {
  812.             return $this->json(['error' => 'Invalid JSON body'], 400);
  813.         }
  814.         $idSearch = $body['idSearch'] ?? null;
  815.         $hotelsKey = $body['hotelsKey'] ?? null;
  816.         if (!is_string($idSearch) || $idSearch === '' || !is_array($hotelsKey) || $hotelsKey === []) {
  817.             return $this->json(['error' => 'Missing parameters'], 400);
  818.         }
  819.         $hotelsKey = array_values(array_unique(array_filter($hotelsKey, 'is_string')));
  820.         if ($hotelsKey === []) {
  821.             return $this->json(['error' => 'Invalid hotelsKey'], 400);
  822.         }
  823.         $ctx = $searchService->buildContext($this->getUser(), $request);
  824.         $request->getSession()?->save();
  825.         $content = $offerService->getOfferDetails(
  826.             $ctx,
  827.             $idSearch,
  828.             $hotelsKey,
  829.             (int)$request->headers->get('sourceId', 0),
  830.             (int)($body['nbRooms'] ?? 1), $isMobile
  831.         );
  832.         return $content === null
  833.             ? $this->json(['error' => 'rate_expired'], 404)
  834.             : $this->json($content);
  835.     }
  836.     private function parseRateKeys(array $rawRateKeys, string $secretKey): array
  837.     {
  838.         $rooms_rate_keys = [];
  839.         $rooms = []; // raw per-room occupation strings, built once
  840.         $checkIn = null;
  841.         $checkOut = null;
  842.         $cityId = 0;
  843.         foreach ($rawRateKeys as $encryptedRateKey) {
  844.             $decryptedRateKey = $this->decryptRateKey($encryptedRateKey, $secretKey);
  845.             $tab = explode('~~@@', $decryptedRateKey);
  846.             if (!isset($tab[1])) {
  847.                 throw new \RuntimeException('Malformed rate key: missing segment.');
  848.             }
  849.             $newRateKey = strtr($tab[1], ['pp' => '+', 'plus' => '+']);
  850.             if (str_contains($newRateKey, '@')) {
  851.                 [$rateKey, $checkInStr, $checkOutStr, $roomStr, $rateCityId] =
  852.                     $this->parseXmlRateKey($newRateKey);
  853.                 $rooms_rate_keys[] = ['rateKey' => $rateKey];
  854.                 $rooms[] = $roomStr;
  855.             } else {
  856.                 [$rateKey, $checkInStr, $checkOutStr, $roomStr] =
  857.                     $this->parseLocalRateKey($newRateKey);
  858.                 $rooms_rate_keys[] = ['rateKey' => $rateKey];
  859.                 $rooms[] = $roomStr;
  860.                 $rateCityId = $cityId; // local rate keys don't carry a cityId today
  861.             }
  862.             // Original code silently overwrote these per rate key, keeping only the
  863.             // last one. We instead assert consistency — all rooms in one search
  864.             // should share the same stay dates / destination.
  865.             $checkIn ??= $checkInStr;
  866.             $checkOut ??= $checkOutStr;
  867.             $cityId = $cityId ?: $rateCityId;
  868.         }
  869.         return [
  870.             'rooms_rate_keys' => $rooms_rate_keys,
  871.             'jsonOccupation' => $this->buildJsonOccupation($rooms),
  872.             'checkIn' => $checkIn ?? '',
  873.             'checkOut' => $checkOut ?? '',
  874.             'cityId' => $cityId,
  875.         ];
  876.     }
  877.     private function parseXmlRateKey(string $newRateKey): array
  878.     {
  879.         $tab1 = explode('@', $newRateKey);
  880.         if (!isset($tab1[1])) {
  881.             throw new \RuntimeException('Malformed XML rate key.');
  882.         }
  883.         $rateKey = '@' . $tab1[1];
  884.         $tab2 = explode('+', $tab1[1]);
  885.         $tab3 = explode('|', $tab2[0]);
  886.         if (!isset($tab3[0], $tab3[1], $tab3[9], $tab3[10])) {
  887.             throw new \RuntimeException('Malformed XML rate key segments.');
  888.         }
  889.         $checkInDate = \DateTime::createFromFormat('Ymd', $tab3[0]);
  890.         $checkOutDate = \DateTime::createFromFormat('Ymd', $tab3[1]);
  891.         if (!$checkInDate || !$checkOutDate) {
  892.             throw new \RuntimeException('Invalid date in rate key.');
  893.         }
  894.         return [
  895.             $rateKey,
  896.             $checkInDate->format('Y-m-d'),
  897.             $checkOutDate->format('Y-m-d'),
  898.             $tab3[9],
  899.             $tab3[10],
  900.         ];
  901.     }
  902.     /**
  903.      * @return array{0:string,1:string,2:string,3:string} [rateKey, checkIn, checkOut, roomStr]
  904.      */
  905.     private function parseLocalRateKey(string $newRateKey): array
  906.     {
  907.         $tabLocal = explode('|', $newRateKey);
  908.         if (!isset($tabLocal[0], $tabLocal[1], $tabLocal[7])) {
  909.             throw new \RuntimeException('Malformed local rate key.');
  910.         }
  911.         $checkInDate = \DateTime::createFromFormat('Ymd', $tabLocal[0]);
  912.         $checkOutDate = \DateTime::createFromFormat('Ymd', $tabLocal[1]);
  913.         if (!$checkInDate || !$checkOutDate) {
  914.             throw new \RuntimeException('Invalid date in rate key.');
  915.         }
  916.         return [
  917.             $newRateKey,
  918.             $checkInDate->format('Y-m-d'),
  919.             $checkOutDate->format('Y-m-d'),
  920.             $tabLocal[7],
  921.         ];
  922.     }
  923.     /**
  924.      * Builds occupation data once for the full room list (this replaces the
  925.      * O(n^2) rebuild that happened inside the rate-key loop in the original).
  926.      */
  927.     private function buildJsonOccupation(array $rooms): array
  928.     {
  929.         $jsonOccupation = [];
  930.         foreach ($rooms as $key => $room) {
  931.             $adults = [];
  932.             $children = [];
  933.             if (str_contains($room, '~')) {
  934.                 // XML-style "adults~children~childAge"
  935.                 $tab = explode('~', $room);
  936.                 $adultCount = (int)($tab[0] ?? 0);
  937.                 $childCount = (int)($tab[1] ?? 0);
  938.                 $childAge = $tab[2] ?? null;
  939.                 // NOTE: original hardcoded adult age as 40 — kept as-is since the
  940.                 // downstream API apparently expects a placeholder age, but this
  941.                 // should ideally come from real guest ages rather than a magic number.
  942.                 $adults = array_fill(0, $adultCount, 40);
  943.                 $children = $childCount > 0 ? array_fill(0, $childCount, $childAge) : [];
  944.             } else {
  945.                 // Local-style "A:n+C:n"
  946.                 $tabRooms = explode('+', $room);
  947.                 if (count($tabRooms) >= 2) {
  948.                     $adults = explode(':', $tabRooms[0])[1] ?? [];
  949.                     $children = explode(':', $tabRooms[1])[1] ?? [];
  950.                 }
  951.             }
  952.             $jsonOccupation[] = [
  953.                 'id' => $key,
  954.                 'adults' => $adults,
  955.                 'children' => $children,
  956.             ];
  957.         }
  958.         return $jsonOccupation;
  959.     }
  960.     private function renderOfferError(): Response
  961.     {
  962.         return $this->render('front/hotel/offer_error.html.twig', [
  963.             'social_networks' => $this->frontService->getSocialNetworks(),
  964.             'menu_front' => $this->frontService->getFrontMenu(),
  965.             'society' => $this->parameterService->getSocietyParameters(),
  966.         ]);
  967.     }
  968.     /**
  969.      * Déchiffre une rate key chiffrée en AES-128-ECB puis urldecode le résultat.
  970.      */
  971.     private function decryptRateKey(string $encryptedRateKey, string $secretKey): ?string
  972.     {
  973.         $decrypted = openssl_decrypt($encryptedRateKey, 'AES-128-ECB', $secretKey);
  974.         if ($decrypted === false) {
  975.             return null;
  976.         }
  977.         return urldecode($decrypted);
  978.     }
  979.     private function generateSearchCode(
  980.         string $secret,
  981.         string $currency = 'TND'
  982.     ): string
  983.     {
  984.         $base64UrlEncode = function ($data) {
  985.             return rtrim(
  986.                 strtr(base64_encode($data), '+/', '-_'),
  987.                 '='
  988.             );
  989.         };
  990.         $now = time();
  991.         $searchResultsKey = bin2hex(random_bytes(16));
  992.         $uuid = bin2hex(random_bytes(16));
  993.         $header = [
  994.             'typ' => 'JWT',
  995.             'alg' => 'HS256'
  996.         ];
  997.         $payload = [
  998.             'searchResultsKey' => $searchResultsKey,
  999.             'showSupplier' => false,
  1000.             'viewCurrency' => $currency,
  1001.             'showNetPrice' => false,
  1002.             'showPriceComponents' => '',
  1003.             'iat' => $now,
  1004.             'nbf' => $now,
  1005.             'exp' => $now + 36000,
  1006.             'uuid' => $uuid,
  1007.             'v' => hash('sha256', $searchResultsKey),
  1008.         ];
  1009.         $encodedHeader = $base64UrlEncode(
  1010.             json_encode($header, JSON_UNESCAPED_SLASHES)
  1011.         );
  1012.         $encodedPayload = $base64UrlEncode(
  1013.             json_encode($payload, JSON_UNESCAPED_SLASHES)
  1014.         );
  1015.         $signature = hash_hmac(
  1016.             'sha256',
  1017.             $encodedHeader . '.' . $encodedPayload,
  1018.             $secret,
  1019.             true
  1020.         );
  1021.         $jwt = $encodedHeader . '.' .
  1022.             $encodedPayload . '.' .
  1023.             $base64UrlEncode($signature);
  1024.         // Partie aléatoire contenant @
  1025.         $randomPart = bin2hex(random_bytes(7))
  1026.             . '.'
  1027.             . random_int(10000000, 99999999)
  1028.             . '@1';
  1029.         return $randomPart . '#TFBEND#' . $jwt;
  1030.     }
  1031. }