<?php

namespace App\Controller;

use App\Entity\Plats;
use App\Form\PlatType;
use App\Form\StatutCommandeType;
use App\Repository\PlatsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;

#[Route('/plats', name: 'app_plat')]
class PlatController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly PlatsRepository $platsRepository
    )
    {
    }

    #[Route('/add', name: '_add')]
    public function add(Request $request): Response
    {
        $plat = new Plats();
        $form = $this->createForm(PlatType::class, $plat);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->entityManager->persist($plat);
            $this->entityManager->flush();
        }

        return $this->render('plat/add.html.twig', [
            'formAdd' => $form,
        ]);
    }

    #[Route('/list', name: '_list')]
    public function list(): Response
    {
        $plat = $this->platsRepository->findAll();
        return $this->render('plat/list.html.twig', [
            'plat' => $plat,
        ]);
    }

    #[Route('/update/{id}', name: '_update')]
    public function update(int $id, Request $request): Response
    {
        $plat = $this->platsRepository->find($id);
        $form = $this->createForm(PlatType::class, $plat);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid())
        {
            $this->entityManager->persist($plat);
            $this->entityManager->flush();
        }

        return $this->render('plat/add.html.twig', [
            'formAdd' => $form,
        ]);
    }

    #[Route('/delete/{id}', name: '_delete')]
    public function delete(int $id): Response
    {
        $statutCommandes = $this->platsRepository->find($id);
        $this->entityManager->remove($statutCommandes);
        $this->entityManager->flush();

        return $this->redirectToRoute('app_plat_list');
    }
}
