<?php

namespace App\Controller;

use App\Entity\Anuncio;
use App\Form\AnuncioType;
use App\Repository\AnuncioRepository;
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('/anuncio')]
class AnuncioController extends AbstractController
{
    #[Route('/', name: 'app_anuncio_index', methods: ['GET'])]
    public function index(AnuncioRepository $anuncioRepository): Response
    {
        return $this->render('anuncio/index.html.twig', [
            'anuncios' => $anuncioRepository->findAll(),
        ]);
    }

    #[Route('/new', name: 'app_anuncio_new', methods: ['GET', 'POST'])]
    public function new(Request $request, EntityManagerInterface $entityManager): Response
    {
        $anuncio = new Anuncio();
        $form = $this->createForm(AnuncioType::class, $anuncio);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->persist($anuncio);
            $entityManager->flush();

            return $this->redirectToRoute('app_anuncio_index', [], Response::HTTP_SEE_OTHER);
        }

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

    #[Route('/{id}', name: 'app_anuncio_show', methods: ['GET'])]
    public function show(Anuncio $anuncio): Response
    {
        return $this->render('anuncio/show.html.twig', [
            'anuncio' => $anuncio,
        ]);
    }

    #[Route('/{id}/edit', name: 'app_anuncio_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Anuncio $anuncio, EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(AnuncioType::class, $anuncio);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->flush();

            return $this->redirectToRoute('app_anuncio_index', [], Response::HTTP_SEE_OTHER);
        }

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

    #[Route('/{id}', name: 'app_anuncio_delete', methods: ['POST'])]
    public function delete(Request $request, Anuncio $anuncio, EntityManagerInterface $entityManager): Response
    {
        if ($this->isCsrfTokenValid('delete'.$anuncio->getId(), $request->request->get('_token'))) {
            $entityManager->remove($anuncio);
            $entityManager->flush();
        }

        return $this->redirectToRoute('app_anuncio_index', [], Response::HTTP_SEE_OTHER);
    }
}
