<?php
declare(strict_types=1);

namespace App\Game\Controller;

use App\Game\Entity\Session;
use App\Game\Repository\SessionRepository;
use App\Tech\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

#[Route('/admin')]
#[IsGranted('ROLE_ADMIN')]
final class GameAdminController extends AbstractController
{
    public function __construct(
        #[Autowire('%kernel.project_dir%')]
        private string $projectDir
    ) {
    }

    #[Route('', name: 'game_admin_dashboard', methods: ['GET'])]
    public function index(
        UserRepository $userRepository,
        SessionRepository $sessionRepository
    ): Response {
        $players = $userRepository->findByRole('ROLE_PLAYER');
        $sessions = $sessionRepository->findAll();

        return $this->render('game/admin/index.html.twig', [
            'players' => $players,
            'sessions' => $sessions,
        ]);
    }

    #[Route('/session/{session}', name: 'game_admin_view_session', methods: ['GET'])]
    public function viewSession(Session $session): Response
    {
        $playersLogs = [];
        foreach ($session->getPlayers() as $player) {
            $username = $player->getUser()->getUsername();
            $logFile = $this->projectDir . '/var/log/sessions/' . $session->getId() . '/' . $username . '.txt';

            $logs = '';
            if (file_exists($logFile)) {
                $logs = file_get_contents($logFile);
            }

            $playersLogs[] = [
                'username' => $username,
                'logs' => $logs,
            ];
        }

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