<?php
namespace App\Controller\Front;
use App\Config\ModuleEnum;
use App\Entity\Customer;
use App\Entity\CustomerMoral;
use App\Entity\Order;
use App\Entity\OrderPayment;
use App\Repository\AgencyRepository;
use App\Repository\CityRepository;
use App\Repository\CustomerPaymentRepository;
use App\Repository\CustomerRepository;
use App\Repository\HotelXmlPriceRepository;
use App\Repository\OrderLineRepository;
use App\Repository\OrderRepository;
use App\Repository\PartyRepository;
use App\Repository\PartyZoneRepository;
use App\Service\Api3TAuthenticationService;
use App\Service\CartService;
use App\Service\CurrencyService;
use App\Service\FlightService;
use App\Service\FrontService;
use App\Service\Helpers;
use App\Service\HotelApiService;
use App\Service\OrderService;
use App\Service\ParameterService;
use App\Service\PartyService;
use App\Service\ProductEmailService;
use App\Service\TransferService;
use App\Service\WalletService;
use DateTime;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
#[Route('/cart')]
class CartController extends AbstractController
{
public function __construct(
private readonly ParameterService $parameterService,
private readonly TranslatorInterface $translator,
private readonly FrontService $frontService,
private readonly ProductEmailService $productEmailService,
private readonly OrderService $orderService,
private readonly WalletService $walletService,
private readonly FlightService $flightService,
private readonly CurrencyService $currencyService,
){
}
#[Route('/', name: 'app_shared_cart_index')]
public function index(
SessionInterface $session,
Api3TAuthenticationService $apiAuthenticationService
): Response{
$cart_array = $session->get('cart');
if (isset($cart_array['products']) && count($cart_array['products']) == 1) {
$cart_line = $cart_array['products'][0];
$module = $cart_line['module'];
$redirect_path = '';
switch ($module) {
case ModuleEnum::hotel->getValue():
$redirect_path = "app_shared_cart_hotel_product_index";
break;
case ModuleEnum::flight->getValue():
$redirect_path = "app_shared_cart_flight_product_index";
break;
}
if ($redirect_path != '') {
return $this->redirectToRoute($redirect_path);
}
}
// dd($cart_array);
$user = $this->getUser();
$customer = $apiAuthenticationService->getCustomer($user);
return $this->render('front/cart/index.html.twig', [
'cart' => $cart_array,
'customer' => $customer,
'society' => $this->parameterService->getSocietyParameters(),
'social_networks' => $this->frontService->getSocialNetworks(),
'currencies' => $this->frontService->getCurrencies(),
'agencies' => $this->frontService->getAgencies(),
"referenceCurrency" => $this->parameterService->getReferenceCurrency(),
// 'terminal' => $terminalPaymentRepository->find(1)
]);
}
#[Route('/hotel', name: 'app_shared_cart_hotel_product_index')]
public function index_hotel_cart(
Request $request,
SessionInterface $session,
Api3TAuthenticationService $apiAuthenticationService,
ParameterService $parameterService,
FrontService $frontService,
): Response
{
$cart_array = $session->get('cart', ['products' => []]);
// dd($cart_array);
$user = $this->getUser();
$customer = $apiAuthenticationService->getCustomer($user);
$guestData = $session->get('guestData');
// dd(
// [
// 'cart' => $cart_array,
// 'customer' => $customer,
// 'society' => $parameterService->getSocietyParameters(),
// 'social_networks' => $frontService->getSocialNetworks(),
// 'currencies' => $frontService->getCurrencies(),
// 'agencies' => $frontService->getAgencies(),
// 'guestData' => $guestData,
// 'META_PIXEL_ID' => $this->parameterService->getTrackerMetaId()
// ]
// );
return $this->render('front/cart/hotel/book_summary.html.twig', [
'cart' => $cart_array,
'customer' => $customer,
'society' => $parameterService->getSocietyParameters(),
'social_networks' => $frontService->getSocialNetworks(),
'currencies' => $frontService->getCurrencies(),
'agencies' => $frontService->getAgencies(),
'guestData' => $guestData,
'META_PIXEL_ID' => $this->parameterService->getTrackerMetaId()
]);
}
#[Route('/flight', name: 'app_shared_cart_flight_product_index')]
public function index_flight_cart(
Request $request,
SessionInterface $session,
Api3TAuthenticationService $apiAuthenticationService,
ParameterService $parameterService,
FrontService $frontService,
): Response{
$cart_array = $session->get('cart', ['products' => []]);
$flightProducts = array_filter($cart_array['products'] ?? [], function ($product) {
return ($product['module'] ?? null) === ModuleEnum::flight->getValue();
});
$lastFlightProduct = !empty($flightProducts) ? end($flightProducts) : null;
$cart_array['products'] = $lastFlightProduct ? [$lastFlightProduct] : [];
if ($lastFlightProduct) {
$lastFlightProduct['available'] = filter_var($lastFlightProduct['available'] ?? false, FILTER_VALIDATE_BOOL);
// $lastFlightProduct['city'] = $lastFlightProduct['city'] ?? '';
// $lastFlightProduct['rating'] = $lastFlightProduct['rating'] ?? 0;
$cart_array['products'] = [$lastFlightProduct];
}
$session->set('cart', $cart_array);
$totalFlightPrice = $lastFlightProduct ? ($lastFlightProduct['price'] ?? 0) : 0;
$user = $this->getUser();
$customer = $apiAuthenticationService->getCustomer($user);
$guestData = $session->get('guestData');
return $this->render('front/cart/flight/book_summary.html.twig', [
'cart' => $cart_array,
'flightProducts' => $cart_array['products'],
'totalFlightPrice' => $totalFlightPrice,
'customer' => $customer,
'society' => $parameterService->getSocietyParameters(),
'social_networks' => $frontService->getSocialNetworks(),
'currencies' => $frontService->getCurrencies(),
'agencies' => $frontService->getAgencies(),
'lastFlightProduct' => $lastFlightProduct,
"product_fee" => $this->frontService->getProductFee(ModuleEnum::flight->getValue(), $customer),
'guestData' => $guestData,
]);
}
#[Route('/addProductParty', name: 'app_admin_add_cart_line_party', methods: ['POST'])]
public function addProductParty(
Request $request,
SessionInterface $session,
PartyRepository $partyRepository,
CartService $cartService,
PartyZoneRepository $partyZoneRepository
): Response{
$cart_array = $cartService->initCart($this->getUser(), $request);
$party = $partyRepository->find((int) $request->get('party'));
$partyZones = $request->get('partyZones');
$beneficiaryName = $request->get('beneficiary_name');
$beneficiaryEmail = $request->get('beneficiary_email');
$product_party_zones = [];
$product_price = 0;
foreach ($partyZones as $partyZoneData) {
if ($partyZoneData['nbAdult'] > 0 || $partyZoneData['nbChild'] > 0) {
$partyZone = $partyZoneRepository->find((int) $partyZoneData['id']);
$product_party_zone = [
'id' => $partyZoneData['id'],
'label' => $partyZone->getZone()->getTitle(),
'adultsCount' => $partyZoneData['nbAdult'],
'childrenCount' => $partyZoneData['nbChild'],
'unitPriceAdult' => $partyZone->getAdultSalePrice(),
'unitPriceChild' => $partyZone->getChildSalePrice()
];
$partyZoneTotalPrice =
$partyZoneData['nbAdult'] * $partyZone->getAdultSalePrice() +
$partyZoneData['nbChild'] * $partyZone->getChildSalePrice();
$product_party_zones[] = $product_party_zone;
$product_price += $partyZoneTotalPrice;
}
}
$cart_line_label = $party->getTitle() . ' (' . $party->getDate()->format('d M Y') . ')';
$cart_line_party = [
'module' => ModuleEnum::party->getValue(),
'elements' => $product_party_zones,
'label' => $cart_line_label,
'partyId' => $party->getId(),
'image' => $party->getPrimaryImageUrl(),
'price' => $product_price,
'beneficiary' => [
'name' => $beneficiaryName,
'email' => $beneficiaryEmail
],
];
$cart_array['products'][] = $cart_line_party;
$session->set("cart", $cart_array);
return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
}
#[Route('/addProductTransferTODELETE', name: 'app_admin_add_cart_line_transfer_to_delete', methods: ['POST'])]
public function addProductTransfer(
Request $request,
SessionInterface $session,
CartService $cartService,
): RedirectResponse{
$cart_array = $cartService->initCart($this->getUser(), $request);
/* 2- add a line into cart_array['products'] */
$cart_line_label = $request->get('product_label');
$beneficiaryName = $request->get('beneficiary_name');
$beneficiaryEmail = $request->get('beneficiary_email');
$elements = [];
$element_base = [
'label' => 'transfer', // todo custom label
'price' => $request->get('transfer_amount_base'),
'rateKey' => $request->get('transfer_rateKey'),
'type' => "transfer",
];
$elements[] = $element_base;
$extras = $request->get("extras");
foreach ($extras as $extra_code) {
$extra_label = $request->get("transfer_extra_" . $extra_code . "_name");
$extra_price = $request->get("transfer_extra_" . $extra_code . "_price");
$element['code'] = $extra_code;
$element['label'] = $extra_label;
$element['price'] = $extra_price;
$element['type'] = "service";
$elements[] = $element;
}
$equipments = $request->get("equipments");
foreach ($equipments as $equipment_code) {
$equipment_label = $request->get("transfer_equipment_" . $equipment_code . "_name");
$equipment_price = $request->get("transfer_equipment_" . $equipment_code . "_price");
$element['code'] = $equipment_code;
$element['label'] = $equipment_label;
$element['price'] = $equipment_price;
$element['type'] = "equipment";
$elements[] = $element;
}
$product_price = $request->get("totalAmount");
//$cart_line_label = $hotel_with_party ? $cart_line_label . ' + party' : $cart_line_label;
$cart_line_transfer = [
'module' => 'Transfer',
'elements' => $elements,
'label' => $cart_line_label,
'quantity' => 1,
'comment' => $request->get("comment"),
'price' => $product_price,
'searchCode' => $request->get('searchCode'),
'beneficiary' => [
'name' => $beneficiaryName,
'email' => $beneficiaryEmail
],
'image' => $request->get('image'),
'source' => $request->get('source')
];
$cart_array['products'][] = $cart_line_transfer; // add a cart line ( a product )
$session->set("cart", $cart_array);
return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
}
#[Route('/addProductFlight', name: 'app_admin_add_cart_line_flight', methods: ['POST'])]
public function addProductFlight(
Request $request,
SessionInterface $session,
CartService $cartService,
Api3TAuthenticationService $apiAuthenticationService,
CurrencyService $currencyService,
CustomerRepository $customerRepository
): RedirectResponse{
// dd('here app_admin_add_cart_line_flight ');
$data = $request->request->all();
$locale = $request->getLocale();
$format = $locale === 'fr' ? 'd/m/Y' : 'm/d/Y';
$passengersCount = $request->get('passengersCount') ?? 1;
$cart_line_date = $request->get('product_date');
$cart_array = $cartService->initCart($this->getUser(), $request);
// 2- add a line into cart_array['products']
$cart_line_label = $request->get('product_label');// description du produit
$elements = [];
for ($i = 1; $i <= $passengersCount; $i++) {
$passengerFirstName = $request->get('traveler_' . $i . '_first_name');
$passengerLastName = $request->get('traveler_' . $i . '_last_name');
$documentType = $request->get('traveler_' . $i . '_document_type') ?? 'PASSPORT';
$documentNumber = $request->get('traveler_' . $i . '_document_passport_number');
$nationality = $request->get('traveler_' . $i . '_document_nationality');
$travelerPhone = $request->get('traveler_' . $i . '_phone')
?? $request->get('traveler_' . $i . '_phone_number')
?? $request->get('phone');
$travelerCountryCallingCode = $request->get('traveler_' . $i . '_prefix')
?? $request->get('traveler_' . $i . '_country_calling_code')
?? $request->get('prefix_phone');
// Handle dates safely
// Expiry Date
$expiryDateStr = $request->get('traveler_' . $i . '_document_expiry_date');
$expiryDate = \DateTime::createFromFormat($format, $expiryDateStr);
if ($expiryDate) {
$expiryDate = $expiryDate->format('Y-m-d');
}
// Birth Date
$birthDateStr = $request->get('traveler_' . $i . '_date_of_birth');
$birthDate = \DateTime::createFromFormat($format, $birthDateStr);
if ($birthDate) {
$birthDate = $birthDate->format('Y-m-d');
}
// Issuance Date
$issuanceDateStr = $request->get('traveler_' . $i . '_document_issuance_date');
$issuanceDate = \DateTime::createFromFormat($format, $issuanceDateStr);
if ($issuanceDate) {
$issuanceDate = $issuanceDate->format('Y-m-d');
}
$element_base = [
'label' => sprintf('%s %s (%s : %s)', $passengerFirstName, $passengerLastName, $documentType, $documentNumber),
'type' => 'flight-passenger',
'firstName' => $passengerFirstName,
'lastName' => $passengerLastName,
'dateOfBirth' => $birthDate,
'gender' => $request->get('traveler_' . $i . '_gender'),
'email' => $request->get('traveler_' . $i . '_email') ?? $request->get('email'),
'associatedAdultId' => $request->get('traveler_' . $i . '_associated') ?? '',
'countryCallingCode' => $travelerCountryCallingCode,
'phoneNumber' => $travelerPhone,
'documentType' => $documentType,
'documentBirthPlace' => $request->get('traveler_' . $i . '_document_birth_place'),
'documentIssuanceLocation' => $request->get('traveler_' . $i . '_document_issuance_location') ?? $nationality,
'documentIssuanceDate' => $issuanceDate,
'documentNumber' => $documentNumber,
'documentExpiryDate' => $expiryDate,
'documentIssuanceCountry' => $request->get('traveler_' . $i . '_document_issuance_country') ?? $nationality,
'documentNationality' => $nationality,
'price' => $request->get('traveller_' . $i . '_price'),
];
$elements[] = $element_base;
}
// $product_price = $request->get("totalAmount");
// call api/flight/checkrate
$auth_data = $apiAuthenticationService->getAuthenticationArray($this->getUser());
$customer = $apiAuthenticationService->getCustomer($this->getUser());
$sourceId = $request->get('source') ?? 1;
$selectedFares = json_decode($request->get('selectedFare'), true);
$selectedServices = json_decode($request->get('selectedServices'), true);
$selectedOffer = $request->get('selectedOffer') ? json_decode($request->get('selectedOffer'), true) : [];
$dictionaries = $request->get('dictionaries') ? json_decode($request->get('dictionaries'), true) : [];
if ($selectedOffer) {
$productDetails = [
'data' => [$selectedOffer],
'dictionaries' => $dictionaries
];
// update cart line price
$host = $request->getSchemeAndHttpHost();
$destCurrency = $this->currencyService->getSaleCurrency($this->getUser());
$flight_product_fee = $this->frontService->getProductFee(ModuleEnum::flight->getValue(), $customer);
$line_product_amount = $checkRateData['price']['amount'] ?? 0;
$line_product_amount += $flight_product_fee;
$connectedUser = $this->getUser();
if ($connectedUser && $connectedUser->getCustomer()) {
// $customer = $customerRepository->find($customerId);
$customer = $connectedUser->getCustomer();
$principalFirstName = $customer->getName();
$principalLastName = $customer->getName();
$principalEmail = $customer->getEmail();
$principalPhone = $customer->getPhone();
$prefixPhone = "+216";
} else {
// super admin account connected => first beneficiaire
$principalFirstName = $request->get('first_name') ?? $elements[0]['firstName'];
$principalLastName = $request->get('last_name') ?? $elements[0]['lastName'];
$principalEmail = $request->get('email') ?? $elements[0]['email'];
$principalPhone = $request->get('phone') ?? $elements[0]['phoneNumber'];
$prefixPhone = $request->get('prefix_phone') ?? null;
}
$cart_line = [
'module' => ModuleEnum::flight->getValue(),
"referenceCurrency" => $this->parameterService->getReferenceCurrency(),
'fee' => $flight_product_fee,
'productDetails' => $productDetails,
'rateKey' => $request->get('rateKey'),
'selectedFares' => $selectedFares,
'selectedServices' => $selectedServices,
'sourceId' => $sourceId,
'elements' => $elements,//passengers details
'label' => $cart_line_label,
'date' => $cart_line_date,
'quantity' => $passengersCount, // nb passengers (ie. orderSublines count)
'comment' => $request->get("comment"),
'price' => $line_product_amount,
'searchCode' => $request->get('searchCode'),
'image' => $host . "/front/assets/images/flight.png",
'source' => $request->get('source'),
'beneficiary' => [ // NA for Flight
'name' => $principalFirstName . " " . $principalLastName,
'email' => $principalEmail,
'firstName' => $principalFirstName,
'lastName' => $principalLastName,
'phone' => $principalPhone,
'prefix_phone' => $prefixPhone
],
'available' => true,
];
$cartService->clearCart(); // initialiser la session pour ne pas ajouter plus que deux offres
$cart_array['products'][] = $cart_line; // add a cart line ( a product )
$session->set("cart", $cart_array);
}
return $this->redirectToRoute('app_shared_cart_flight_product_index', [], Response::HTTP_SEE_OTHER);
}
/**
* This method will call the payment service (if not payment at agency) then the book-api for each product in the cart
* @throws \Exception
*/
#[Route('/pay', name: 'app_shared_cart_pay', methods: ['POST'])]
public function payCart(
Request $request,
SessionInterface $session,
CartService $cartService,
AgencyRepository $agencyRepository,
OrderRepository $orderRepository,
HotelApiService $hotelApiService,
TransferService $transferService,
CurrencyService $currencyService,
PartyService $partyService,
Helpers $helpers,
Api3TAuthenticationService $apiAuthenticationService,
): Response{
$cart_array = $session->get('cart');
if ($cart_array == null || count($cart_array['products']) == 0) {
return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
}
// Get agency, currency, user and customer
$agency = $agencyRepository->find($session->get('agency') ?? 1);
if (!$agency->isActive()) {
$this->addFlash('error', "AGENCY IS DISABLED - PLEASE CONTACT YOUR ADMINISTRATOR");
return $this->redirectToRoute('front_info_message');
}
$user = $this->getUser();
if (is_null($user)) {
$user = $apiAuthenticationService->getDefaultUser();
}
$customer = $apiAuthenticationService->getCustomer($user);
$customerName = array_key_exists('customerName', $cart_array)
? $cart_array['customerName']
: $customer->getName();
$customerPhone = array_key_exists('customerPhone', $cart_array)
? $cart_array['customerPhone']
: $customer->getPhone();
$customerEmail = array_key_exists('customerEmail', $cart_array)
? $cart_array['customerEmail']
: $customer->getEmail();
// Prepare Order top-level info.
$order = new Order();
$order->setUser($user);
$order->setCustomer($customer);
$order->setAgency($agency);
$order->setCurrency($customer->getCurrency());
$order->setExchangeRateSaleToReference($currencyService->calculateExchangeRate($customer->getCurrency(), $agency->getCurrency()));
$order->setExchangeRateSaleToCustomer(1);
$order->setCustomerName($customerName);
$order->setCustomerPhone($customerPhone);
$order->setCustomerEmail($customerEmail);
$order->setReference($helpers->generateShortId()); // unique ID
foreach ($cart_array['products'] as $cart_line) {
$module = $cart_line['module'];
switch ($module) {
case ModuleEnum::hotel->getValue():
$first_ratekey = "";
if (count($cart_line['elements'])) {
$first_ratekey = $cart_line['elements'][0]['rateKey'];
}
$xmlSourceId = 0;
if (str_contains($first_ratekey, '@')) {
$xmlSourceId = strstr($first_ratekey, '@', true); // left subString before @
}
$is_hub_book = $xmlSourceId != 0;
if ($is_hub_book) { // Book from Xml
$hotelApiService->getHubOrderLine_cartLine($cart_line, $order);
} else {
$book_parameters = $hotelApiService->getBookParametersFromCartLine($cart_line);
$ol = $hotelApiService->bookFromLocal($book_parameters, $order, apply_fee: true);
}
break;
case ModuleEnum::party->getValue():
$book_parameters = $partyService->getBookParametersFromCartLine($cart_line);
$partyService->bookFromLocal($book_parameters, $order);
break;
case ModuleEnum::transfer->getValue():
$xmlSourceId = $cart_line['xmlSourceId'];
$book_parameters = [];
$is_hub_book = $xmlSourceId != 0;
if ($is_hub_book) {
$transferService->preBookFromHub($cart_line, $order);
} else {
$transferService->bookFromLocal($cart_line, $order);
}
break;
case ModuleEnum::flight->getValue():
$sourceId = $cart_line['sourceId'];
$preBookArray = [
'sourceId' => $cart_line['sourceId'],
'rateKey' => $cart_line['rateKey'],
'feeAmount' => $cart_line['fee'],
'beneficiary' => [
'firstName' => $cart_line['beneficiary']['firstName'],
'lastName' => $cart_line['beneficiary']['lastName'],
"name" => $cart_line['beneficiary']['firstName'] . " " . $cart_line['beneficiary']['lastName'],
'email' => $cart_line['beneficiary']['email'] ?? '',
'phone' => $cart_line['beneficiary']['phone'] ?? '',
'prefix_phone' => $cart_line['beneficiary']['prefix_phone'] ?? '',
],
'flightOffer' => $cart_line['productDetails']['data'][0],
'dictionaries' => $cart_line['productDetails']['dictionaries'] ?? [],
'providerMessage' => $cart_line['productDetails']['providerMessage'] ?? '',
// 'cart_line' => $cart_line,
'elements' => $cart_line['elements'],
'selectedServices' => $cart_line['selectedServices'],
];
$orderline = $this->flightService->preBook($preBookArray, $sourceId, $order, 1);
break;
default:
break;
}
}
// Check if Order is not empty
if (count($order->getOrderLines()) == 0) {
$this->addFlash('error', $this->translator->trans('Pages.Common.Alerts.EmptyOrder'));
return $this->redirectToRoute("app_shared_cart_index");
}
// Here Order is prepared, Now Process Payment Mode and Emails to Send
// CASE OF B2C (CustomerPhysical)
if ($customer->getClass() == "CustomerPhysical") {
$orderRepository->save($order, true);
// IF CREDIT CARD option is checked (Normally the Order is AVAILABLE) THEN redirect to Terminal payment directly
$terminal = $request->request->get("paymentMode");
if (preg_match('/CreditCard(\d+)/', $terminal, $match)) {
$terminalId = intval($match[1]);
return $this->redirectToRoute('app_front_order_online_payment_register', [
'reference' => $order->getReference(),
'terminal' => $terminalId,
], Response::HTTP_SEE_OTHER);
}
} elseif ($customer->getClass() == "CustomerMoral") { // CASE OF B2B (CustomerMoral)
$sufficientBalance = $this->walletService->isSufficientBalance($order);
$email_template = 'email/products/flight/booking-confirmation.html.twig';
if ($sufficientBalance) {
$orderRepository->save($order, true);
$this->orderService->bookTemporaryOrderlines($order);
$this->orderService->authorizeOrderVouchers($order);
$this->productEmailService->associateEmailsToOrder($order, true);
$orderRepository->save($order, true);
} else {
$errorMessage = $this->translator->trans('Pages.Cart.Alerts.InsufficientBalance', [], "messages_front");
$this->addFlash("error", $errorMessage);
return $this->redirectToRoute("app_shared_cart_index");
}
} elseif (is_null($order->getId())) {
$this->addFlash("error", "Error : Unable to create the order");
}
$cartService->clearCart();
//$this->addFlash('success', $this->translator->trans("Pages.Cart.Alerts.MessageSuccess", [], "messages_front"));
return $this->redirectToRoute("app_cart_redirect_order", ['id' => $order->getId()]);
}
#[Route('/delete/{idx}', name: 'app_shared_cart_delete')]
public function delete($idx, SessionInterface $session): Response
{
$cart = $session->get('cart');
// Use array_splice() to remove the element at the specified position
if (isset($cart['products'])) {
if (key_exists($idx, $cart['products'])) {
array_splice($cart['products'], $idx, 1);
}
}
$session->set("cart", $cart);
return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
}
#[Route('/clear', name: 'app_shared_cart_clear')]
public function clear(SessionInterface $session): Response
{
$cart = $session->get('cart', []);
// Empty the products array
$cart['products'] = [];
$session->set('cart', $cart);
return $this->redirectToRoute('app_shared_cart_index', [], Response::HTTP_SEE_OTHER);
}
#[Route('/{id}/redirect', name: 'app_cart_redirect_order')]
public function redirectOrder(Order $order): Response
{
if ($this->isGranted("ROLE_ADMIN")) {
return $this->redirectToRoute("app_admin_order_order_show", ['id' => $order->getId()]);
}
if ($this->isGranted("ROLE_B2C")) {
return $this->redirectToRoute("app_front_user_area_booking_b2c");
}
if ($this->isGranted("ROLE_B2B_AGENT")) {
return $this->redirectToRoute("app_front_booking_show", ['id' => $order->getId()]);
}
return $this->redirectToRoute(
"app_front_guest_order_show",
[
'reference' => $order->getReference(),
'token' => $order->getToken()
]
);
}
}