<?php

class GatewayQuestion
{
    private $con;

    public function __construct()
    {
        global $dns, $user, $pass;
        $this->con = new Connection($dns, $user, $pass);
    }

    public function addQuestion($question)
    {
        $query = "insert into questions(content,idchapter,difficulty,nbfails) values (:content,:idchapter,:difficulty,:nbfails);";
        $this->con->executeQuery(
            $query,
            array(
                ':content' => array($question['content'], PDO::PARAM_STR),
                ':idchapter' => array($question['idchapter'], PDO::PARAM_INT),
                ':difficulty' => array(intval($question['difficulty']), PDO::PARAM_INT),
                ':nbfails' => array(intval($question['nbfails']), PDO::PARAM_INT)
            )
        );
        $questionId = $this->con->lastInsertId();
        return $questionId;
    }

    public function getQuestionByID($id)
    {
        $query = "SELECT * FROM questions WHERE id = :id;";
        $this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
        $results = $this->con->getResults();

        return $results[0];
    }

    public function getQuestions()
    {
        $query = "SELECT * FROM questions";
        $this->con->executeQuery($query);
        $results = $this->con->getResults();

        return $results;
    }

    public function updateQuestion($id, $question)
    {
        $query = "UPDATE questions SET content = :content, idchapter = :idchapter, idanswergood = :idanswergood WHERE id = :id;";
        $this->con->executeQuery(
            $query,
            array(
                ':content' => array($question['content'], PDO::PARAM_STR),
                ':idchapter' => array($question['idchapter'], PDO::PARAM_INT),
                ':idanswergood' => array($question['idanswergood'], PDO::PARAM_INT),
                ':id' => array($id, PDO::PARAM_INT),
            )
        );
    }

    public function deleteQuestionByID($id)
    {
        $query = "DELETE FROM questions WHERE id = :id;";
        $this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
    }

    public function getQuestionsByChapterAndDifficulty($idChapter, $difficulty)
    {
        $query = "SELECT * FROM questions WHERE idchapter = :idChapter AND difficulty = :difficulty;";
        $this->con->executeQuery(
            $query,
            array(
                ':idChapter' => array($idChapter, PDO::PARAM_INT),
                ':difficulty' => array($difficulty, PDO::PARAM_INT),
            )
        );
        $results = $this->con->getResults();

        return $results;
    }
}
