<?php defined('BASEPATH') || exit('No direct script access allowed.');

/**
* Online Exam Controller
*/
class Online_Exam extends CI_Controller
{
	public $data = array();
	function __construct()
	{
		parent::__construct();

		/*
		Loading Models
		*/
		$this->load->model('subscription_model');
		$this->load->model('online_exam_model');
		$this->load->model('exam_configuration_model');

	}

	public function index()
	{
		$this->load->view('online_exam/index',$this->data);
	}

	public function init($exam_standard, $exam_org, $post_level){
		$this->session->set_userdata('ongoing_exam_config', array(
			'exam_standard' => $exam_standard,
			'exam_org' 		=> $exam_org,
			'post_level' 	=> $post_level
			));
		redirect('online_exam','refresh');
	}

	public function get_exam_data()
	{
		$user = $this->auth->user();

		
		$subscription = $this->subscription_model->getSubscriptionByStudent($user->user_ID);

		$subscription_question_pool = unserialize($subscription->question_pool);

		$exam_question_pool = $this->_createExamQuestionPool($subscription_question_pool);

		$question_pallete = $this->online_exam_model->createQuestionPallete($exam_question_pool);

		$questions = $this->online_exam_model->getQuestionsFromDB($exam_question_pool);

		$answers = $this->online_exam_model->getAnswersFromDB($question_pallete);

		$paragraphs = $this->online_exam_model->getParagraphsFromDB($question_pallete);

		$subjects = $this->online_exam_model->getSubjects();

		$data = array(
			'user' => array(
				'name'			=> $user->f_name." ".$user->l_name,
				'username'		=> $user->username,
				'profile_img'	=> $user->profile_img,
			),
			'question_pallete'	=> $question_pallete,
			'questions' 		=> $questions,
			'answers' 			=> $answers,
			'paragraphs' 		=> $paragraphs,
			'subjects' 			=> $subjects
		);
		echo json_encode($data);
		exit();
	}

	protected function _createExamQuestionPool($subscription_question_pool)
	{
		$subscription_question_pool = $subscription_question_pool[$this->session->userdata('ongoing_exam_config')['exam_standard']];
		
		$ongoing_exam_config = $this->session->userdata('ongoing_exam_config');

		$exam_config = $this->db->get_where('exam_config', array(
													'exam_standard_ID' 	=> $ongoing_exam_config['exam_standard'],
													'exam_org_ID' 		=> $ongoing_exam_config['exam_org'],
													'post_level_ID' 	=> $ongoing_exam_config['post_level']
													))->row();
		$exam_subject_details = unserialize($exam_config->subjects);
		
		$exam_question_pool = array();

		foreach($exam_subject_details as $subject => $nos_ques){
			$exam_question_pool[$subject] = array();

			$subject_question_pool = explode(',',$subscription_question_pool[$subject]);

			$subject_question_keys = array_rand( $subject_question_pool, $nos_ques );

			foreach($subject_question_keys as $key){
				$exam_question_pool[$subject][] = $subject_question_pool[$key];
			}
		}

		return $exam_question_pool;
	}


}