<?php

namespace App\Controller;

use App\Entity\Provincia;
use App\Form\ProvinciaType;
use App\Repository\ProvinciaRepository;
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('/provincia', name: 'app_provincia_')]
class ProvinciaController extends AbstractController
{
    #[Route('/', name: 'index')]
    public function index(ProvinciaRepository $provinciaRepository): Response
    {
        $provincias = $provinciaRepository->findAll();
        return $this->render('provincia/index.html.twig', compact('provincias'));
    }

    #[Route('/add', name: 'add')]
    public function addProvincia(Request $request, EntityManagerInterface $em): Response
    {
        $provincia = new Provincia();
        $form = $this->createForm(ProvinciaType::class,$provincia);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $em->persist($provincia);
            $em->flush();
            $this->addFlash('success','Provincia salvo com sucesso!');
            return $this->redirectToRoute('app_provincia_add');
        }
        return $this->render('provincia/addProvincia.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/edit/{id}', name: 'edit')]
    public function editProvincia(Provincia $provincia,Request $request, EntityManagerInterface $em): Response
    {
        $form = $this->createForm(ProvinciaType::class,$provincia);
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $em->persist($provincia);
            $em->flush();
            $this->addFlash('success','Dados da provincia alterado com sucesso!');
            return $this->redirectToRoute('app_provincia_index');
        }
        return $this->render('provincia/editProvincia.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/apagar/{id}', name: 'delete')]
    public function deleteProvincia(Provincia $prov, EntityManagerInterface $em){

        $em->remove($prov);
        $em->flush();
        $this->addFlash('success','Província removido com sucesso!');
        return $this->redirectToRoute('app_provincia_index');
    }
}
