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

/**
* Questions and Answers
*/
class Questions_Answers extends CI_Controller
{
	
	function __construct()
	{
		parent::__construct();

		$this->data['page_name'] = "Questions and Answers";

		/**
		 * Loading Models
		 */
		$this->load->model('questions_model');
		$this->load->model('question_resources_model');
		$this->load->model('answers_model');
		$this->load->model('exam_standard_model');
		$this->load->model('exam_org_model');
		$this->load->model('post_level_model');
		$this->load->model('subject_model');

		$this->data['exam_standards']	= $this->exam_standard_model->get();
		$this->data['ques_levels'] 		= $this->questions_model->getQuesLevel();
		$this->data['subjects'] 		= $this->subject_model->get();
		$this->data['paragraphs'] = $this->question_resources_model->get();
	}

	public function index()
	{
		if($this->session->has_userdata('save_and_new_options')){
			$this->session->unset_userdata('save_and_new_options');
	    }
	    $this->data['exam_orgs'] = $this->exam_org_model->get();
	    $this->data['post_levels'] = $this->post_level_model->get();

		$this->data['questions_answers_data'] = $this->getQuestionsAnswersData();

		$this->load->view('questions_answers/index', $this->data);
	}

	public function create()
	{

		$this->form_validation->set_rules(array(
            array(
                'field' => 'exam_standard',
                'label' => 'Exam Standard',
                'rules' => 'required',
                'errors' => array(
                        'required' => 'Please select an %s.',
                ),
            ),
            array(
            	'field'	=> 'exam_org',
            	'label' => 'Exam Organization',
            	'rules' => 'required',
                'errors' => array(
                        'required' => 'Please select an %s.',
                ),
            ),
            array(
            	'field'	=> 'ques_level',
            	'label' => 'Question Level',
            	'rules' => 'required',
                'errors' => array(
                        'required' => 'Please select a %s.',
                ),
            ),
            array(
            	'field'	=> 'subject',
            	'label' => 'Subject',
            	'rules' => 'required',
                'errors' => array(
                        'required' => 'Please select a %s.',
                ),
            ),
            array(
            	'field'	=> 'ques_content_en',
            	'label' => 'Question Content',
            	'rules' => 'required',
                'errors' => array(
                        'required' => 'Please provide a %s.',
                ),
            ),
            array(
            	'field'	=> 'correct_answer',
            	'label' => 'Correct Answer',
            	'rules' => 'required',
                'errors' => array(
                        'required' => 'Please select a %s.',
                ),
            ),
            array(
            	'field'	=> 'marks',
            	'label' => 'Marks',
            	'rules' => 'required|numeric',
                'errors' => array(
                        'required' 	=> 'Please enter %s for the Question.',
                        'numeric' 	=> '%s must be a numeric value.',
                ),
            ),

        ));

        if($this->form_validation->run()==TRUE) {

        	if($_POST['save_and_new']){
        		//save selected options in session
        		$this->session->set_userdata('save_and_new_options', array(
        			'exam_standard' => $this->input->post('exam_standard'),
        			'exam_org' 		=> $this->input->post('exam_org'),
        			'post_level' 	=> $this->input->post('post_level'),
        			'ques_level'	=> $this->input->post('ques_level'),
        			'subject'		=> $this->input->post('subject')
        		));
	        }

	        //continue with saving the data and redirect to all questions
	        $paragraph_id = NULL;

	        // if has paragraph insert paragraph
	        if($this->input->post('with_paragraph') !== NULL && $this->input->post('with_paragraph') == '1') {
	    		$paragraph_id = $this->question_resources_model->insert();
	        	
		        if (!$paragraph_id){
		        	set_alert('error','Error while updating Question.');
		        	$this->redirectBack();
			    }
			}
			
		    if($this->input->post('with_paragraph') !== NULL && $this->input->post('with_paragraph') == '2') {
		    	$paragraph_id = $this->input->post('paragraph');
		    }

	        // insert question
	        $question_id = $this->questions_model->insert($paragraph_id);

	        if(!$question_id){
	        	set_alert('error','Error while adding new Question.');
	        	$this->redirectBack();
	        }

	        // insert answer
	        if( $this->answers_model->insert($question_id) ){
	        	set_alert('success','Question was added successfully');
	        	$this->redirectBack();
	        } else {
	        	set_alert('error','Error while adding new Question.');
	        	$this->redirectBack();
	        }
	        	
        }


        if( $this->session->has_userdata('save_and_new_options') ){

        	$this->data['exam_orgs'] 	= $this->exam_org_model->get_where_exam_standard( $this->session->userdata('save_and_new_options')['exam_standard'] );
        	$this->data['post_levels'] 	= $this->post_level_model->get_where_exam_org( $this->session->userdata('save_and_new_options')['exam_org'] );

        }   

		$this->data['with_paragraph'] = 0;
		$this->load->view('questions_answers/create_edit_form',$this->data);
	}

	public function edit()
	{
		$this->data['form_title'] = 'EDIT QUESTION AND ANSWERS';
		$this->data['with_paragraph'] = 0;

		$question_id = ($this->session->flashdata('edit_id') != NULL)? $this->session->flashdata('edit_id'):$this->input->post('edit_id'); 

		$this->data['question'] = $this->questions_model->get($question_id);
		$this->data['answers'] = $this->answers_model->get_answers_of_question($question_id);
		$this->data['paragraphs'] = $this->question_resources_model->get();
		if($this->data['question']->paragraph_ID != NULL ){
			$this->data['with_paragraph'] = 2;			
		}

		$this->session->set_userdata('save_and_new_options', array(
			'exam_standard' => $this->data['question']->exam_standard_ID,
        	'exam_org' 		=> $this->data['question']->exam_org_ID,
        	'post_level' 	=> $this->data['question']->post_level_ID,
        	'ques_level'	=> $this->data['question']->question_level,
        	'subject'		=> $this->data['question']->subject_ID
       	));		
		
		$this->data['exam_orgs'] 	= $this->exam_org_model->get_where_exam_standard( $this->session->userdata('save_and_new_options')['exam_standard'] );
        $this->data['post_levels'] 	= $this->post_level_model->get_where_exam_org( $this->session->userdata('save_and_new_options')['exam_org'] );

        $this->load->view('questions_answers/create_edit_form',$this->data);
	}

	public function update()
	{
		if($_POST['save_and_new']){
        		//save selected options in session
        		$this->session->set_userdata('save_and_new_options', array(
        			'exam_standard' => $this->input->post('exam_standard'),
        			'exam_org' 		=> $this->input->post('exam_org'),
        			'post_level' 	=> $this->input->post('post_level'),
        			'ques_level'	=> $this->input->post('ques_level'),
        			'subject'		=> $this->input->post('subject')
        		));
	    }

	    //continue with saving the data and redirect to all questions
	    $paragraph_id = NULL;

	    // if has paragraph insert paragraph
	    if($this->input->post('with_paragraph') !== NULL && $this->input->post('with_paragraph') == '1'){
	    	$paragraph_id = $this->question_resources_model->insert();
	        	
	        if (!$paragraph_id){
	        	set_alert('error','Error while updating Question.');
	        	$this->redirectBack();
	        }
	    }

	    if($this->input->post('with_paragraph') !== NULL && $this->input->post('with_paragraph') == '2') {
	    	$paragraph_id = $this->input->post('paragraph');
	    }

	    // insert question
	    $question_id = $this->questions_model->update($paragraph_id);

	    if(!$question_id){
	       	set_alert('error','Error while updating Question.');
	       	$this->redirectBack();
	    }

	    // insert answer
	    if( $this->answers_model->update($this->input->post('question_id')) ){
	       	set_alert('success','Question was updated successfully');
	       	$this->redirectBack();
	    } else {
	     	set_alert('error','Error while updating Question.');
	       	$this->redirectBack();
	    }
	}

	public function delete()
	{
		if($this->answers_model->delete($this->input->post('delete_id'))){
	    	if($this->questions_model->delete($this->input->post('delete_id'))){
	    			set_alert('success','Question Deleted Successfully.');
	    	} else {
	    		set_alert('error','Error while deleting Question.');
	    	}
	    } else {
	    	set_alert('error','Error while deleting Question.');
	    }
	    
	    redirect('questions_answers');	
	}

	public function edit_paragraph($paragraph_id = NULL, $question_id = NULL)
	{
		if($_POST){
			if($this->question_resources_model->update($this->input->post('paragraph_id'))){
				set_alert('success','Paragraph updated Successfully.');
			} else {
				set_alert('error','Error while updating Paragraph.');
			}

			if($this->input->post('question_id') != NULL){
				$this->session->set_flashdata('edit_id', $this->input->post('question_id'));
				redirect('questions_answers/edit');
			} else {
				redirect('questions_answers/create');
			}

		}

		$this->data['title'] = 'Edit Paragraph';
		$this->data['paragraph'] = $this->question_resources_model->get($paragraph_id);

		if($question_id !== NULL) {
			$this->data['question_id'] = $question_id;
		}

		$this->load->view('questions_answers/edit_paragraph',$this->data);
	}


	protected function getQuestionsAnswersData()
	{
		$questions_answers_data 	= array();
		$all_questions 				= $this->questions_model->get();
		$all_answers 				= $this->answers_model->get();

		foreach ($all_questions as $question) {
			$answers = array();
			$correct_answer = "";
			$paragraph = '';
			foreach($all_answers as $answer){
				if($answer->question_ID == $question->question_ID){
					array_push($answers, $answer);

					if($answer->correct_answer==1){
						$correct_answer = $answer;
					}
				}
			}

			foreach($this->data['paragraphs'] as $para){
				if($question->paragraph_ID == $para->question_resource_ID) {
					$paragraph = $para;
				}
			}

			array_push($questions_answers_data,array(
				'question'			=> $question,
				'answers'			=> $answers,
				'correct_answer'	=> $correct_answer,
				'paragraph'			=> $paragraph,
			));
		}
		return $questions_answers_data;

	}

	protected function redirectBack()
	{
		if(isset($_POST['save']) && $_POST['save']){
			if($this->session->has_userdata('save_and_new_options')) {
	        	$this->session->unset_userdata('save_and_new_options');
	        }
	        redirect('questions_answers');
	    } else {
	    	redirect('questions_answers/create');
		}
	}
}
