src/Controller/Front/CartController.php line 69

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use App\Config\ModuleEnum;
  4. use App\Entity\Customer;
  5. use App\Entity\CustomerMoral;
  6. use App\Entity\Order;
  7. use App\Entity\OrderPayment;
  8. use App\Repository\AgencyRepository;
  9. use App\Repository\CityRepository;
  10. use App\Repository\CustomerPaymentRepository;
  11. use App\Repository\CustomerRepository;
  12. use App\Repository\HotelXmlPriceRepository;
  13. use App\Repository\OrderLineRepository;
  14. use App\Repository\OrderRepository;
  15. use App\Repository\PartyRepository;
  16. use App\Repository\PartyZoneRepository;
  17. use App\Service\Api3TAuthenticationService;
  18. use App\Service\CartService;
  19. use App\Service\CurrencyService;
  20. use App\Service\FlightService;
  21. use App\Service\FrontService;
  22. use App\Service\Helpers;
  23. use App\Service\HotelApiService;
  24. use App\Service\OrderService;
  25. use App\Service\ParameterService;
  26. use App\Service\PartyService;
  27. use App\Service\ProductEmailService;
  28. use App\Service\TransferService;
  29. use App\Service\WalletService;
  30. use DateTime;
  31. use Psr\Log\LoggerInterface;
  32. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  33. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  34. use Symfony\Component\HttpClient\HttpClient;
  35. use Symfony\Component\HttpFoundation\RedirectResponse;
  36. use Symfony\Component\HttpFoundation\Request;
  37. use Symfony\Component\HttpFoundation\RequestStack;
  38. use Symfony\Component\HttpFoundation\Response;
  39. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  40. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  41. use Symfony\Component\Routing\Annotation\Route;
  42. use Symfony\Contracts\HttpClient\HttpClientInterface;
  43. use Symfony\Contracts\Translation\TranslatorInterface;
  44. #[Route('/cart')]
  45. class CartController extends AbstractController
  46. {
  47.     public function __construct(
  48.         private readonly ParameterService       $parameterService,
  49.         private readonly TranslatorInterface    $translator,
  50.         private readonly FrontService           $frontService,
  51.         private readonly ProductEmailService    $productEmailService,
  52.         private readonly OrderService           $orderService,
  53.         private readonly WalletService          $walletService,
  54.         private readonly FlightService          $flightService,
  55.         private readonly CurrencyService        $currencyService,
  56.     ){
  57.     }
  58.     #[Route('/'name'app_shared_cart_index')]
  59.     public function index(
  60.         SessionInterface $session,
  61.         Api3TAuthenticationService $apiAuthenticationService
  62.     ): Response{
  63.         $cart_array $session->get('cart');
  64.         if (isset($cart_array['products']) && count($cart_array['products']) == 1) {
  65.             $cart_line $cart_array['products'][0];
  66.             $module $cart_line['module'];
  67.             $redirect_path '';
  68.             switch ($module) {
  69.                 case ModuleEnum::hotel->getValue():
  70.                     $redirect_path "app_shared_cart_hotel_product_index";
  71.                     break;
  72.                 case ModuleEnum::flight->getValue():
  73.                     $redirect_path "app_shared_cart_flight_product_index";
  74.                     break;
  75.             }
  76.             if ($redirect_path != '') {
  77.                 return $this->redirectToRoute($redirect_path);
  78.             }
  79.         }
  80.         //        dd($cart_array);
  81.         $user $this->getUser();
  82.         $customer $apiAuthenticationService->getCustomer($user);
  83.         return $this->render('front/cart/index.html.twig', [
  84.             'cart' => $cart_array,
  85.             'customer' => $customer,
  86.             'society' => $this->parameterService->getSocietyParameters(),
  87.             'social_networks' => $this->frontService->getSocialNetworks(),
  88.             'currencies' => $this->frontService->getCurrencies(),
  89.             'agencies' => $this->frontService->getAgencies(),
  90.             "referenceCurrency" => $this->parameterService->getReferenceCurrency(),
  91.             //            'terminal' => $terminalPaymentRepository->find(1)
  92.         ]);
  93.     }
  94.     #[Route('/hotel'name'app_shared_cart_hotel_product_index')]
  95.     public function index_hotel_cart(
  96.         Request                    $request,
  97.         SessionInterface           $session,
  98.         Api3TAuthenticationService $apiAuthenticationService,
  99.         ParameterService           $parameterService,
  100.         FrontService               $frontService,
  101.     ): Response
  102.     {
  103.         $cart_array $session->get('cart', ['products' => []]);
  104. //        dd($cart_array);
  105.         $user $this->getUser();
  106.         $customer $apiAuthenticationService->getCustomer($user);
  107.         $guestData $session->get('guestData');
  108. //        dd(
  109. //            [
  110. //                'cart' => $cart_array,
  111. //                'customer' => $customer,
  112. //                'society' => $parameterService->getSocietyParameters(),
  113. //                'social_networks' => $frontService->getSocialNetworks(),
  114. //                'currencies' => $frontService->getCurrencies(),
  115. //                'agencies' => $frontService->getAgencies(),
  116. //                'guestData' => $guestData,
  117. //                'META_PIXEL_ID' => $this->parameterService->getTrackerMetaId()
  118. //            ]
  119. //        );
  120.         return $this->render('front/cart/hotel/book_summary.html.twig', [
  121.             'cart' => $cart_array,
  122.             'customer' => $customer,
  123.             'society' => $parameterService->getSocietyParameters(),
  124.             'social_networks' => $frontService->getSocialNetworks(),
  125.             'currencies' => $frontService->getCurrencies(),
  126.             'agencies' => $frontService->getAgencies(),
  127.             'guestData' => $guestData,
  128.             'META_PIXEL_ID' => $this->parameterService->getTrackerMetaId()
  129.         ]);
  130.     }
  131.     #[Route('/flight'name'app_shared_cart_flight_product_index')]
  132.     public function index_flight_cart(
  133.         Request                     $request,
  134.         SessionInterface            $session,
  135.         Api3TAuthenticationService  $apiAuthenticationService,
  136.         ParameterService            $parameterService,
  137.         FrontService                $frontService,
  138.     ): Response{
  139.         $cart_array $session->get('cart', ['products' => []]);
  140.         $flightProducts array_filter($cart_array['products'] ?? [], function ($product) {
  141.             return ($product['module'] ?? null) === ModuleEnum::flight->getValue();
  142.         });
  143.         $lastFlightProduct = !empty($flightProducts) ? end($flightProducts) : null;
  144.         $cart_array['products'] = $lastFlightProduct ? [$lastFlightProduct] : [];
  145.         if ($lastFlightProduct) {
  146.             $lastFlightProduct['available'] = filter_var($lastFlightProduct['available'] ?? falseFILTER_VALIDATE_BOOL);
  147.             //    $lastFlightProduct['city'] = $lastFlightProduct['city'] ?? '';
  148.             //   $lastFlightProduct['rating'] = $lastFlightProduct['rating'] ?? 0;
  149.             $cart_array['products'] = [$lastFlightProduct];
  150.         }
  151.         $session->set('cart'$cart_array);
  152.         $totalFlightPrice $lastFlightProduct ? ($lastFlightProduct['price'] ?? 0) : 0;
  153.         $user $this->getUser();
  154.         $customer $apiAuthenticationService->getCustomer($user);
  155.         $guestData $session->get('guestData');
  156.         return $this->render('front/cart/flight/book_summary.html.twig', [
  157.             'cart' => $cart_array,
  158.             'flightProducts' => $cart_array['products'],
  159.             'totalFlightPrice' => $totalFlightPrice,
  160.             'customer' => $customer,
  161.             'society' => $parameterService->getSocietyParameters(),
  162.             'social_networks' => $frontService->getSocialNetworks(),
  163.             'currencies' => $frontService->getCurrencies(),
  164.             'agencies' => $frontService->getAgencies(),
  165.             'lastFlightProduct' => $lastFlightProduct,
  166.             "product_fee" => $this->frontService->getProductFee(ModuleEnum::flight->getValue(), $customer),
  167.             'guestData' => $guestData,
  168.         ]);
  169.     }
  170.     #[Route('/addProductParty'name'app_admin_add_cart_line_party'methods: ['POST'])]
  171.     public function addProductParty(
  172.         Request             $request,
  173.         SessionInterface    $session,
  174.         PartyRepository     $partyRepository,
  175.         CartService         $cartService,
  176.         PartyZoneRepository $partyZoneRepository
  177.     ): Response{
  178.         $cart_array $cartService->initCart($this->getUser(), $request);
  179.         $party $partyRepository->find((int) $request->get('party'));
  180.         $partyZones $request->get('partyZones');
  181.         $beneficiaryName $request->get('beneficiary_name');
  182.         $beneficiaryEmail $request->get('beneficiary_email');
  183.         $product_party_zones = [];
  184.         $product_price 0;
  185.         foreach ($partyZones as $partyZoneData) {
  186.             if ($partyZoneData['nbAdult'] > || $partyZoneData['nbChild'] > 0) {
  187.                 $partyZone $partyZoneRepository->find((int) $partyZoneData['id']);
  188.                 $product_party_zone = [
  189.                     'id' => $partyZoneData['id'],
  190.                     'label' => $partyZone->getZone()->getTitle(),
  191.                     'adultsCount' => $partyZoneData['nbAdult'],
  192.                     'childrenCount' => $partyZoneData['nbChild'],
  193.                     'unitPriceAdult' => $partyZone->getAdultSalePrice(),
  194.                     'unitPriceChild' => $partyZone->getChildSalePrice()
  195.                 ];
  196.                 $partyZoneTotalPrice =
  197.                     $partyZoneData['nbAdult'] * $partyZone->getAdultSalePrice() +
  198.                     $partyZoneData['nbChild'] * $partyZone->getChildSalePrice();
  199.                 $product_party_zones[] = $product_party_zone;
  200.                 $product_price += $partyZoneTotalPrice;
  201.             }
  202.         }
  203.         $cart_line_label $party->getTitle() . ' (' $party->getDate()->format('d M Y') . ')';
  204.         $cart_line_party = [
  205.             'module' => ModuleEnum::party->getValue(),
  206.             'elements' => $product_party_zones,
  207.             'label' => $cart_line_label,
  208.             'partyId' => $party->getId(),
  209.             'image' => $party->getPrimaryImageUrl(),
  210.             'price' => $product_price,
  211.             'beneficiary' => [
  212.                 'name' => $beneficiaryName,
  213.                 'email' => $beneficiaryEmail
  214.             ],
  215.         ];
  216.         $cart_array['products'][] = $cart_line_party;
  217.         $session->set("cart"$cart_array);
  218.         return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
  219.     }
  220.     #[Route('/addProductTransferTODELETE'name'app_admin_add_cart_line_transfer_to_delete'methods: ['POST'])]
  221.     public function addProductTransfer(
  222.         Request             $request,
  223.         SessionInterface    $session,
  224.         CartService         $cartService,
  225.     ): RedirectResponse{
  226.         $cart_array $cartService->initCart($this->getUser(), $request);
  227.         /* 2- add a line into cart_array['products'] */
  228.         $cart_line_label $request->get('product_label');
  229.         $beneficiaryName $request->get('beneficiary_name');
  230.         $beneficiaryEmail $request->get('beneficiary_email');
  231.         $elements = [];
  232.         $element_base = [
  233.             'label' => 'transfer'// todo custom label
  234.             'price' => $request->get('transfer_amount_base'),
  235.             'rateKey' => $request->get('transfer_rateKey'),
  236.             'type' => "transfer",
  237.         ];
  238.         $elements[] = $element_base;
  239.         $extras $request->get("extras");
  240.         foreach ($extras as $extra_code) {
  241.             $extra_label $request->get("transfer_extra_" $extra_code "_name");
  242.             $extra_price $request->get("transfer_extra_" $extra_code "_price");
  243.             $element['code'] = $extra_code;
  244.             $element['label'] = $extra_label;
  245.             $element['price'] = $extra_price;
  246.             $element['type'] = "service";
  247.             $elements[] = $element;
  248.         }
  249.         $equipments $request->get("equipments");
  250.         foreach ($equipments as $equipment_code) {
  251.             $equipment_label $request->get("transfer_equipment_" $equipment_code "_name");
  252.             $equipment_price $request->get("transfer_equipment_" $equipment_code "_price");
  253.             $element['code'] = $equipment_code;
  254.             $element['label'] = $equipment_label;
  255.             $element['price'] = $equipment_price;
  256.             $element['type'] = "equipment";
  257.             $elements[] = $element;
  258.         }
  259.         $product_price $request->get("totalAmount");
  260.         //$cart_line_label = $hotel_with_party ? $cart_line_label . ' + party' : $cart_line_label;
  261.         $cart_line_transfer = [
  262.             'module' => 'Transfer',
  263.             'elements' => $elements,
  264.             'label' => $cart_line_label,
  265.             'quantity' => 1,
  266.             'comment' => $request->get("comment"),
  267.             'price' => $product_price,
  268.             'searchCode' => $request->get('searchCode'),
  269.             'beneficiary' => [
  270.                 'name' => $beneficiaryName,
  271.                 'email' => $beneficiaryEmail
  272.             ],
  273.             'image' => $request->get('image'),
  274.             'source' => $request->get('source')
  275.         ];
  276.         $cart_array['products'][] = $cart_line_transfer// add a cart line ( a product )
  277.         $session->set("cart"$cart_array);
  278.         return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
  279.     }
  280.     #[Route('/addProductFlight'name'app_admin_add_cart_line_flight'methods: ['POST'])]
  281.     public function addProductFlight(
  282.         Request                     $request,
  283.         SessionInterface            $session,
  284.         CartService                 $cartService,
  285.         Api3TAuthenticationService  $apiAuthenticationService,
  286.         CurrencyService             $currencyService,
  287.         CustomerRepository          $customerRepository
  288.     ): RedirectResponse{
  289.         // dd('here app_admin_add_cart_line_flight ');
  290.         $data $request->request->all();
  291.         $locale $request->getLocale();
  292.         $format $locale === 'fr' 'd/m/Y' 'm/d/Y';
  293.         $passengersCount $request->get('passengersCount') ?? 1;
  294.         $cart_line_date $request->get('product_date');
  295.         $cart_array $cartService->initCart($this->getUser(), $request);
  296.         // 2- add a line into cart_array['products']
  297.         $cart_line_label $request->get('product_label');// description du produit
  298.         $elements = [];
  299.         for ($i 1$i <= $passengersCount$i++) {
  300.             $passengerFirstName $request->get('traveler_' $i '_first_name');
  301.             $passengerLastName $request->get('traveler_' $i '_last_name');
  302.             $documentType $request->get('traveler_' $i '_document_type') ?? 'PASSPORT';
  303.             $documentNumber $request->get('traveler_' $i '_document_passport_number');
  304.             $nationality $request->get('traveler_' $i '_document_nationality');
  305.             $travelerPhone $request->get('traveler_' $i '_phone')
  306.                 ?? $request->get('traveler_' $i '_phone_number')
  307.                 ?? $request->get('phone');
  308.             $travelerCountryCallingCode $request->get('traveler_' $i '_prefix')
  309.                 ?? $request->get('traveler_' $i '_country_calling_code')
  310.                 ?? $request->get('prefix_phone');
  311.             // Handle dates safely
  312.             // Expiry Date
  313.             $expiryDateStr $request->get('traveler_' $i '_document_expiry_date');
  314.             $expiryDate \DateTime::createFromFormat($format$expiryDateStr);
  315.             if ($expiryDate) {
  316.                 $expiryDate $expiryDate->format('Y-m-d');
  317.             }
  318.             // Birth Date
  319.             $birthDateStr $request->get('traveler_' $i '_date_of_birth');
  320.             $birthDate \DateTime::createFromFormat($format$birthDateStr);
  321.             if ($birthDate) {
  322.                 $birthDate $birthDate->format('Y-m-d');
  323.             }
  324.             // Issuance Date
  325.             $issuanceDateStr $request->get('traveler_' $i '_document_issuance_date');
  326.             $issuanceDate \DateTime::createFromFormat($format$issuanceDateStr);
  327.             if ($issuanceDate) {
  328.                 $issuanceDate $issuanceDate->format('Y-m-d');
  329.             }
  330.             $element_base = [
  331.                 'label' => sprintf('%s %s (%s : %s)'$passengerFirstName$passengerLastName$documentType$documentNumber),
  332.                 'type' => 'flight-passenger',
  333.                 'firstName' => $passengerFirstName,
  334.                 'lastName' => $passengerLastName,
  335.                 'dateOfBirth' => $birthDate,
  336.                 'gender' => $request->get('traveler_' $i '_gender'),
  337.                 'email' => $request->get('traveler_' $i '_email') ?? $request->get('email'),
  338.                 'associatedAdultId' => $request->get('traveler_' $i '_associated') ?? '',
  339.                 'countryCallingCode' => $travelerCountryCallingCode,
  340.                 'phoneNumber' => $travelerPhone,
  341.                 'documentType' => $documentType,
  342.                 'documentBirthPlace' => $request->get('traveler_' $i '_document_birth_place'),
  343.                 'documentIssuanceLocation' => $request->get('traveler_' $i '_document_issuance_location') ?? $nationality,
  344.                 'documentIssuanceDate' => $issuanceDate,
  345.                 'documentNumber' => $documentNumber,
  346.                 'documentExpiryDate' => $expiryDate,
  347.                 'documentIssuanceCountry' => $request->get('traveler_' $i '_document_issuance_country') ?? $nationality,
  348.                 'documentNationality' => $nationality,
  349.                 'price' => $request->get('traveller_' $i '_price'),
  350.             ];
  351.             $elements[] = $element_base;
  352.         }
  353.         // $product_price = $request->get("totalAmount");
  354.         // call api/flight/checkrate
  355.         $auth_data $apiAuthenticationService->getAuthenticationArray($this->getUser());
  356.         $customer $apiAuthenticationService->getCustomer($this->getUser());
  357.         $sourceId $request->get('source') ?? 1;
  358.         $selectedFares json_decode($request->get('selectedFare'), true);
  359.         $selectedServices json_decode($request->get('selectedServices'), true);
  360.         $selectedOffer $request->get('selectedOffer') ? json_decode($request->get('selectedOffer'), true) : [];
  361.         $dictionaries $request->get('dictionaries') ? json_decode($request->get('dictionaries'), true) : [];
  362.         if ($selectedOffer) {
  363.             $productDetails = [
  364.                 'data' => [$selectedOffer],
  365.                 'dictionaries' => $dictionaries
  366.             ];
  367.             // update cart line price
  368.             $host $request->getSchemeAndHttpHost();
  369.             $destCurrency $this->currencyService->getSaleCurrency($this->getUser());
  370.             $flight_product_fee $this->frontService->getProductFee(ModuleEnum::flight->getValue(), $customer);
  371.             $line_product_amount $checkRateData['price']['amount'] ?? 0;
  372.             $line_product_amount += $flight_product_fee;
  373.             $connectedUser $this->getUser();
  374.             if ($connectedUser && $connectedUser->getCustomer()) {
  375.                 //                $customer = $customerRepository->find($customerId);
  376.                 $customer $connectedUser->getCustomer();
  377.                 $principalFirstName $customer->getName();
  378.                 $principalLastName $customer->getName();
  379.                 $principalEmail $customer->getEmail();
  380.                 $principalPhone $customer->getPhone();
  381.                 $prefixPhone "+216";
  382.             } else {
  383.                 // super admin account connected => first beneficiaire
  384.                 $principalFirstName $request->get('first_name') ?? $elements[0]['firstName'];
  385.                 $principalLastName $request->get('last_name') ?? $elements[0]['lastName'];
  386.                 $principalEmail $request->get('email') ?? $elements[0]['email'];
  387.                 $principalPhone $request->get('phone') ?? $elements[0]['phoneNumber'];
  388.                 $prefixPhone $request->get('prefix_phone') ?? null;
  389.             }
  390.             $cart_line = [
  391.                 'module' => ModuleEnum::flight->getValue(),
  392.                 "referenceCurrency" => $this->parameterService->getReferenceCurrency(),
  393.                 'fee' => $flight_product_fee,
  394.                 'productDetails' => $productDetails,
  395.                 'rateKey' => $request->get('rateKey'),
  396.                 'selectedFares' => $selectedFares,
  397.                 'selectedServices' => $selectedServices,
  398.                 'sourceId' => $sourceId,
  399.                 'elements' => $elements,//passengers details
  400.                 'label' => $cart_line_label,
  401.                 'date' => $cart_line_date,
  402.                 'quantity' => $passengersCount// nb passengers (ie. orderSublines count)
  403.                 'comment' => $request->get("comment"),
  404.                 'price' => $line_product_amount,
  405.                 'searchCode' => $request->get('searchCode'),
  406.                 'image' => $host "/front/assets/images/flight.png",
  407.                 'source' => $request->get('source'),
  408.                 'beneficiary' => [ // NA for Flight
  409.                     'name' => $principalFirstName " " $principalLastName,
  410.                     'email' => $principalEmail,
  411.                     'firstName' => $principalFirstName,
  412.                     'lastName' => $principalLastName,
  413.                     'phone' => $principalPhone,
  414.                     'prefix_phone' => $prefixPhone
  415.                 ],
  416.                 'available' => true,
  417.             ];
  418.             $cartService->clearCart(); // initialiser la session pour ne pas ajouter plus que deux offres
  419.             $cart_array['products'][] = $cart_line// add a cart line ( a product )
  420.             $session->set("cart"$cart_array);
  421.         }
  422.         return $this->redirectToRoute('app_shared_cart_flight_product_index', [], Response::HTTP_SEE_OTHER);
  423.     }
  424.     /**
  425.      * This method will call the payment service (if not payment at agency) then the book-api for each product in the cart
  426.      * @throws \Exception
  427.      */
  428.     #[Route('/pay'name'app_shared_cart_pay'methods: ['POST'])]
  429.     public function payCart(
  430.         Request                     $request,
  431.         SessionInterface            $session,
  432.         CartService                 $cartService,
  433.         AgencyRepository            $agencyRepository,
  434.         OrderRepository             $orderRepository,
  435.         HotelApiService             $hotelApiService,
  436.         TransferService             $transferService,
  437.         CurrencyService             $currencyService,
  438.         PartyService                $partyService,
  439.         Helpers                     $helpers,
  440.         Api3TAuthenticationService  $apiAuthenticationService,
  441.     ): Response{
  442.         $cart_array $session->get('cart');
  443.         if ($cart_array == null || count($cart_array['products']) == 0) {
  444.             return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
  445.         }
  446.         // Get agency, currency, user and customer
  447.         $agency $agencyRepository->find($session->get('agency') ?? 1);
  448.         if (!$agency->isActive()) {
  449.             $this->addFlash('error'"AGENCY IS DISABLED -  PLEASE CONTACT YOUR ADMINISTRATOR");
  450.             return $this->redirectToRoute('front_info_message');
  451.         }
  452.         $user $this->getUser();
  453.         if (is_null($user)) {
  454.             $user $apiAuthenticationService->getDefaultUser();
  455.         }
  456.         $customer $apiAuthenticationService->getCustomer($user);
  457.         $customerName array_key_exists('customerName'$cart_array)
  458.             ? $cart_array['customerName']
  459.             : $customer->getName();
  460.         $customerPhone array_key_exists('customerPhone'$cart_array)
  461.             ? $cart_array['customerPhone']
  462.             : $customer->getPhone();
  463.         $customerEmail array_key_exists('customerEmail'$cart_array)
  464.             ? $cart_array['customerEmail']
  465.             : $customer->getEmail();
  466.         // Prepare Order top-level info.
  467.         $order = new Order();
  468.         $order->setUser($user);
  469.         $order->setCustomer($customer);
  470.         $order->setAgency($agency);
  471.         $order->setCurrency($customer->getCurrency());
  472.         $order->setExchangeRateSaleToReference($currencyService->calculateExchangeRate($customer->getCurrency(), $agency->getCurrency()));
  473.         $order->setExchangeRateSaleToCustomer(1);
  474.         $order->setCustomerName($customerName);
  475.         $order->setCustomerPhone($customerPhone);
  476.         $order->setCustomerEmail($customerEmail);
  477.         $order->setReference($helpers->generateShortId()); // unique ID
  478.         foreach ($cart_array['products'] as $cart_line) {
  479.             $module $cart_line['module'];
  480.             switch ($module) {
  481.                 case ModuleEnum::hotel->getValue():
  482.                     $first_ratekey "";
  483.                     if (count($cart_line['elements'])) {
  484.                         $first_ratekey $cart_line['elements'][0]['rateKey'];
  485.                     }
  486.                     $xmlSourceId 0;
  487.                     if (str_contains($first_ratekey'@')) {
  488.                         $xmlSourceId strstr($first_ratekey'@'true); // left subString before @
  489.                     }
  490.                     $is_hub_book $xmlSourceId != 0;
  491.                     if ($is_hub_book) { // Book from Xml
  492.                         $hotelApiService->getHubOrderLine_cartLine($cart_line$order);
  493.                     } else {
  494.                         $book_parameters $hotelApiService->getBookParametersFromCartLine($cart_line);
  495.                         $ol $hotelApiService->bookFromLocal($book_parameters$orderapply_feetrue);
  496.                     }
  497.                     break;
  498.                 case ModuleEnum::party->getValue():
  499.                     $book_parameters $partyService->getBookParametersFromCartLine($cart_line);
  500.                     $partyService->bookFromLocal($book_parameters$order);
  501.                     break;
  502.                 case ModuleEnum::transfer->getValue():
  503.                     $xmlSourceId $cart_line['xmlSourceId'];
  504.                     $book_parameters = [];
  505.                     $is_hub_book $xmlSourceId != 0;
  506.                     if ($is_hub_book) {
  507.                         $transferService->preBookFromHub($cart_line$order);
  508.                     } else {
  509.                         $transferService->bookFromLocal($cart_line$order);
  510.                     }
  511.                     break;
  512.                 case ModuleEnum::flight->getValue():
  513.                     $sourceId $cart_line['sourceId'];
  514.                     $preBookArray = [
  515.                         'sourceId' => $cart_line['sourceId'],
  516.                         'rateKey' => $cart_line['rateKey'],
  517.                         'feeAmount' => $cart_line['fee'],
  518.                         'beneficiary' => [
  519.                             'firstName' => $cart_line['beneficiary']['firstName'],
  520.                             'lastName' => $cart_line['beneficiary']['lastName'],
  521.                             "name" => $cart_line['beneficiary']['firstName'] . " " $cart_line['beneficiary']['lastName'],
  522.                             'email' => $cart_line['beneficiary']['email'] ?? '',
  523.                             'phone' => $cart_line['beneficiary']['phone'] ?? '',
  524.                             'prefix_phone' => $cart_line['beneficiary']['prefix_phone'] ?? '',
  525.                         ],
  526.                         'flightOffer' => $cart_line['productDetails']['data'][0],
  527.                         'dictionaries' => $cart_line['productDetails']['dictionaries'] ?? [],
  528.                         'providerMessage' => $cart_line['productDetails']['providerMessage'] ?? '',
  529.                         //                        'cart_line' => $cart_line,
  530.                         'elements' => $cart_line['elements'],
  531.                         'selectedServices' => $cart_line['selectedServices'],
  532.                     ];
  533.                     $orderline $this->flightService->preBook($preBookArray$sourceId$order1);
  534.                     break;
  535.                 default:
  536.                     break;
  537.             }
  538.         }
  539.         // Check if Order is not empty
  540.         if (count($order->getOrderLines()) == 0) {
  541.             $this->addFlash('error'$this->translator->trans('Pages.Common.Alerts.EmptyOrder'));
  542.             return $this->redirectToRoute("app_shared_cart_index");
  543.         }
  544.         // Here Order is prepared, Now Process Payment Mode and Emails to Send
  545.         // CASE OF B2C (CustomerPhysical)
  546.         if ($customer->getClass() == "CustomerPhysical") {
  547.             $orderRepository->save($ordertrue);
  548.             // IF CREDIT CARD option is checked (Normally the Order is AVAILABLE) THEN redirect to Terminal payment directly
  549.             $terminal $request->request->get("paymentMode");
  550.             if (preg_match('/CreditCard(\d+)/'$terminal$match)) {
  551.                 $terminalId intval($match[1]);
  552.                 return $this->redirectToRoute('app_front_order_online_payment_register', [
  553.                     'reference' => $order->getReference(),
  554.                     'terminal' => $terminalId,
  555.                 ], Response::HTTP_SEE_OTHER);
  556.             }
  557.         } elseif ($customer->getClass() == "CustomerMoral") { // CASE OF B2B (CustomerMoral)
  558.             $sufficientBalance $this->walletService->isSufficientBalance($order);
  559.             $email_template 'email/products/flight/booking-confirmation.html.twig';
  560.             if ($sufficientBalance) {
  561.                 $orderRepository->save($ordertrue);
  562.                 $this->orderService->bookTemporaryOrderlines($order);
  563.                 $this->orderService->authorizeOrderVouchers($order);
  564.                 $this->productEmailService->associateEmailsToOrder($ordertrue);
  565.                 $orderRepository->save($ordertrue);
  566.             } else {
  567.                 $errorMessage $this->translator->trans('Pages.Cart.Alerts.InsufficientBalance', [], "messages_front");
  568.                 $this->addFlash("error"$errorMessage);
  569.                 return $this->redirectToRoute("app_shared_cart_index");
  570.             }
  571.         } elseif (is_null($order->getId())) {
  572.             $this->addFlash("error""Error : Unable to create the order");
  573.         }
  574.         $cartService->clearCart();
  575.         //$this->addFlash('success', $this->translator->trans("Pages.Cart.Alerts.MessageSuccess", [], "messages_front"));
  576.         return $this->redirectToRoute("app_cart_redirect_order", ['id' => $order->getId()]);
  577.     }
  578.     #[Route('/delete/{idx}'name'app_shared_cart_delete')]
  579.     public function delete($idxSessionInterface $session): Response
  580.     {
  581.         $cart $session->get('cart');
  582.         // Use array_splice() to remove the element at the specified position
  583.         if (isset($cart['products'])) {
  584.             if (key_exists($idx$cart['products'])) {
  585.                 array_splice($cart['products'], $idx1);
  586.             }
  587.         }
  588.         $session->set("cart"$cart);
  589.         return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
  590.     }
  591.     #[Route('/clear'name'app_shared_cart_clear')]
  592.     public function clear(SessionInterface $session): Response
  593.     {
  594.         $cart $session->get('cart', []);
  595.         // Empty the products array
  596.         $cart['products'] = [];
  597.         $session->set('cart'$cart);
  598.         return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
  599.     }
  600.     #[Route('/{id}/redirect'name'app_cart_redirect_order')]
  601.     public function redirectOrder(Order $order): Response
  602.     {
  603.         if ($this->isGranted("ROLE_ADMIN")) {
  604.             return $this->redirectToRoute("app_admin_order_order_show", ['id' => $order->getId()]);
  605.         }
  606.         if ($this->isGranted("ROLE_B2C")) {
  607.             return $this->redirectToRoute("app_front_user_area_booking_b2c");
  608.         }
  609.         if ($this->isGranted("ROLE_B2B_AGENT")) {
  610.             return $this->redirectToRoute("app_front_booking_show", ['id' => $order->getId()]);
  611.         }
  612.         return $this->redirectToRoute(
  613.             "app_front_guest_order_show",
  614.             [
  615.                 'reference' => $order->getReference(),
  616.                 'token' => $order->getToken()
  617.             ]
  618.         );
  619.     }
  620. }