<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\DrinkType;
use App\Form\DrinkTypeForm;
use App\Repository\DrinkTypeRepository;
use App\Service\InventoryService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/drink-type')]
final class DrinkTypeController extends AbstractController
{
    #[Route(name: 'app_drink_type_index', methods: ['GET'])]
    public function index(InventoryService $inventoryService): Response
    {
        return $this->render('drink_type/index.html.twig', [
            'drink_stocks' => $inventoryService->getAllDrinkTypesWithStockLevels(true)
        ]);
    }

    #[Route(path: '/new', name: 'app_drink_type_new', methods: ['GET', 'POST'])]
    public function new(Request $request, EntityManagerInterface $entityManager): Response
    {
        $drinkType = new DrinkType('', '');
        $form = $this->createForm(DrinkTypeForm::class, $drinkType);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->persist($drinkType);
            $entityManager->flush();

            return $this->redirectToRoute('app_drink_type_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('drink_type/new.html.twig', [
            'drink_type' => $drinkType,
            'form' => $form,
        ]);
    }

    #[Route(path: '/{id}', name: 'app_drink_type_show', methods: ['GET'])]
    public function show(DrinkType $drinkType): Response
    {
        return $this->render('drink_type/show.html.twig', [
            'drink_type' => $drinkType,
        ]);
    }

    #[Route(path: '/{id}/edit', name: 'app_drink_type_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, DrinkType $drinkType, EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(DrinkTypeForm::class, $drinkType);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->flush();

            return $this->redirectToRoute('app_drink_type_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('drink_type/edit.html.twig', [
            'drink_type' => $drinkType,
            'form' => $form,
        ]);
    }

    #[Route(path: '/{id}', name: 'app_drink_type_delete', methods: ['POST'])]
    public function delete(Request $request, DrinkType $drinkType, EntityManagerInterface $entityManager): Response
    {
        if ($this->isCsrfTokenValid('delete' . $drinkType->getId(), $request->getPayload()->getString('_token'))) {
            $entityManager->remove($drinkType);
            $entityManager->flush();
        }

        return $this->redirectToRoute('app_drink_type_index', [], Response::HTTP_SEE_OTHER);
    }
}
