<?php

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ShippingAutoSupType;
use CpCreation\VitiCore\Shop\Model\ShippingAutoSup;
use CpCreation\VitiCore\Shop\Repository\ShippingAutoSupRepository;
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-auto-sup')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN')"))]
final class ShippingAutoSupController extends AbstractController
{
    public function __construct(
        private readonly ShippingAutoSupRepository $shippingAutoSupRepository,
    ) {}

    #[Route('', name: 'admin_shipping_auto_sup')]
    public function index(): Response
    {
        $cities = $this->shippingAutoSupRepository->findOrder();
        $citiesNoFound = $this->shippingAutoSupRepository->findCheckFalse();

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

    #[Route('/{id}/edit', name: 'admin_shipping_auto_sup_edit')]
    public function edit(ShippingAutoSup $shippingAutoSup, Request $request): Response
    {
        $form = $this->createForm(ShippingAutoSupType::class, $shippingAutoSup);
        $form->handleRequest($request);

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

            $this->shippingAutoSupRepository->save($data);
            $this->addFlash('alert-success', 'La ville '.$shippingAutoSup->getCity().' a été modifiée avec succès.');

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

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