<?php

namespace App\Controller\Brain;

use App\Entity\Category;
use App\Form\CategoryType;

use Doctrine\ORM\EntityManagerInterface;

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

final class BrainCategoryController extends AbstractController
{
    #[Route('/brain/category/list', name: 'brain_categories_list')]
    public function index(EntityManagerInterface $entityManager): Response
    {

        $categories = $entityManager->getRepository(Category::class)->findAll();
        return $this->render('brain/taxonomy/index.html.twig', [
            'taxonomy' => $categories,
            'type' => 'Category'
        ]);
    }

    #[Route('/brain/category/new', name: 'brain_categories_new')]
    public function new(EntityManagerInterface $entityManager, Request $request): Response
    {

        $form = $this->createForm(CategoryType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $data = $form->getData();
            $category = new Category();

            $category->setTitle($data->getTitle());

            $entityManager->persist($category);

            $entityManager->flush();

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

        return $this->render('brain/taxonomy/create.html.twig', [
            'action' => 'New',
            'form' => $form,
            'type' => 'Category'
        ]);
    }
}
