<?php

declare(strict_types=1);

namespace App\Game\Controller;

use App\Game\Entity\GameSetting;
use App\Game\Enum\GameSettingType;
use App\Game\Form\AdminGameType;
use App\Game\Entity\Game;
use App\Game\Repository\GameRepository;
use App\Game\Repository\GameSettingRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/admin/games')]
#[IsGranted('ROLE_ADMIN')]
final class GameAdminGameController extends AbstractController
{
    #[Route('', name: 'game_admin_games', methods: ['GET'])]
    public function index(GameRepository $gameRepository): Response
    {
        return $this->render('game/admin/games/index.html.twig', [
            'games' => $gameRepository->findBy([], ['id' => 'ASC']),
        ]);
    }

    #[Route('/{id}/edit', name: 'game_admin_game_edit', methods: ['GET', 'POST'])]
    public function edit(
        Game $game,
        Request $request,
        EntityManagerInterface $em,
        GameSettingRepository $gameSettingRepository,
    ): Response {
        $totalTimeSetting = $gameSettingRepository->getSetting($game, GameSettingType::TOTAL_TIME);

        $form = $this->createForm(AdminGameType::class, $game, [
            'total_time' => $totalTimeSetting?->getValue(),
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $totalTime = $form->get('totalTime')->getData();

            if ($totalTime !== null) {
                if (!$totalTimeSetting) {
                    $totalTimeSetting = new GameSetting();
                    $totalTimeSetting->setGame($game);
                    $totalTimeSetting->setName(GameSettingType::TOTAL_TIME);
                }
                $totalTimeSetting->setValue((string) $totalTime);
                $em->persist($totalTimeSetting);
            }

            $em->flush();
            $this->addFlash('success', sprintf('Game "%s" updated.', $game->getName()));

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

        return $this->render('game/admin/games/edit.html.twig', [
            'game' => $game,
            'form' => $form,
        ]);
    }
}
