<?php

namespace App\Controller;

use App\Entity\Newsletter;
use App\Form\NewsletterType;
use App\Repository\ArticleRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

final class HomeController extends AbstractController
{
    #[Route('/', name: 'app_home')]
    public function index(ArticleRepository $articleRepository,Request $request,EntityManagerInterface $entityManager): Response
    {
        $articles= $articleRepository->findBy(
            ['published' => 1],
            ['datePublication'=>'DESC']
        );
        //integer le formulaire newsletter
            // Créer le formulaire
            $newsletter = new Newsletter();
            $form = $this->createForm(NewsletterType::class,$newsletter);

            // Gérer la soumission du formulaire
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {

                $email = $form->getData()->getEmail();
                $entityManager->persist($newsletter);
                $entityManager->flush();
                // Ajouter un message flash
                $this->addFlash('success', 'Merci pour votre inscription à la newsletter !');
                // Rediriger pour éviter le re-soumission du formulaire
                return $this->redirectToRoute('app_home');
            }

        //integer le formulaire newsletter

        return $this->render('home/index.html.twig', [
            'titre' => 'accueil',
            'articles'=>$articles,
            'form' => $form
        ]);
    }
}
