<?php
namespace App\Controller;
use App\Entity\Cart;
use App\Entity\OrderItem;
use App\Form\AddToCartType;
use App\Manager\CartManager;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CartController extends AbstractController
{
/**
* @Route("/cart", name="cart")
*/
public function index(Request $request): Response
{
if ($request->isXmlHttpRequest()) {
return $this->render('cart/partials/_cart_section.html.twig');
}
return $this->render('cart/index.html.twig', [
'controller_name' => 'CartController',
'additional_services' => [],
]);
}
/**
* @Route("/cart/{id}/update", name="cart_update")
*/
public function updateCart(OrderItem $item, Request $request, ManagerRegistry $registry, ProductController $controller): Response
{
$form = $this->createForm(AddToCartType::class, $item, [
'action' => $this->generateUrl('cart_update', ['id' => $item->getId()]).'?partial=true',
]);
$form->handleRequest($request);
if ($request->get('partial') && $request->isXmlHttpRequest()) {
$payment_option = $form->get('paymentOption')->getData();
if ($form->isSubmitted() && $form->isValid()) {
$controller->setInstallmentOption($item , $payment_option,
$item->getProducts()->getInstallments()->toArray());
$registry->getManager()->flush();
return new Response('', \Symfony\Component\HttpFoundation\Response::HTTP_OK);
}
return $this->renderForm('order_item/_form.html.twig', [
'form' => $form,
]);
}
return new Response('', \Symfony\Component\HttpFoundation\Response::HTTP_UNAUTHORIZED);
}
/**
* @Route("/removeFromCart", name="removeFromCart")
*/
public function removeFromCart(Request $request, CartManager $cartManager): Response
{
$itemId = $request->request->get('itemId');
if (!empty($itemId)) {
$cart = $cartManager->getCurrentCart();
$items = $cart->getOrderItems();
foreach ($items as $c_item) {
if ($c_item->getProducts()->getId() == $itemId) {
$cart->removeOrderItem($c_item);
}
}
$cartManager->save($cart);
}
return $this->render('cart/partials/_cart_section.html.twig');
}
}