<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Entity\Category;
use App\Repository\ProductRepository;
class HeaderController extends AbstractController
{
#[Route('/header', name: 'app_header')]
public function index(): Response
{
// Obtener todas las categorÃas
$categories = $this->getDoctrine()
->getRepository(Category::class)
->findAll();
return $this->render('header/index.html.twig', [
'controller_name' => 'HeaderController',
'categories' => $categories
]);
}
/**
* @Route("/cartIconView", name="cartIconView")
*/
public function cartIconView(SessionInterface $session, ProductRepository $productRepository)
{
// Obtener el carrito de la sesión
$cart = $session->get('cart', []);
// Calcular el total
$total = 0;
$quantity = 0;
$refreshCart = [];
foreach ($cart as $item) {
$productId = $item['id'];
$product = $productRepository->find($productId);
if (!$product) {
throw $this->createNotFoundException("El producto con ID $productId no existe.");
continue;
}
if (($product->getStock() - $item['quantity']) < 0) {
$this->addFlash('error', 'Lo sentimos, no hay suficiente stock del producto: "'.$product->getName().'"');
continue;
}
$quantity += $item['quantity'];
$total += $item['price'] * $item['quantity'];
$refreshCart[] = $item;
}
$session->set('cart', $refreshCart);
return $this->render('header/header-cart.html.twig', [
'total' => number_format($total, 2, ',', '.'),
'quantity' => $quantity
]);
}
}