<?php
if (!defined('ABSPATH')) exit();
if (!class_exists('DbIndeedAbstract')) require_once ULP_PATH . 'classes/Abstracts/DbIndeedAbstract.class.php';
if (class_exists('DbQuizQuestions')) return;
class DbQuizQuestions extends DbIndeedAbstract{
	/**
	 * @var string
	 */
	protected $table = '';
	/**
	 * @param none
	 * @return none
	 */
	public function __construct(){
		global $wpdb;
		$this->table = $wpdb->prefix . 'ulp_quizes_questions';
	}
	/**
	 * Return all questions for a quiz
	 * @param int (quiz id)
	 * @return array
	 */
	public function getQuizQuestions($quiz_id=0, $asc_or_desc='ASC'){
		global $wpdb;
		$array = array();
		$quiz_id = esc_sql($quiz_id);
		$asc_or_desc = esc_sql($asc_or_desc);
		$data = $this->getResults('question_id', "quiz_id=$quiz_id AND status=1 ORDER BY item_order $asc_or_desc"); /// extra cols  item_order, status
		if ($data){
			foreach ($data as $subarray){
				//$array[$subarray['question_id']] = $subarray;
				$array[] = $subarray['question_id'];
			}
		}
		return $array;
	}
	/**
	 * @param int (question id)
	 * @param int (quiz id)
	 * @return bool
	 */
	public function deleteQuestionFromQuiz($question_id=0, $quiz_id=0){
		global $wpdb;
		$question_id = esc_sql($question_id);
		$quiz_id = esc_sql($quiz_id);
		return $wpdb->query("DELETE FROM {$this->table} WHERE question_id=$question_id AND quiz_id=$quiz_id ;");
	}
	/**
	 * @param int (question id)
	 * @param int (quiz id)
	 * @return int
	 */
	public function saveQuizQuestion($question_id=0, $quiz_id=0, $item_order=0, $status=0){
		$quiz_id = esc_sql($quiz_id);
		$question_id = esc_sql($question_id);
		$item_order = esc_sql($item_order);
		$status = esc_sql($status);
		$id = $this->getVar('id', "quiz_id=$quiz_id AND question_id=$question_id");
		if ($id){
			$this->update("item_order=$item_order, status=$status", "id=$id");
			return $id;
		} else {
			return $this->insert("null, $quiz_id, $question_id, $item_order, $status");
		}
	}
}
