<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

use CpCreation\VitiCore\AgeVerification\Model\AgeVerificationConfig;
use CpCreation\VitiCore\AgeVerification\Repository\AgeVerificationConfigRepository;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\AgeVerificationConfigType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Translation\TranslatorInterface;

#[Route('/configuration/age-verification')]
#[IsGranted('ROLE_ADMIN')]
final class AgeVerificationController extends AbstractController
{
    public function __construct(
        private readonly AgeVerificationConfigRepository $configRepository,
        private readonly TranslatorInterface $translator,
    ) {}

    #[Route('', name: 'admin_age_verification')]
    public function index(Request $request): Response
    {
        $config = $this->configRepository->findOne() ?? new AgeVerificationConfig();
        $form = $this->createForm(AgeVerificationConfigType::class, $config);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var AgeVerificationConfig $data */
            $data = $form->getData();
            $this->configRepository->save($data);
            $this->addFlash('alert-success', $this->translator->trans('age_verification.admin.saved'));

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

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