<?php

namespace App\Controller\BackendAdmin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

use Doctrine\ORM\EntityManagerInterface;

use App\Repository\CategorieRepository;

use App\Entity\Categorie;

use App\Form\BackendAdmin\CategorieType;

#[Route('/backend/admin/categorie')]
class CategorieController extends AbstractController
{

    /**
     * @var CategorieRepository $categorieRepository
     */
    private $categorieRepository;

    /**
     * @var EntityManagerInterface $em
     */
    private $em;

    /**
     * @param CategorieRepository $categorieRepository
     * @param EntityManagerInterface $em
     * @return $this
     */
    public function __construct(
        CategorieRepository $categorieRepository,
        EntityManagerInterface $em
    ){
        $this->categorieRepository = $categorieRepository;
        $this->em = $em;
    }


    #[Route('/index', name: 'backend_admin_categorie_index')]
    public function index(Request $request): Response
    {
        $categorie = new Categorie();

        $idCategorie = $request->get('idCategorie');
        if($idCategorie){
            $categorie = $this->categorieRepository->find($idCategorie);
        }
        
        $form = $this->createForm(CategorieType::class, $categorie);
        
        return $this->render('backend_admin/categorie/index_categorie.html.twig', ['form'=>$form, 'categorie' => $categorie, 'categories'=> $this->categorieRepository->findBy([], ["id"=>'DESC'])]);
    }

    
    #[Route('/add', name: 'backend_admin_categorie_add')]
    public function add(Request $request): Response
    {
        $categorie = new Categorie();
		
		$form = $this->createForm(CategorieType::class, $categorie);

        $form->handleRequest($request);
        
		if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($categorie);
			$this->em->flush();
            $this->addFlash('success', ['title'=>'Success', 
                                        'message'=>"La catégorie <b>(".$categorie->getNom().")</b> a été bien créer."]);
		}
        return $this->redirectToRoute('backend_admin_categorie_index');
    }


    #[Route('/update/{id}', name: 'backend_admin_categorie_update')]
    public function update(Request $request, Categorie $categorie): Response
    {
        $form = $this->createForm(CategorieType::class, $categorie);

        $form->handleRequest($request);
		if ($form->isSubmitted() && $form->isValid()) {
			
            $this->em->persist($categorie);
			$this->em->flush();

            $this->addFlash('success', ['title'=>'Success', 
                                        'message'=>"La catégorie <b>(".$categorie->getNom().")</b> a été bien Modifier."]);
		}

        return $this->redirectToRoute('backend_admin_categorie_index');
    }


    
    
}


//datatable.html.twig