<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ProductTaxType;
use CpCreation\VitiCore\Product\Model\ProductTax;
use CpCreation\VitiCore\Product\Repository\ProductTaxRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/product-tax')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN')"))]
final class ProductTaxController extends AbstractController
{
    public function __construct(
        private readonly ProductTaxRepository $productTaxRepository,
    ) {}

    #[Route('', name: 'admin_product_tax')]
    public function index(): Response
    {
        $taxes = $this->productTaxRepository->findAll();

        return $this->render('@CpCreationVitiCore/admin/product/tax/index.html.twig', [
            'items' => $taxes,
        ]);
    }

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

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var ProductTax $data */
            $data = $form->getData();

            $this->productTaxRepository->save($data);
            $this->addFlash('alert-success', 'La taxe a été ajoutée avec succès');

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

        return $this->render('@CpCreationVitiCore/admin/product/tax/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/edit', name: 'admin_product_tax_edit')]
    public function edit(ProductTax $tax, Request $request): Response
    {
        $form = $this->createForm(ProductTaxType::class, $tax);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var ProductTax $data */
            $data = $form->getData();

            $this->productTaxRepository->save($data);
            $this->addFlash('alert-success', 'La taxe a été modifiée avec succès');

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

        return $this->render('@CpCreationVitiCore/admin/product/tax/edit.html.twig', [
            'item' => $tax,
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/delete', name: 'admin_product_tax_delete')]
    public function delete(ProductTax $tax): Response
    {
        $this->productTaxRepository->delete($tax);
        $this->addFlash('alert-success', 'La taxe a été supprimée avec succès.');

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