src/Controller/Front/CartController.php line 76

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