<?php
namespace App\Service;
use App\Entity\App\Product;
use App\Repository\App\ProductRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class CartService
{
public function __construct(
private readonly RequestStack $requestStack,
private readonly ProductRepository $productRepository,
) {
}
public function getProductCart(): array
{
return $this->getSession()->get('products') ?? [];
}
public function addToCart(int $id, Request $request): void
{
$customization = $request->request->get('customization') ?? 'default';
$productsCart = $this->getProductCart();
if (!empty($productsCart[$id])) {
++$productsCart[$id]['quantity'];
} else {
$productsCart[$id] = [
'id' => $id,
'quantity' => 1,
'customization' => $customization,
];
}
$this->getSession()->set('products', $productsCart);
}
public function updateQuantityForProduct(int $productId, int $quantity): int
{
$productsCart = $this->getProductCart();
$price = 0;
$total = 0;
foreach ($productsCart as $productIdKey => &$productDetails) {
/** @var Product $product */
$product = $this->productRepository->findOneById($productDetails['id']);
if ($productDetails['id'] === $productId) {
$productDetails['quantity'] = $quantity;
}
$price = $product->getPrice() * $productDetails['quantity'];
$total += $price;
}
unset($productDetails);
$this->getSession()->set('products', $productsCart);
return $total;
}
public function removeAllProductsForId(int $id): void
{
$productsCart = $this->getProductCart();
if (!empty($productsCart[$id])) {
unset($productsCart[$id]);
}
$this->getSession()->set('products', $productsCart);
}
public function getProducts(): array
{
$productsCart = $this->getProductCart();
$products = [];
foreach ($productsCart as $productId => $quantity) {
$product = $this->productRepository->findOneById($productId);
$products[] = [
'product' => $product,
'quantity' => $quantity,
];
}
return $products;
}
public function removeCart(): void
{
$this->getSession()->clear();
}
/*private function generateCustomizationKey(int $id, string $customization): string
{
return $id.'-'.md5(json_encode($customization));
}*/
private function getSession(): SessionInterface
{
return $this->requestStack->getSession();
}
}