<?php

require_once 'src/Billets.php';
require_once 'src/Coms.php';

class BilletController
{
    private $entityManager;

    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function add_billet($titre, $contenu)
    {
        $user = $this->entityManager->find(User::class, $_SESSION["id_user"]);

        if (isset($_SESSION["id_user"])){
        $billet = new Billets();
        $billet->setTitre($titre);
        $billet->setContenu($contenu);
        $billet->setAuteur($user);
        $billet->setDatePost(new \DateTime());

        $this->entityManager->persist($billet);
        $this->entityManager->flush();
        }
    }

    public function supr_billet($id)
    {
        $billet = $this->entityManager->find(Billets::class, $id);
        if ($billet) {
            $this->entityManager->remove($billet);
            $this->entityManager->flush();
        }
    }

    public function modify_billet($id, $titre, $contenu)
    {
        $billet = $this->entityManager->find(Billets::class, $id);
        $billet->setTitre($titre);
        $billet->setContenu($contenu);
        $this->entityManager->flush();   
     }

     public function getBilletById($id)
     {
         return $this->entityManager->find(Billets::class, $id);
     }

    public function getCommentairesByBilletId($id): array
    {
        return $this->entityManager->getRepository(Coms::class)
            ->findBy(['billet' => $id], ['datePost' => 'ASC']);
    }
}

?>