<?php
/**
* Created by Elements.at New Media Solutions GmbH
*
*/
namespace App\Controller\Shop;
use App\Model\DataObject\Customer;
use App\Model\Shop\Event\EventProduct;
use App\Model\Shop\Event\ShopDynamicPrice;
use App\Model\Shop\Merchandise\MerchandiseProduct;
use App\Model\Shop\Ticket\ShopTicketCatalog;
use App\Service\Shop\ShopService;
use App\Service\TrackingService;
use Carbon\Carbon;
use Elements\Bundle\TicketShopFrameworkBundle\Model\DataObject\TicketConsumerCategory;
use Elements\Bundle\TicketShopFrameworkBundle\Model\DataObject\TicketProduct;
use Pimcore\Model\DataObject\CustomerContact;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Class CheckoutController
*
* @Route("/{_locale}/shop/cart")
*
* @package App\Controller\Shop
*/
class CartController extends AbstractShopController
{
/**
* @Route("/list", name="cart_list")
*
* @param Request $request
*
* @return Response
*/
public function listAction(Request $request): Response
{
$trackingManager = $this->factory->getTrackingManager();
/** @phpstan-ignore-next-line */
$trackingManager->trackcartView($this->getCart());
return $this->render('shop/cart/list.html.twig');
}
/**
* @Route("/add/ticket", name="cart_add_ticket")
*
* @param Request $request
* @param TranslatorInterface $translator
* @param ShopService $shopService
*
* @return Response
*
* @throws \Exception
*/
public function addTicketAction(Request $request, TranslatorInterface $translator, ShopService $shopService, TrackingService $trackingService): Response
{
// $success = false;
$cart = $this->getCart();
$addedItems = [];
$data = null;
if ($request->getContentType() == 'json') {
$data = json_decode($request->getContent(), true);
}
if (isset($data['configurations'])) {
foreach ($data['configurations'] as $config) {
$insurance = null;
$params = [];
$originalTicketProduct = TicketProduct::getById((int)$config['option']);
$ticketProduct = TicketProduct::getById((int)$config['upgradeOption']);
$ticketCatalog = ShopTicketCatalog::getById((int)$config['upgradeCatalog']);
$consumerCategory = TicketConsumerCategory::getById((int)$config['mappedPriceGroup']);
if (isset($config['dateStart'])) {
$ticketStartDate = Carbon::create($config['dateStart']);
} else {
$ticketStartDate = Carbon::today();
if ($ticketProduct->isSeasonTicket() && $ticketCatalog->getCurrentDateRangeStartDate()?->greaterThan($ticketStartDate)) {
$ticketStartDate = $ticketCatalog->getCurrentDateRangeStartDate();
}
}
if (array_key_exists('personId', $config)) {
if ($person = CustomerContact::getById((int)$config['personId'])) {
$params['person'] = $person;
} elseif ($customer = Customer::getById((int)$config['personId'])) {
$params['person'] = $customer;
}
}
$params['isUpgradeOption'] = $config['upgradeOption'] != $config['option'];
$params['originalProduct'] = $originalTicketProduct;
// $isInsuranceAllowed = true;
if ($insuranceId = $config['insurance']) {
$insurance = TicketProduct::getById((int)$insuranceId);
// $skidataProduct = $ticketProduct->getSkidataProduct();
// $isInsuranceAllowed = $shopService->isInsuranceAllowed($insurance, $skidataProduct, $consumerCategory->getSkidataConsumerForSkidataProduct($skidataProduct));
}
if ($consumerCategory) { //&& $isInsuranceAllowed
$addedItemsPerCategory = $shopService->addTicketItemsToCartPerConsumer(
$ticketProduct,
$consumerCategory,
1,
$insurance,
$ticketCatalog,
$cart,
$ticketStartDate,
$params
);
$addedItems = array_merge($addedItems, $addedItemsPerCategory);
// $success = true;
}
}
if ($addedItems) {
$trackingManager = $this->factory->getTrackingManager();
$arr = $trackingService->correctItemQuantity($cart, $addedItems);
$productCount = $arr['count'];
$products = $arr['products'];
foreach ($productCount as $key => $count) {
$trackingManager->trackCartProductActionAdd($cart, $products[$key], $count);
}
$trackingManager->forwardTrackedCodesAsFlashMessage();
}
}
$jsonResponse = [
'success' => true,
'message' => $translator->trans('cart.cart-add-successful'), // $translator->trans('cart.cart-add-error'),
'ticketCount' => count($addedItems),
'cartItemsCounter' => $cart->getItemAmount(),
];
return $this->json($jsonResponse);
}
/**
* @Route("/add/event", name="cart_add_event")
*
* @param Request $request
* @param TranslatorInterface $translator
* @param ShopService $shopService
*
* @return Response
*
* @throws \Exception
*/
public function addEventAction(Request $request, TranslatorInterface $translator, ShopService $shopService, TrackingService $trackingService): Response
{
$cart = $this->getCart();
$data = null;
if ($request->getContentType() == 'json') {
$data = json_decode($request->getContent(), true);
}
$product = EventProduct::getById($data['activityId']);
$allAddedItems = [];
if (isset($data['configurations'])) {
foreach ($data['configurations'] as $config) {
$quantity = $config['amount'];
$priceObj = ShopDynamicPrice::getById($config['priceGroup']);
$selectedDate = Carbon::parse($config['selectedDate']);
if (isset($config['selectedTime'])) {
$selectedDate->setTimeFromTimeString($config['selectedTime']);
}
if ($addedItem = $shopService->addEventToCartPerPriceObject($product, $priceObj, $cart, $selectedDate, $quantity)) {
$allAddedItems[] = $addedItem;
}
}
if ($allAddedItems) {
$trackingManager = $this->factory->getTrackingManager();
foreach ($allAddedItems as $value) {
$trackingManager->trackCartProductActionAdd($cart, $value->getProduct(), $value->getCount());
}
$trackingManager->forwardTrackedCodesAsFlashMessage();
}
}
return $this->json([
'success' => true,
'message' => $translator->trans('cart.cart-add-successful'),
'ticketCount' => count($allAddedItems),
'cartItemsCounter' => $cart->getItemAmount(),
]);
}
/**
* @Route("/add/merch", name="cart_add_merch")
*
* @param Request $request
* @param TranslatorInterface $translator
* @param ShopService $shopService
*
* @return Response
*
* @throws \Exception
*/
public function addMerchAction(Request $request, TranslatorInterface $translator, ShopService $shopService, TrackingService $trackingService): Response
{
if ($variantId = $request->get('variant')) {
$merch = MerchandiseProduct::getById(intval($variantId));
} else {
$merch = MerchandiseProduct::getById(intval($request->get('id')));
}
$trackingData = [];
if ($merch instanceof MerchandiseProduct) {
$product = $shopService->addMerchandiseToCart($merch, $request->get('amount') ?: 1, $this->getCart());
$trackingData = $trackingService->createGA4ProductInfoArray($product->getProduct(), 'add_to_cart', $request->get('amount') ?: 1);
}
$jsonResponse = [
'success' => true,
'message' => $translator->trans('cart.cart-add-successful'),
'ticketCount' => $request->get('amount') ?: 1,
'cartItemsCounter' => $this->getCart()->getItemAmount(),
];
if (!empty($trackingData)) {
$jsonResponse['responseTrackingData'] = [
'gtm' => [
'datalayer' => $trackingData,
],
];
}
return $this->json($jsonResponse);
}
/**
* @Route("/remove-product/{itemKey}", name="cart_remove_product_modal")
*
* @param Request $request
* @param string $itemKey
* @param string $cartName
*
* @return Response
*/
public function deleteProductModal(Request $request, string $itemKey, string $cartName = 'cart'): Response
{
$form = $this->createFormBuilder([])->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$cart = $this->getCart($cartName);
$trackingManager = $this->factory->getTrackingManager();
$cartItem = $cart->getItem($itemKey);
$trackingManager->trackCartProductActionRemove($cart, $cartItem->getProduct(), $cartItem->getCount());
$trackingManager->forwardTrackedCodesAsFlashMessage();
$cart->removeItem($itemKey);
if ($cart->isEmpty()) {
/** @phpstan-ignore-next-line */
$cart->setCheckoutData('cashback', null);
}
$cart->save();
//reset cashback
return $this->redirect($request->get('redirectUri'));
}
$html = $this->renderTemplate('shop/includes/cart/delete-product-modal.html.twig', [
'form' => $form->createView(),
'itemName' => $request->get('itemName'),
])->getContent();
return $this->json([
'success' => true,
'html' => $html,
]);
}
/**
* @Route("/remove-product-group", name="cart_remove_product_group_modal")
*
* @param Request $request
* @param string $cartName
*
* @return Response
*/
public function deleteProductGroupModal(Request $request, string $cartName = 'cart'): Response
{
$form = $this->createFormBuilder([])->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$cart = $this->getCart($cartName);
$cartItemKeys = explode(',', $request->get('itemKeys'));
foreach ($cartItemKeys as $cartItemKey) {
$cart->removeItem(htmlspecialchars($cartItemKey));
}
if ($cart->isEmpty()) {
/** @phpstan-ignore-next-line */
$cart->setCheckoutData('cashback', null);
}
$cart->save();
//reset cashback
return $this->redirect($request->get('redirectUri'));
}
$html = $this->renderTemplate('shop/includes/cart/delete-product-modal.html.twig', [
'form' => $form->createView(),
'itemName' => $request->get('itemName'),
'isGroupDelete' => $request->get('isGroupDelete'),
])->getContent();
return $this->json([
'success' => true,
'html' => $html,
]);
}
/**
* @Route("/clear", name="cart_clear")
*
* @return Response
*/
public function clearCart(): Response
{
$cart = $this->getCart();
$cart->clear();
$cart->save();
return $this->redirectToRoute('cart_list');
}
/**
* @Route("/cart-overlay", name="cart_overlay")
*
* @return Response
*/
public function cartOverlay(): Response
{
$cart = $this->getCart();
if ($cart->getItemAmount() == 0) {
$html = $this->renderTemplate('shop/includes/cart/cart-overlay-result-empty.html.twig')->getContent();
} else {
$html = $this->renderTemplate('shop/includes/cart/cart-overlay-result.html.twig')->getContent();
}
return $this->json([
'success' => true,
'html' => $html,
]);
}
}