<?php

namespace Modules\Ajax\Controller;

use Skeleton\Controller\Controller;
use Entity\Model\Favoris;

class FavorisController extends Controller
{
    public function ajouterFavorisAction() :string
    {
        $post = $this->request->getParsedBody();
    
        $entity_Favoris = new Favoris($this->pdo);
        
        $fav_exist = $entity_Favoris->find([
            'ID_USER' => $_SESSION['Session_Login'],
            'TITRE_FAV' =>  $post['titre'],
        ]);

        if (!$fav_exist) {
            $entity_Favoris->insert([
                'ID_USER' => $_SESSION['Session_Login'],
                'PATH_FAV' => $post['path'],
                'PATH_PARAMS' => json_encode($post['param'] ?? null) == 'null'
                    ? ''
                    : json_encode($post['param']),
                'TITRE_FAV' => $post['titre'],
            ]);

            $listeFav = (new \Modules\Ajax\Repository\Favoris($this->pdo))->listeFavoris();
            $_SESSION['USER']['FAVORIS'] = $listeFav;
        }
        
        return 'true';
    }
    
    public function supprimerFavorisAction() :string
    {
        $post = $this->request->getParsedBody();
        $entity_Favoris = new Favoris($this->pdo);
        
        $entity_Favoris->delete($post['id']);

        $listeFav = (new \Modules\Ajax\Repository\Favoris($this->pdo))->listeFavoris();
        $_SESSION['USER']['FAVORIS'] = $listeFav;

        return 'true';
    }
}
