<?php

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ShopConfigType;
use CpCreation\VitiCore\Shop\Model\ShopConfig;
use CpCreation\VitiCore\Shop\Repository\ShopConfigRepository;
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('/shop-config')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN')"))]
final class ShopConfigController extends AbstractController
{
    public function __construct(
        private readonly ShopConfigRepository $shopConfigRepository,
    ) {}

    #[Route('', name: 'admin_shop_config')]
    public function index(): Response
    {
        $config = $this->shopConfigRepository->findAll();

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

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

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

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

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

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

    #[Route('/{id}/edit', name: 'admin_shop_config_edit')]
    public function edit(ShopConfig $config, Request $request): Response
    {
        $form = $this->createForm(ShopConfigType::class, $config);
        $form->handleRequest($request);

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

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

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

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

    #[Route('/{id}/delete', name: 'admin_shop_config_delete')]
    public function delete(ShopConfig $config): Response
    {
        $this->shopConfigRepository->delete($config);
        $this->addFlash('alert-success', 'La configuration a été supprimée avec succès.');

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