<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\NewsType;
use CpCreation\VitiCore\News\Model\News;
use CpCreation\VitiCore\News\Repository\NewsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/news')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN') or is_granted('ROLE_NEWS')"))]
final class NewsController extends AbstractController
{
    public function __construct(
        private readonly NewsRepository $newsRepository,
    ) {}

    #[Route('', name: 'admin_news')]
    public function index(): Response
    {
        $news = $this->newsRepository->findBy([], ['eventAt' => 'DESC']);

        return $this->render('@CpCreationVitiCore/admin/news/index.html.twig', [
            'items' => $news,
        ]);
    }

    #[Route('/new', name: 'admin_news_new')]
    public function new(Request $request): Response
    {
        $form = $this->createForm(NewsType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var News $data */
            $data = $form->getData();

            $this->newsRepository->save($data);
            $this->addFlash('alert-success', 'La news '.$data->getTitle().' a été ajoutée avec succès');

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

        return $this->render('@CpCreationVitiCore/admin/news/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/edit', name: 'admin_news_edit')]
    public function edit(News $news, Request $request): Response
    {
        $form = $this->createForm(NewsType::class, $news);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var News $data */
            $data = $form->getData();

            $data->setUpdatedAt(new \DateTimeImmutable());

            $this->newsRepository->save($data);
            $this->addFlash('alert-success', 'La news '.$news->getTitle().' a été modifiée avec succès');

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

        return $this->render('@CpCreationVitiCore/admin/news/edit.html.twig', [
            'item' => $news,
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/delete', name: 'admin_news_delete')]
    public function delete(News $news): Response
    {
        $this->newsRepository->delete($news);
        $this->addFlash('alert-success', 'La news '.$news->getTitle().' a été supprimée avec succès.');

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