<?php
namespace App\Controller;
use App\Entity\OrderItem;
use App\Entity\Product;
use App\Form\AddToCartType;
use App\Manager\CartManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ProductController extends AbstractController
{
/**
* @Route("/product/{slug}", name="product")
*/
public function index(Product $product, Request $request, CartManager $cartManager): Response
{
$order_item = new OrderItem();
$form = $this->createForm(AddToCartType::class, $order_item->setProducts($product));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var OrderItem $item */
$item = $form->getData();
$payment_option = $form->get('paymentOption')->getData();
$installments_arr = $product->getInstallments()->toArray();
$this->setInstallmentOption($item, $payment_option, $installments_arr);
$item->setQuantity(1)
->setProducts($product);
$cart = $cartManager->getCurrentCart();
$cart
->addOrderItem($item);
$cartManager->save($cart);
return $this->redirectToRoute('cart');
}
return $this->render('product/index.html.twig', [
'controller_name' => 'ProductController',
'product' => $product,
'form' => $form->createView(),
]);
}
public function setInstallmentOption(OrderItem $item, $payment_option, $installments_arr)
{
foreach ($installments_arr as $installment) {
if ($installment->getDuration() == $payment_option) {
$item->setPaymentOption($installment);
}
}
if (empty($item->getPaymentOption())) {
foreach ($installments_arr as $installment) {
if ($installment->getDuration() == '1 months') {
$item->setPaymentOption($installment);
}
}
}
}
}