<?php

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ShippingConfigType;
use CpCreation\VitiCore\Shop\Model\ShippingConfig;
use CpCreation\VitiCore\Shop\Repository\ShippingConfigRepository;
use Doctrine\ORM\EntityManagerInterface;
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('/shipping-config')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN') or is_granted('ROLE_SHIPPING')"))]
final class ShippingConfigController extends AbstractController
{
    public function __construct(
        private readonly ShippingConfigRepository $shippingConfigRepository,
        private readonly EntityManagerInterface $em,
    ) {}

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

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

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

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

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

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

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

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

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

            $data->setUpdatedAt(new \DateTimeImmutable()); // Forcer Update de doctrine
            $this->shippingConfigRepository->save($data);

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

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

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

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

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

    #[Route('/{id}/delete/price', name: 'admin_shipping_config_price_delete')]
    public function deleteShippingPrice(ShippingConfig $config): Response
    {
        $connection = $this->em->getConnection();
        $platform   = $connection->getDatabasePlatform();

        // Doctrine DBAL 3+ : executeStatement()
        $connection->executeStatement($platform->getTruncateTableSQL('shop_shipping_auto', true));

        $config->setFile(null);
        $this->shippingConfigRepository->save($config);

        return $this->redirectToRoute('admin_shipping_config_edit', [
            'id' => $config->getId(),
        ]);
    }

    #[Route('/{id}/delete/sup', name: 'admin_shipping_config_sup_delete')]
    public function deleteShippingCost(ShippingConfig $config): Response
    {
        $connection = $this->em->getConnection();
        $platform   = $connection->getDatabasePlatform();

        $connection->executeStatement($platform->getTruncateTableSQL('shop_shipping_auto_sup', true));

        $config->setFileSup(null);
        $this->shippingConfigRepository->save($config);

        return $this->redirectToRoute('admin_shipping_config_edit', [
            'id' => $config->getId(),
        ]);
    }
}
