<?php
    
class Quiz{

    private $con;

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

    public function getQuestions($num, $lang){
        $lang_table = "question_text_" . mysqli_real_escape_string($this->con, $lang);

        $sql = "SELECT q.id_question, q.correct_answer, qt.question_text, qt.answer_one, qt.answer_two, qt.answer_three  FROM question q
        JOIN $lang_table qt on q.id_question = qt.id_question 
        ORDER BY RAND() LIMIT $num"; 
        $result = mysqli_query($this->con, $sql); 
        $data = array(); 
        while($row = mysqli_fetch_assoc($result)){
          $data["question"][] = $row;  
        }
        return $data; 
    }

    public function setExperience($id_user, $points){
      $sql = "SELECT experience, level FROM user WHERE id_user = $id_user";
      $result = mysqli_query($this->con, $sql); 
      $row = mysqli_fetch_assoc($result); 
      $lvl = $row["level"]; 
      $exp = $row["experience"]; 
      if($exp+$points<100){
        $sql = "UPDATE user SET experience = experience + $points WHERE id_user = $id_user"; 
        $result = mysqli_query($this->con, $sql); 
        if($result === TRUE){
          return 1;
        }else{
            return 0;
        }
      }else{
        $points = $exp+$points-100;
        $sql = "UPDATE user SET experience = 0, level = level + 1 WHERE id_user = $id_user"; 
        $result = mysqli_query($this->con, $sql); 
        if($result === TRUE){
          $sql = "UPDATE user SET experience = $points WHERE id_user = $id_user"; 
          $result = mysqli_query($this->con, $sql); 
          if($result === TRUE){
            return 1;
          }else{
            return 0;
          }
        }else{
            return 0;
        }
        
      }
    }
}
?>