<?php

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\TrackingConfigType;
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('/configuration/tracking')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN')"))]
final class TrackingController extends AbstractController
{
    public function __construct(
        private readonly ShopConfigRepository $shopConfigRepository,
    ) {
    }

    #[Route('', name: 'admin_tracking')]
    public function index(Request $request): Response
    {
        $config = $this->shopConfigRepository->findOne() ?? new ShopConfig();

        $form = $this->createForm(TrackingConfigType::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 de tracking a été enregistrée avec succès');

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

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