<?php

namespace App\Controller\Frontend;

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

use Doctrine\ORM\EntityManagerInterface;

use App\Entity\Newslettre;

use App\Repository\NewslettreRepository;
use App\Repository\GroupeCategorieRepository;


#[Route('/frontend/newslettre')]
class NewslettreController extends AbstractController
{

    #[Route('/index', name: 'frontend_newslettre_index')]
    public function index(GroupeCategorieRepository $groupeCategorieRepository): Response
    {
        $selectNews = [];
        foreach($this->getUser()->getNewslettres() as $newslettre){
            $selectNews[] = $newslettre->getRelated();
        }

        return $this->render('frontend/newslettre/index.html.twig', [
            'groupes'=>$groupeCategorieRepository->findAll(),
            'selectNews'=> $selectNews
        ]);
    }


    #[Route('/update', name: 'frontend_newslettre_update')]
    public function update(Request $request, EntityManagerInterface $em, NewslettreRepository $newslettreRepository)
    {
        $operation = $request->get('operation');
        $related = $request->get('related');
        $user = $this->getUser();

        if($operation == "true"){
            $newslettre = new Newslettre();
            $newslettre->setProfile($user);
            $newslettre->setRelated($related);
            $em->persist($newslettre);
        }else{
            $newslettre = $newslettreRepository->findOneBy(['related'=>$related, 'profile'=>$user]);
            $em->remove($newslettre);
        }
        
        $em->flush();
        
        return new Response("true");
    }

}
