<?php

namespace App\Controller;

use App\Entity\Servico;
use App\Form\EditServicoType;
use App\Form\ServicoType;
use App\Repository\ServicoRepository;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/admin/servico', name: 'app_admin_servico_')]
class ServicoController extends AbstractController
{
    #[Route('/', name: 'index')]
    public function index(ServicoRepository $servicoRepository, PaginatorInterface $paginator, Request $request, EntityManagerInterface $em): Response
    {
        $servico = new Servico();
        $form = $this->createForm(ServicoType::class,$servico);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $em->persist($servico);
            $em->flush();
            $this->addFlash('success','Serviço clínico salvo com sucesso!');
            return $this->redirectToRoute('app_admin_servico_index');
        }

        $query = $servicoRepository->findServicos();
        $pagination = $paginator->paginate($query,$request->query->getInt('page',1),6 );
        return $this->render('servico/index.html.twig', [
            'form' => $form->createView(),
            'pagination' => $pagination
        ]);
    }

    #[Route('/editar/{id}', name: 'edit')]
    public function editServico(Servico $servico,Request $request, EntityManagerInterface $em): Response
    {
        $form = $this->createForm(EditServicoType::class,$servico);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $em->persist($servico);
            $em->flush();
            //$this->addFlash('success','Serviço clínico salvo com sucesso!');
            return $this->redirectToRoute('app_admin_servico_index');
        }
        return $this->render('servico/editServico.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/apagar/{id}', name: 'delete')]
    public function deleteServico(Servico $servico, EntityManagerInterface $em){
        $em->remove($servico);
        $em->flush();
        $this->addFlash('success','Serviço removido com sucesso!');
        return $this->redirectToRoute('app_admin_servico_index');
    }
}
