<?php
declare(strict_types=1);
namespace App\Controller\Shop;
use App\Entity\Channel\ChannelPricing;
use App\Entity\Configurator\ConfiguratorOption;
use App\Entity\Order\Order;
use App\Entity\Product\ProductVariant;
use App\Provider\PriceTTCProvider;
use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
use Sylius\Bundle\OrderBundle\Controller\OrderItemController;
use Sylius\Component\Order\CartActions;
use Sylius\Component\Order\Model\OrderItemInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class AddItemToCartController extends OrderItemController
{
public function addAction(Request $request): Response
{
/** @var Order $cart */
$cart = $this->getCurrentCart();
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, CartActions::ADD);
/** @var OrderItemInterface $orderItem */
$orderItem = $this->newResourceFactory->create($configuration, $this->factory);
$this->getQuantityModifier()->modify($orderItem, 1);
$form = $this->getFormFactory()->create(
$configuration->getFormType(),
$this->createAddToCartCommand($cart, $orderItem),
$configuration->getFormOptions()
);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$moneyFormatter = $this->container->get('sylius.money_formatter');
$em = $this->getDoctrine()->getManager();
$configuratorOptionRepository = $em->getRepository(ConfiguratorOption::class);
$criteria = [];
if ($request->request->get('demarches_administratives')) {
$criteria[] = $request->request->get('demarches_administratives');
}
if ($request->request->get('installation_kit_solaire')) {
$criteria[] = $request->request->get('installation_kit_solaire');
}
if ($request->request->get('panneaux_emplacement')) {
$criteria[] = $request->request->get('panneaux_emplacement');
}
//todo : créer une méthode de repo qui récupère toutes les options comprise dans le tableau des codes $criteria
// $configuratorOptions = $configuratorOptionRepository->findByCodes($criteria);
/** @var AddToCartCommandInterface $addToCartCommand */
$addToCartCommand = $form->getData();
/** @var ProductVariant $variant */
$variant = $addToCartCommand->getCartItem()->getVariant();
/** @var ChannelPricing $pricing */
$price = $variant->getChannelPricingForChannel($cart->getChannel())->getPrice();
$addToCartCommand->getCartItem()->setImmutable(true);
$addToCartCommand->getCartItem()->setUnitPrice($price);
$errors = $this->getCartItemErrors($addToCartCommand->getCartItem());
if (0 < count($errors)) {
$form = $this->getAddToCartFormWithErrors($errors, $form);
return $this->handleBadAjaxRequestView($configuration, $form);
}
$event = $this->eventDispatcher->dispatchPreEvent(CartActions::ADD, $configuration, $orderItem);
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
$this->flashHelper->addFlashFromEvent($configuration, $event);
return $this->redirectHandler->redirectToIndex($configuration, $orderItem);
}
$this->getOrderModifier()->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
$source_path = '//placehold.it/400x300';
if($variant->getImages()->first() != false) {
$source_path = $variant->getImages()->first()->getPath();
}
else {
if($variant->getProduct()->getImages()->first() != false) {
$source_path = $variant->getProduct()->getImages()->first()->getPath();
}
}
$cacheManager = $this->container->get('liip_imagine.cache.manager');
$path = $cacheManager->getBrowserPath(parse_url($source_path, PHP_URL_PATH), 'sylius_shop_product_large_thumbnail', [], null);
$htmlOptions = '';
foreach ($variant->getOptionValues() as $optionValue) {
$htmlOptions .= '<div>
<small><strong class="visible-devis">'.$optionValue->getName() .' : </strong>'. $optionValue->getValue() .'</small>
</div>';
}
$quantityAdd = $addToCartCommand->getCartItem()->getQuantity();
if ($variant->getName() !== null) {
$name = $variant->getName();
}
else {
$name = $variant->getProduct()->getName();
}
//add tva
/** @var PriceTTCProvider $priceTTCProvider */
$priceTTCProvider = $this->container->get('app.provider.price_ttc_provider');
$priceTTC = $priceTTCProvider->getPriceTTCFromVariant($variant, $price, false);
$priceConvert = $moneyFormatter->format((int)$priceTTC, $cart->getCurrencyCode(), $cart->getLocaleCode());
//partie datalayer
$gtmEventListener = $this->container->get('app.google_tag_manager.listener.event');
$datalayer = $gtmEventListener->addToCart($orderItem->getProduct());
$responseJson = [
'variantName' => $name,
'source_path' => $path,
'options' => $htmlOptions,
'quantity' => $quantityAdd,
'price' => $priceConvert,
'dataLayer' => $datalayer
];
$cartManager = $this->getCartManager();
$cartManager->persist($cart);
$cartManager->flush();
$resourceControllerEvent = $this->eventDispatcher->dispatchPostEvent(CartActions::ADD, $configuration, $orderItem);
if ($resourceControllerEvent->hasResponse()) {
return $resourceControllerEvent->getResponse();
}
return new Response(json_encode($responseJson));
}
if (!$configuration->isHtmlRequest()) {
return $this->handleBadAjaxRequestView($configuration, $form);
}
return $this->render(
$configuration->getTemplate(CartActions::ADD . '.html'),
[
'configuration' => $configuration,
$this->metadata->getName() => $orderItem,
'form' => $form->createView(),
]
);
}
}