<?php

namespace App\Controller;

use App\Entity\Configuration;
use App\Form\ConfigurationType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class ConfigurationController extends AbstractController
{
    private EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    #[Route('/admin/configuration', name: 'admin_configuration_index')]
    public function index(Request $request): Response
    {
        $configuration = $this->entityManager->getRepository(Configuration::class)->findOneBy(['id' => 1]);
        $form = $this->createForm(ConfigurationType::class, $configuration);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $isConfiguration = $this->entityManager->getRepository(Configuration::class)->findOneBy(['id' => 1]);
            if ($isConfiguration) {
                $isConfiguration->setOwnerMail($form->getData()->getOwnerMail());
            } else {
                $configuration = new Configuration();
                $configuration->setOwnerMail($form->getData()->getOwnerMail());
                $this->entityManager->persist($configuration);
            }
            $this->entityManager->flush();
        }
        return $this->render('configuration/index.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}
