<?php

namespace App\Controller;

use App\Entity\Reductions;
use App\Form\ReductionsType;
use App\Repository\ReductionsRepository;
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('/reductions')]
final class ReductionsController extends AbstractController
{
    #[Route(name: 'app_reductions_index', methods: ['GET'])]
    public function index(ReductionsRepository $reductionsRepository): Response
    {
        return $this->render('reductions/index.html.twig', [
            'reductions' => $reductionsRepository->findAll(),
        ]);
    }

    #[Route('/new', name: 'app_reductions_new', methods: ['GET', 'POST'])]
    public function new(Request $request, EntityManagerInterface $entityManager): Response
    {
        $reduction = new Reductions();
        $form = $this->createForm(ReductionsType::class, $reduction);
        $form->handleRequest($request);

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

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

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


    #[Route('/{id}/edit', name: 'app_reductions_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Reductions $reduction, EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(ReductionsType::class, $reduction);
        $form->handleRequest($request);

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

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

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

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

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