<?php

declare(strict_types=1);

namespace App\Game\Controller;

use App\Tech\Entity\User;
use App\Tech\Form\AdminUserType;
use App\Tech\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/admin/users')]
#[IsGranted('ROLE_ADMIN')]
final class GameAdminUserController extends AbstractController
{
    #[Route('', name: 'game_admin_users', methods: ['GET'])]
    public function index(UserRepository $userRepository): Response
    {
        $users = $userRepository->findBy([], ['id' => 'ASC']);

        return $this->render('game/admin/users/index.html.twig', [
            'users' => $users,
            'marketingOptInCount' => count(array_filter($users, static fn (User $user) => $user->isMarketingOptIn())),
        ]);
    }

    #[Route('/{id}/edit', name: 'game_admin_user_edit', methods: ['GET', 'POST'])]
    public function edit(
        User $user,
        Request $request,
        EntityManagerInterface $em,
        UserPasswordHasherInterface $passwordHasher,
    ): Response {
        $form = $this->createForm(AdminUserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $plainPassword = $form->get('plainPassword')->getData();
            if ($plainPassword) {
                $user->setPassword($passwordHasher->hashPassword($user, $plainPassword));
            }

            $em->flush();
            $this->addFlash('success', sprintf('User "%s" updated.', $user->getUsername()));

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

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

    #[Route('/{id}/delete', name: 'game_admin_user_delete', methods: ['POST'])]
    public function delete(User $user, Request $request, EntityManagerInterface $em): Response
    {
        if (!$this->isCsrfTokenValid('delete_user_' . $user->getId(), $request->request->get('_token'))) {
            $this->addFlash('danger', 'Invalid CSRF token.');
            return $this->redirectToRoute('game_admin_users');
        }

        $username = $user->getUsername();
        $em->remove($user);
        $em->flush();

        $this->addFlash('success', sprintf('User "%s" deleted.', $username));

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