<?php

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

   public function add_user($login, $mdp)
   {
        $user = new User();
        $user->setLogin($login);
        if (!empty($mdp)) {
            $user->setMdp($mdp);
        }
        $this->entityManager->persist($user);
        $this->entityManager->flush();
   }

   public function supr_user($id)
    {
        $user = $this->entityManager->find(User::class, $id);
        if ($user) {
            $this->entityManager->remove($user);
            $this->entityManager->flush();
        }
    }

    public function traite_login($login, $password)
    {
        $userController = $this->entityManager->getRepository(User::class);
        $user = $userController->findOneBy(['login' => $login]);
        if (!$user) {
            return "<div class='message error'>Login incorrect</div>
                    <a href=\"login.php\" class=\"link\">Retentez votre chance !</a><br>
                    <a href=\"inscription.php\" class=\"link\">Ou inscrivez-vous !</a>";
        }
        if (!password_verify($password, $user->getMdp())) {
            return "<div class='message error'>Mot de passe incorrect</div>
                    <a href=\"login.php\" class=\"link\">Retentez votre chance !</a><br>
                    <a href=\"inscription.php\" class=\"link\">Ou inscrivez-vous !</a>";
        }

        $_SESSION["login"] = $user->getLogin();
        $_SESSION["id_user"] = $user->getId();

        return "<div class='message success'>Vous êtes connecté. Bienvenue {$user->getLogin()}</div>
                <a href=\"index.php\" class=\"link\">Page d'accueil</a>";
    }


    public function modify_user($id_user, $login, $mdp)
    {
        $user = $this->entityManager->find(User::class, $id_user);

        $user->setLogin($login);
        $user->setMdp($mdp);

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

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

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

?>