<?php
namespace QuizPress\API\Query;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Quizzes {

	public static function get_total_number_of_quizzes() {
		global $wpdb;
		$results = $wpdb->get_var(
			$wpdb->prepare("SELECT COUNT(ID) 
            FROM {$wpdb->posts} 
            WHERE post_type = %s 
            AND post_status = %s", 'quizpress_quiz', 'publish')
		);
		return (int) $results;
	}

	public static function get_quiz_limit_time( $quiz_id, $need_unit = 'seconds' ) {
		if ( empty( $quiz_id ) ) {
			return 0;
		}

		$save_unit = get_post_meta( $quiz_id, 'quizpress_quiz_time_unit', true );
		$save_time = (int) get_post_meta( $quiz_id, 'quizpress_quiz_time', true );

		if ( $save_time <= 0 ) {
			return 0;
		}

		// Normalize everything to seconds
		$unit_to_seconds = [
			'hours'   => 3600,
			'minutes' => 60,
			'seconds' => 1,
		];

		if ( ! isset( $unit_to_seconds[ $save_unit ], $unit_to_seconds[ $need_unit ] ) ) {
			return 0;
		}

		$seconds = $save_time * $unit_to_seconds[ $save_unit ];

		return $seconds / $unit_to_seconds[ $need_unit ];
	}

	public static function get_total_number_of_quizzes_by_instructor_id( $instructor_id ) {
		global $wpdb;
		$results = $wpdb->get_var(
			$wpdb->prepare("SELECT COUNT(ID) 
            FROM {$wpdb->posts} 
            WHERE post_type = %s 
            AND post_author = %d
			AND post_status = %s", 'quizpress_quiz', $instructor_id, 'publish')
		);
		return (int) $results;
	}

	public static function get_all_quiz_options() {
		global $wpdb;

		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, post_title 
				 FROM {$wpdb->posts} 
				 WHERE post_type = %s",
				'quizpress_quiz'
			)
		);

		return $results;
	}

	public static function get_quiz_settings_by_quiz_id( $ID ) {
		return [
			'quiz_time' => (int) get_post_meta( $ID, 'quizpress_quiz_time', true ),
			'quiz_time_unit' => get_post_meta( $ID, 'quizpress_quiz_time_unit', true ),
			'quiz_hide_quiz_time' => (bool) get_post_meta( $ID, 'quizpress_quiz_hide_quiz_time', true ),
			'quiz_feedback_mode' => get_post_meta( $ID, 'quizpress_quiz_feedback_mode', true ),
			'quiz_passing_grade' => (int) get_post_meta( $ID, 'quizpress_quiz_passing_grade', true ),
			'quiz_max_questions_for_answer' => (int) get_post_meta( $ID, 'quizpress_quiz_max_questions_for_answer', true ),
			'quiz_max_attempts_allowed' => (int) get_post_meta( $ID, 'quizpress_quiz_max_attempts_allowed', true ),
			'quiz_auto_start' => (bool) get_post_meta( $ID, 'quizpress_quiz_auto_start', true ),
			'quiz_questions_order' => get_post_meta( $ID, 'quizpress_quiz_questions_order', true ),
			'quiz_hide_question_number' => (bool) get_post_meta( $ID, 'quizpress_quiz_hide_question_number', true ),
			'quiz_short_answer_characters_limit' => (int) get_post_meta( $ID, 'quizpress_quiz_short_answer_characters_limit', true ),
		];
	}

}
