<?php
namespace Gateway;
use PDO;

class CommentaryGateway  extends Gateway{

    public function firstIdComment():int{
        $query = "Select id_comment from Commentary;";
        $this -> co -> executeQuery($query);
        $res = $this -> co -> getResults();
        $tab = null;
        foreach($res as $r){
            $tab[] = $r["id_comment"];
        }
        if($tab == null){
            return 1;
        }
        $id=1;
        while(in_array($id,$tab)){$id=$id+1;}
        return $id;
    }

    public function create(string $comment ,string $idUser, int $idQuote) :bool {
        $id=$this->firstIdComment();

        $query="INSERT INTO Commentary(quote,users,datec,comment,id_comment) VALUES(:idQuote, :idUser , CURRENT_DATE,:comment ,:idComment)";

        return $this -> co -> executeQuery($query, array(
            "comment" => array($comment, PDO::PARAM_STR),
            "idUser" => array($idUser, PDO::PARAM_STR),
            "idQuote" => array($idQuote, PDO::PARAM_INT),
            "idComment" => array($id, PDO::PARAM_INT)));
    }

    public function findById(int $id) : array {

        $query="SELECT * FROM Commentary WHERE id_comment = :id_comment";

        $this -> co -> executeQuery($query, array("id_comment" => $id));
        return $res = $this -> co -> getResults();
    }

    public function findByQuote(int $id) : array{
        $query="SELECT c.id_comment, c.dateC, c.comment, u.username, i.imgPath FROM Commentary c JOIN Users u ON u.id_user = c.users JOIN Image i ON i.id_img = u.img WHERE quote = :idQuote ORDER BY c.datec DESC";
        $this -> co -> executeQuery($query, array("idQuote" => array($id,PDO::PARAM_STR)));
        return $res = $this -> co -> getResults();
    }


    public function findAll() : array {
        $query="SELECT * FROM Commentary";
        $this -> co -> executeQuery($query);
        return $res = $this -> co -> getResults();
    }

    public function delete(int $id) : bool {
        $query="DELETE FROM Commentary WHERE id_comment = :id_comment";
        return $this -> co -> executeQuery($query, array("id_comment" => $id));

    }

    public function update(commentaryEntity $c) : bool {

        $query="UPDATE Commentary SET comment = :comment WHERE id_comment = :id_comment";

        return $this -> co -> executeQuery($query, array(
            "comment" => array($c->getComment(),PDO::PARAM_STR),
            "id_comment" => array($c->getIdComment(),PDO::PARAM_INT))
        );

    }
}
?>
