<?php

namespace App\Controller;

use App\Entity\Usuario;
use App\Form\AdminUsuarioType;
use App\Form\RoleUserType;
use App\Repository\UsuarioRepository;
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;

#[Route('/admin/usuarios', name: 'app_admin_usuarios_')]
class AdminUsuariosController extends AbstractController
{
    #[Route('/', name: 'index')]
    public function index(UsuarioRepository $usuarioRepository): Response
    {
        $usuarios = $usuarioRepository->findAll();
        return $this->render('admin_usuarios/index.html.twig', compact('usuarios'));
    }

    #[Route('/apagar/{id}', name: 'apagar')]
    public function deletarUsuario(Usuario $utilizador, EntityManagerInterface $em){
        $user = $this->getUser();

        if($user != $utilizador){
            $em->remove($utilizador);
            $em->flush();
            $this->addFlash('success','Usuário removido com sucesso!');
            return $this->redirectToRoute('app_admin_usuarios_index');
        }else{
            $this->addFlash('danger','Não podes apagar o administrador!');
            return $this->redirectToRoute('app_admin_usuarios_index');
        }
    }

    #[Route('/editar/{id}', name: 'edit')]
    public function editarRoleUser(Usuario $user,Request $request, EntityManagerInterface $em){
        $form = $this->createForm(RoleUserType::class,$user);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $em->persist($user);
            $em->flush();
            $this->addFlash('success','Dados so usuário alterado com sucesso!');
            return $this->redirectToRoute('app_admin_usuarios_index');
        }

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

    #[Route('/perfil', name: 'perfil')]
    public function PerfilUser(){
        return $this->render('admin_usuarios/perfil.html.twig',[

        ]);
    }
}
