<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Service\HuskyClient;
use App\Entity\Fridge;
use App\Entity\Product;
use App\Form\FridgeType;
use App\Repository\FridgeRepository;
class FridgeController extends AbstractController
{
/**
* @Route("/fridge/browse/{page}", defaults={"page"=0}, name="browse_fridge")
*/
public function browseFridge(Request $request, $page): Response
{
if ($page == 0) {
$page = 1;
}
$user = $this->getUser();
$is_admin = ( array_search('ROLE_ADMIN', $user->getRoles()) !== False );
$session = $request->getSession();
$frepo = $this->getDoctrine()->getRepository(Fridge::class);
if ( $is_admin )
$fridges = $frepo->findAllByPage($page);
else
$fridges = $frepo->findBy(['owner' => $user]);
$count = count($fridges);
$sdate = (new \DateTimeImmutable())->modify('this monday');
return $this->render('browse_fridge.html.twig', [
'controller_name' => 'FridgeController',
'fridges' => $fridges,
'start_date' => $sdate,
'page_title' => 'Frigoríficos',
'pages' => ['page_id' => 'browse_fridge', 'last' => floor(($count-1)/$frepo->getLinesPerPage())+1, 'current' => $page]
]);
}
/**
* @Route("/fridge/edit/{fridge_id}", name="edit_fridge")
*/
public function editFridge(Request $request, $fridge_id)
{
$frepo = $this->getDoctrine()->getRepository(Fridge::class);
if ($fridge_id == 'new') {
$fridge = new Fridge();
} else {
$fridge = $frepo->find($fridge_id);
}
$form = $this->createForm(FridgeType::class, $fridge);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$fridge = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($fridge);
$entityManager->flush();
if ($fridge_id == 'new') {
$this->addFlash('success', 'El nuevo refrigerador se ha añadido con éxito');
} else {
$this->addFlash('success', 'Los cambios se han guardado');
}
return $this->redirectToRoute('browse_fridge');
} else {
return $this->render(
'edit_fridge.html.twig',
array(
'form' => $form->createView(),
'page_title' => ($fridge_id == 'new' ? 'Nuevo refrigerador' : 'Editar refrigerador'),
'fridge_id' => $fridge_id,
)
);
}
}
/**
* @Route("/fridge/products/{fridge_id}", name="view_fridge_products")
*/
public function viewFridgeProducts(Request $request, $fridge_id)
{
$frepo = $this->getDoctrine()->getRepository(Fridge::class);
$prepo = $this->getDoctrine()->getRepository(Product::class);
$fridge = $frepo->find($fridge_id);
$products = $prepo->findLastProductStocks($fridge);
return $this->render(
'view_fridge_products.html.twig',
array(
'fridge' => $fridge,
'products' => $products,
'page_title' => 'Productos en refrigerador '.$fridge->getFriendlyName(),
)
);
}
}