<?php

namespace App\Controller;

use App\Entity\Chimp;
use App\Form\ChimpType;
use App\Repository\ChimpRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/chimp/c/r/u/d")
 */
class ChimpCRUDController extends AbstractController
{
    /**
     * @Route("/", name="chimp_c_r_u_d_index", methods={"GET"})
     */
    public function index(ChimpRepository $chimpRepository): Response
    {
        return $this->render('chimp_crud/index.html.twig', [
            'chimps' => $chimpRepository->findAll(),
        ]);
    }

    /**
     * @Route("/new", name="chimp_c_r_u_d_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $chimp = new Chimp();
        $form = $this->createForm(ChimpType::class, $chimp);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($chimp);
            $entityManager->flush();

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

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

    /**
     * @Route("/{id}", name="chimp_c_r_u_d_show", methods={"GET"})
     */
    public function show(Chimp $chimp): Response
    {
        return $this->render('chimp_crud/show.html.twig', [
            'chimp' => $chimp,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="chimp_c_r_u_d_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Chimp $chimp): Response
    {
        $form = $this->createForm(ChimpType::class, $chimp);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

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

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

    /**
     * @Route("/{id}", name="chimp_c_r_u_d_delete", methods={"POST"})
     */
    public function delete(Request $request, Chimp $chimp): Response
    {
        if ($this->isCsrfTokenValid('delete'.$chimp->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($chimp);
            $entityManager->flush();
        }

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