<?php

namespace App\Controller\Brain;

use App\Entity\Page;
use App\Form\PageType;

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 BrainPageController extends AbstractController
{
    #[Route('/brain/page/list', name: 'brain_page_list')]
    public function index(EntityManagerInterface $entityManager): Response 
    {
        $pages = $entityManager->getRepository(Page::class)->findAll();
        
        return $this->render('brain/page/index.html.twig', [
            'pages' => $pages
        ]);
    }

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

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

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $data = $form->getData();
            $page = new Page();

            $page->setTitle($data->getTitle());
            $page->setText($data->getText());
            $page->setUrl($data->getUrl());

            if ($data->isPublished()) {
                $page->setPublished(true);
            } else {
                $page->setPublished(false);
            }

            $entityManager->persist($page);

            $entityManager->flush();

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

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

    #[Route('/brain/page/edit/{id}', name: 'brain_page_edit')]
    public function edit(EntityManagerInterface $entityManager, string $id, Request $request): Response
    {

        $page = $entityManager->getRepository(Page::class)->findOneBy(['id' => $id]);

        $form = $this->createForm(PageType::class, $page);

        $form->handleRequest($request);

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

            $page->setTitle($data->getTitle());
            $page->setText($data->getText());
            $page->setUrl($data->getUrl());

            if ($data->isPublished()) {
                $page->setPublished(true);
            } else {
                $page->setPublished(false);
            }

            $entityManager->flush();

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

        return $this->render('brain/page/create.html.twig', [
            'action' => 'Edit',
            'form' => $form
        ]);
    }
}
