<?php

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\UserType;
use CpCreation\VitiCore\User\Model\User;
use CpCreation\VitiCore\User\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/users')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN')"))]
final class UserController extends AbstractController
{
    public function __construct(
        private readonly UserRepository $userRepository,
    ) {}

    #[Route('', name: 'admin_user')]
    public function listAllUsers(): Response
    {
        $users = $this->userRepository->findAdminUsers();

        return $this->render('@CpCreationVitiCore/admin/user/index.html.twig', [
            'items' => $users,
        ]);
    }

    #[Route('/new', name: 'admin_user_new')]
    public function new(Request $request): Response
    {
        $form = $this->createForm(UserType::class, null, [
            'validation_groups' => ['registration', 'Default'],
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var User $data */
            $data = $form->getData();

            $this->userRepository->save($data);
            $this->addFlash('alert-success', 'L\'admin '.$data->getUsername().' a été ajouté avec succès');

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

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

    #[Route('/{id}/edit', name: 'admin_user_edit')]
    public function edit(User $user, Request $request): Response
    {
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var User $data */
            $data = $form->getData();

            $data->setUpdatedAt(new \DateTimeImmutable());
            $this->userRepository->save($data);

            $this->addFlash('alert-success', 'L\'admin '.$data->getUsername().' a été modifié avec succès');

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

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

    #[Route('/{id}/delete', name: 'admin_user_delete')]
    public function delete(User $user): Response
    {
        $this->userRepository->delete($user);
        $this->addFlash('alert-success', 'L\'admin '.$user->getUsername().' a été supprimé avec succès.');

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