GIF89a; CRX
KBHT HEHE
Server IP : 172.26.0.195  /  Your IP : 3.149.237.231
Web Server : Apache
System : Linux 43-205-77-33.cprapid.com 3.10.0-1160.119.1.el7.tuxcare.els2.x86_64 #1 SMP Mon Jul 15 12:09:18 UTC 2024 x86_64
User : jnclnmuac ( 1026)
PHP Version : 8.0.30
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON
Directory (0755) :  /home/jnclnmuac/public_html/web/../web/../cas/application/controllers/admin/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/jnclnmuac/public_html/web/../web/../cas/application/controllers/admin/TasksAndQuizzes.php
<?php

/**
 * Controller For Handling All Requests Related To Quizzes & Assignments
 *
 * @author Ankit Srivastava
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class TasksAndQuizzes extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('admin/TaskAndQuizManagement');
        $this->load->model('admin/CourseManagement');
        $this->load->model('admin/SessionManagement');
        $this->load->model('admin/SubjectManagement');
        $this->load->model('admin/StudentManagement');
    }

    public function topics() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData["topics"] = $this->TaskAndQuizManagement->getAllSubjectTopics()->result();
            $this->load->view("admin/quizzes/topics", $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createTopic() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $this->load->view('admin/quizzes/createTopic', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewTopic() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select A Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Subject Topic Can Not Be Blank.'));
            $queryByTopicName = $this->TaskAndQuizManagement->getTopicInfoByName(trim($this->input->post('subjectTopic')));
            $topicInfoByName = $queryByTopicName->result();
            if ($this->form_validation->run() == FALSE) {
                $this->createTopic();
            } else if (sizeof($topicInfoByName)) {
                $this->session->set_flashdata('errorMessage', "A Topic With This Name (" . trim($this->input->post('subjectTopic')) . ") Already Exits. Please Choose A Different Topic Name.");
                $this->createTopic();
            } else {
                $newTopicInfo = array(
                    'stm_name' => addslashes(trim($this->input->post('subjectTopic'))),
                    'stm_description' => addslashes(trim($this->input->post('subjectTopicDesc'))),
                    'sm_id' => $this->input->post('subject'),
                    'stm_added_on' => date("Y-m-d H:i:s"),
                    'stm_added_by' => $this->session->userdata("adminData")["smember_id"],
                    'stm_updated_on' => date("Y-m-d H:i:s"),
                    'stm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                if ($this->TaskAndQuizManagement->createNewTopic($newTopicInfo)) {
                    $this->session->set_flashdata('successMessage', 'Topic Created Successfully.');
                    redirect("admin/TasksAndQuizzes/topics");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Creating Topic. Try Later.');
                    redirect("admin/TasksAndQuizzes/topics");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function saveNewTopicAndReturnForDropDown() {
        if ($this->sessionvalidator->isLoggedIn()) {
            if (trim($this->input->post('subjectTopicModal')) == "") {
                $responseData = array(
                    'csrfName' => $this->security->get_csrf_token_name(),
                    'csrfHash' => $this->security->get_csrf_hash(),
                    'st_id' => -1,
                    'st_name' => ""
                );
                echo json_encode($responseData);
            } else if (sizeof($this->TaskAndQuizManagement->getTopicInfoByName(trim($this->input->post('subjectTopicModal')))->result())) {
                $responseData = array(
                    'csrfName' => $this->security->get_csrf_token_name(),
                    'csrfHash' => $this->security->get_csrf_hash(),
                    'stm_id' => 0,
                    'stm_name' => ""
                );
                echo json_encode($responseData);
            } else {
                $newTopicInfo = array(
                    'sm_id' => $this->input->post('subjectModal'),
                    'stm_name' => addslashes(trim($this->input->post('subjectTopicModal'))),
                    'stm_description' => addslashes(trim($this->input->post('subjectTopicModalDesc'))),
                    'stm_added_on' => date("Y-m-d H:i:s"),
                    'stm_added_by' => $this->session->userdata("adminData")["smember_id"],
                    'stm_updated_on' => date("Y-m-d H:i:s"),
                    'stm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $stm_id = $this->TaskAndQuizManagement->createNewTopic($newTopicInfo);
                $topic_info = $this->TaskAndQuizManagement->getTopicInfoBy($stm_id)->result()[0];
                $responseData = array(
                    'csrfName' => $this->security->get_csrf_token_name(),
                    'csrfHash' => $this->security->get_csrf_hash(),
                    'stm_id' => $topic_info->stm_id,
                    'stm_name' => stripslashes($topic_info->stm_name)
                );
                echo json_encode($responseData);
            }
        } else {
            redirect("admin/");
        }
    }

    public function editTopic($topic_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $viewData['topicInfo'] = $this->TaskAndQuizManagement->getTopicInfoBy($topic_id)->result()[0];
            $this->load->view('admin/quizzes/editTopic', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateTopic() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $stm_id = $this->input->post('stm_id');
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select A Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Subject Topic Can Not Be Blank.'));
            if ($this->form_validation->run() == FALSE) {
                $this->editTopic($stm_id);
            } else if (!$this->TaskAndQuizManagement->isTopicNameSafeUpdate($stm_id, trim($this->input->post('subjectTopic')))) {
                $this->session->set_flashdata('errorMessage', "A Topic With This Name (" . trim($this->input->post('subjectTopic')) . ") Already Exits. Please Choose A Different Name.");
                $this->editTopic($stm_id);
            } else {
                $topicUpdateInfo = array(
                    'stm_id' => $stm_id,
                    'stm_name' => addslashes(trim($this->input->post('subjectTopic'))),
                    'stm_description' => addslashes(trim($this->input->post('subjectTopicDesc'))),
                    'sm_id' => $this->input->post('subject'),
                    'stm_updated_on' => date("Y-m-d H:i:s"),
                    'stm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                if ($this->TaskAndQuizManagement->updateTopicInfo($topicUpdateInfo)) {
                    $this->session->set_flashdata('successMessage', 'Topic Updated Successfully.');
                    redirect("admin/TasksAndQuizzes/topics");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Updating Topic. Try Later.');
                    redirect("admin/TasksAndQuizzes/topics");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function toggleTopicStatus($topic_id, $toUpdateStatus) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $topicUpdateData = array(
                'stm_id' => $topic_id,
                'stm_updated_on' => date("Y-m-d H:i:s"),
                'stm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'stm_active_status' => $toUpdateStatus
            );
            if ($this->TaskAndQuizManagement->updateTopicInfo($topicUpdateData)) {
                $this->session->set_flashdata('successMessage', 'Topic Status Updated Successfully.');
                redirect("admin/TasksAndQuizzes/topics");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Updating Topic Status. Try Later.');
                redirect("admin/TasksAndQuizzes/topics");
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteTopic($topic_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $topicDeleteData = array(
                'stm_id' => $topic_id,
                'stm_updated_on' => date("Y-m-d H:i:s"),
                'stm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'stm_delete_status' => 'T'
            );
            if ($this->TaskAndQuizManagement->updateTopicInfo($topicDeleteData)) {
                $this->session->set_flashdata('successMessage', 'Topic Deleted Successfully.');
                redirect("admin/TasksAndQuizzes/topics");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting Topic. Try Later.');
                redirect("admin/TasksAndQuizzes/topics");
            }
        } else {
            redirect("admin/");
        }
    }

    public function undoDeleteTopic($topic_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $topicDeleteData = array(
                'stm_id' => $topic_id,
                'stm_updated_on' => date("Y-m-d H:i:s"),
                'stm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'stm_delete_status' => 'F'
            );
            if ($this->TaskAndQuizManagement->updateTopicInfo($topicDeleteData)) {
                $this->session->set_flashdata('successMessage', 'Topic Recovered Successfully.');
                redirect("admin/TasksAndQuizzes/topics");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Recovering Topic. Try Later.');
                redirect("admin/TasksAndQuizzes/topics");
            }
        } else {
            redirect("admin/");
        }
    }

    public function getTopicsForDropdownBySubject() {
        $subject_id = $_POST['subject_id'];
        $query = $this->TaskAndQuizManagement->getAllNonDeletedActiveSubjectTopicsBy($subject_id);
        $topics = $query->result();
        if (sizeof($topics)) {
            $options = "";
            for ($i = 0; $i < (sizeof($topics)); $i++) {
                $options .= "<option value=" . $topics[$i]->stm_id . ">" . stripslashes($topics[$i]->stm_name) . "</option>";
            }
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'topics' => $options
            );
        } else {
            $options = "<option value='' disabled>No Topics Available</option>";
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'topics' => $options
            );
        }
        echo json_encode($responseData);
    }

    /* Request Handlers For Subjective Questions */

    public function subjectiveQuestions() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['subjectiveGenQuestion'] = $this->TaskAndQuizManagement->getAllGeneralQuestionsOfUser($this->session->userdata("adminData")['smember_id'], "S")->result();
            $viewData['subjectiveCompQuestion'] = $this->TaskAndQuizManagement->getAllGroupQuestionsOfUser($this->session->userdata("adminData")['smember_id'], "S")->result();
            if ($this->session->flashdata('genQuestionTab') == NULL && $this->session->flashdata('compQuestionTab') == NULL) {
                $this->session->set_flashdata('genQuestionTab', 'active');
            }
            $this->load->view("admin/quizzes/subjectiveQuestions", $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createSubjectiveGeneralQuestions() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $this->load->view('admin/quizzes/addSubjectiveGeneralQues', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewSubjectiveGeneralQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select Any Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Please Select Any Topic.'));
            if ($this->form_validation->run() == FALSE) {
                $this->createSubjectiveGeneralQuestions();
            } else {
                $questions = $this->input->post("questions");
                $questionMarks = $this->input->post("marks");
                $qestionsInfo = array();
                if (sizeof($questions) == 1) {
                    if (!empty($_FILES['imageFile']['name'])) {
                        $genSubQuesImg['upload_path'] = './assets/admin/uploads/questionBank/';
                        $genSubQuesImg['allowed_types'] = 'jpeg|jpg|png';
                        $genSubQuesImg['max_size'] = '500';
                        $genSubQuesImg['file_ext_tolower'] = TRUE;
                        $genSubQuesImg['encrypt_name'] = TRUE;
                        $this->load->library('upload', $genSubQuesImg);
                        if (!$this->upload->do_upload('imageFile')) {
                            $this->session->set_flashdata('errorMessage', "Question Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                            $this->createSubjectiveGeneralQuestions();
                        } else {
                            array_push($qestionsInfo, array(
                                'qb_question' => addslashes($questions[0]),
                                'qb_marks' => addslashes($questionMarks[0]),
                                'qb_image' => "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'],
                                'stm_id' => trim($this->input->post('subjectTopic')),
                                'qb_ques_type_flag' => "S",
                                'qb_added_on' => date("Y-m-d H:i:s"),
                                'qb_added_by' => $this->session->userdata("adminData")["smember_id"],
                                'qb_updated_on' => date("Y-m-d H:i:s"),
                                'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                            ));
                        }
                    } else {
                        array_push($qestionsInfo, array(
                            'qb_question' => addslashes($questions[0]),
                            'qb_marks' => addslashes($questionMarks[0]),
                            'stm_id' => trim($this->input->post('subjectTopic')),
                            'qb_ques_type_flag' => "S",
                            'qb_added_on' => date("Y-m-d H:i:s"),
                            'qb_added_by' => $this->session->userdata("adminData")["smember_id"],
                            'qb_updated_on' => date("Y-m-d H:i:s"),
                            'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        ));
                    }
                } else {
                    for ($i = 0; $i < sizeof($questions); $i++) {
                        array_push($qestionsInfo, array(
                            'qb_question' => addslashes($questions[$i]),
                            'qb_marks' => addslashes($questionMarks[$i]),
                            'stm_id' => trim($this->input->post('subjectTopic')),
                            'qb_ques_type_flag' => "S",
                            'qb_added_on' => date("Y-m-d H:i:s"),
                            'qb_added_by' => $this->session->userdata("adminData")["smember_id"],
                            'qb_updated_on' => date("Y-m-d H:i:s"),
                            'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        ));
                    }
                }
                $this->session->set_flashdata('genQuestionTab', 'active');
                $this->session->set_flashdata('compQuestionTab', '');
                if ($this->TaskAndQuizManagement->createNewGeneralQuestionsMulti($qestionsInfo)) {
                    $this->session->set_flashdata('successMessage', 'Subjective General Questions Saved Successfully.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Saving Subjective General Questiono. Try Later.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editGeneralQuestions($qb_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $viewData['questionInfo'] = $this->TaskAndQuizManagement->getGeneralQuestionInfoBy($qb_id)->result()[0];
            $this->load->view('admin/quizzes/editSubjectiveGeneralQues', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateSubjectiveGeneralQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $qb_id = $this->input->post("qb_id");
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select Any Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Please Select Any Topic.'));
            $questionImageFileName = "";
            if (trim($this->input->post('qb_image')) != "") {
                $questionImageFileName = substr($this->input->post('qb_image'), strripos($this->input->post('qb_image'), "/") + 1);
            }
            if ($this->form_validation->run() == FALSE) {
                $this->editSubjectiveGeneralQuestions($qb_id);
            } else {
                $qestionsInfo = array();
                if (!empty($_FILES['imageFile']['name'])) {
                    $genSubQuesImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $genSubQuesImg['allowed_types'] = 'jpeg|jpg|png';
                    $genSubQuesImg['max_size'] = '500';
                    $genSubQuesImg['file_ext_tolower'] = TRUE;
                    $genSubQuesImg['encrypt_name'] = TRUE;
                    $this->load->library('upload', $genSubQuesImg);
                    if (!$this->upload->do_upload('imageFile')) {
                        $this->session->set_flashdata('errorMessage', "Question Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createSubjectiveGeneralQuestions();
                    } else {
                        $qestionsInfo = array(
                            'qb_id' => $qb_id,
                            'qb_question' => addslashes(trim($this->input->post("question"))),
                            'qb_marks' => addslashes(trim($this->input->post("mark"))),
                            'qb_image' => "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'],
                            'stm_id' => trim($this->input->post('subjectTopic')),
                            'qb_updated_on' => date("Y-m-d H:i:s"),
                            'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    }
                } else {
                    if ($this->input->post("removeImage") != NULL) {
                        $qestionsInfo = array(
                            'qb_id' => $qb_id,
                            'qb_question' => addslashes(trim($this->input->post("question"))),
                            'qb_image' => NULL,
                            'qb_marks' => addslashes(trim($this->input->post("mark"))),
                            'stm_id' => trim($this->input->post('subjectTopic')),
                            'qb_updated_on' => date("Y-m-d H:i:s"),
                            'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    } else {
                        $qestionsInfo = array(
                            'qb_id' => $qb_id,
                            'qb_question' => addslashes(trim($this->input->post("question"))),
                            'qb_marks' => addslashes(trim($this->input->post("mark"))),
                            'stm_id' => trim($this->input->post('subjectTopic')),
                            'qb_updated_on' => date("Y-m-d H:i:s"),
                            'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    }
                }
                $this->session->set_flashdata('genQuestionTab', 'active');
                $this->session->set_flashdata('compQuestionTab', '');
                if ($this->TaskAndQuizManagement->updateGenralQuestionInfo($qestionsInfo)) {
                    if (($questionImageFileName != "" && (!empty($_FILES['imageFile']['name'])) ) || ($this->input->post("removeImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $questionImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $questionImageFileName);
                        }
                    }
                    $this->session->set_flashdata('successMessage', 'Subjective General Questions Updated Successfully.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Updating Subjective General Questiono. Try Later.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteGeneralQuestion($qb_id, $question_type) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $questionDeleteData = array(
                'qb_id' => $qb_id,
                'qb_updated_on' => date("Y-m-d H:i:s"),
                'qb_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'qb_delete_status' => 'T'
            );
            $this->session->set_flashdata('genQuestionTab', 'active');
            $this->session->set_flashdata('compQuestionTab', '');
            if ($this->TaskAndQuizManagement->updateGenralQuestionInfo($questionDeleteData)) {
                $this->session->set_flashdata('successMessage', 'Question Deleted Successfully.');
                if ($question_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveQuestions");
                }
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting Question. Try Later.');
                if ($question_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveQuestions");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function getSubjectiveGeneralQuestionsBySubjectAndTopic() {
        $subjectId = $_POST['subject_id'];
        $topicIds = ($_POST['topic_id'] == "") ? array() : $_POST['topic_id'];
        $smemeber_id = $_POST['smemeber_id'];
        $gen_question_info = $this->TaskAndQuizManagement->getAllGeneralQuestionsOfUser($smemeber_id, "S", $topicIds, $subjectId)->result();
        $genQuestionList = array();
        if (sizeof($gen_question_info)) {
            for ($i = 0; $i < sizeof($gen_question_info); $i++) {
                $thisQuestionInfo = array(
                    'sqb_id' => $gen_question_info[$i]->qb_id,
                    'sqb_question' => stripslashes($gen_question_info[$i]->qb_question),
                    'sqb_image' => ($gen_question_info[$i]->qb_image == NULL || $gen_question_info[$i]->qb_image == "") ? "" : "<br><img src='" . base_url($gen_question_info[$i]->qb_image) . "' width='50%' height='50%'/>",
                    'sqb_marks' => stripslashes($gen_question_info[$i]->qb_marks)
                );
                array_push($genQuestionList, $thisQuestionInfo);
            }
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'available_question' => sizeof($gen_question_info),
                'question_list' => $genQuestionList,
                'message' => 'General Questions Available'
            );
        } else {
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'available_question' => 0,
                'question_list' => $genQuestionList,
                'message' => 'No General Questions Available Under Selected Subject/Topic.'
            );
        }
        echo json_encode($responseData);
    }

    /* Request Handlers For Subjective Comprehensive Questions */

    public function createSubjectiveComprehensiveQuestions() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $this->load->view('admin/quizzes/addSubjectiveComprehensiveQues', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewSubjectiveGroupQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select Any Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Please Select Any Topic.'));
            $this->form_validation->set_rules('questionDesc', 'Question Description', 'trim|required|max_length[1000]', array('required' => 'Question Description Can Not Be Blank.'));
            if ($this->form_validation->run() == FALSE) {
                $this->createSubjectiveComprehensiveQuestions();
            } else {
                $subQuestions = $this->input->post("questions");
                $subQuestionMarks = $this->input->post("marks");
                $newSubjectiveGroupQuestionInfo = array();
                if (!empty($_FILES['imageFile']['name'])) {
                    $comphSubQuesImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $comphSubQuesImg['allowed_types'] = 'jpeg|jpg|png';
                    $comphSubQuesImg['max_size'] = '500';
                    $comphSubQuesImg['file_ext_tolower'] = TRUE;
                    $comphSubQuesImg['encrypt_name'] = TRUE;
                    $this->load->library('upload', $comphSubQuesImg);
                    if (!$this->upload->do_upload('imageFile')) {
                        $this->session->set_flashdata('errorMessage', "Question Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createSubjectiveComprehensiveQuestions();
                    } else {
                        $newSubjectiveGroupQuestionInfo = array(
                            'qg_question' => addslashes(trim($this->input->post('questionDesc'))),
                            'qg_image' => "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'],
                            'qg_marks' => $this->input->post('totalMarks'),
                            'qg_added_on' => date("Y-m-d H:i:s"),
                            'qg_added_by' => $this->session->userdata("adminData")["smember_id"],
                            'qg_updated_on' => date("Y-m-d H:i:s"),
                            'qg_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    }
                } else {
                    $newSubjectiveGroupQuestionInfo = array(
                        'qg_question' => addslashes(trim($this->input->post('questionDesc'))),
                        'qg_marks' => $this->input->post('totalMarks'),
                        'qg_added_on' => date("Y-m-d H:i:s"),
                        'qg_added_by' => $this->session->userdata("adminData")["smember_id"],
                        'qg_updated_on' => date("Y-m-d H:i:s"),
                        'qg_updated_by' => $this->session->userdata("adminData")["smember_id"]
                    );
                }
                $this->db->trans_start();
                $group_id = $this->TaskAndQuizManagement->createNewQuestionGroup($newSubjectiveGroupQuestionInfo);
                $subQuestionsInfo = array();
                for ($i = 0; $i < sizeof($subQuestions); $i++) {
                    array_push($subQuestionsInfo, array(
                        'qb_question' => addslashes($subQuestions[$i]),
                        'qb_marks' => addslashes($subQuestionMarks[$i]),
                        'qg_id' => $group_id,
                        'stm_id' => trim($this->input->post('subjectTopic')),
                        'qb_ques_type_flag' => "S",
                        'qb_added_on' => date("Y-m-d H:i:s"),
                        'qb_added_by' => $this->session->userdata("adminData")["smember_id"],
                        'qb_updated_on' => date("Y-m-d H:i:s"),
                        'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                    ));
                }
                $this->session->set_flashdata('genQuestionTab', '');
                $this->session->set_flashdata('compQuestionTab', 'active');
                if ($this->TaskAndQuizManagement->createNewGeneralQuestionsMulti($subQuestionsInfo)) {
                    $this->db->trans_complete();
                    $this->session->set_flashdata('successMessage', 'Subjective Group Question Created Successfully.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Creating Subjective Group Questions. Try Later.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editSubjectiveComprehensiveQuestions($qg_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $viewData['questionInfo'] = $this->TaskAndQuizManagement->getGroupQuestionInfoBy($qg_id)->result();
            $this->load->view('admin/quizzes/editSubjectiveComprehensiveQues', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateSubjectiveGroupQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $qg_id = $this->input->post("qg_id");
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select Any Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Please Select Any Topic.'));
            $this->form_validation->set_rules('questionDesc', 'Question Description', 'trim|required|max_length[1000]', array('required' => 'Question Description Can Not Be Blank.'));
            $questionImageFileName = "";
            if (trim($this->input->post('qg_image')) != "") {
                $questionImageFileName = substr($this->input->post('qg_image'), strripos($this->input->post('qg_image'), "/") + 1);
            }
            if ($this->form_validation->run() == FALSE) {
                $this->editSubjectiveComprehensiveQuestions($qg_id);
            } else {
                $subQuestions = $this->input->post("questions");
                $subQuestionMarks = $this->input->post("marks");
                if (!empty($_FILES['imageFile']['name'])) {
                    $comphSubQuesImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $comphSubQuesImg['allowed_types'] = 'jpeg|jpg|png';
                    $comphSubQuesImg['max_size'] = '500';
                    $comphSubQuesImg['file_ext_tolower'] = TRUE;
                    $comphSubQuesImg['encrypt_name'] = TRUE;
                    $this->load->library('upload', $comphSubQuesImg);
                    if (!$this->upload->do_upload('imageFile')) {
                        $this->session->set_flashdata('errorMessage', "Question Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->editSubjectiveComprehensiveQuestions($qg_id);
                    } else {
                        $subjectiveGroupQuestionInfo = array(
                            'qg_id' => $qg_id,
                            'qg_question' => addslashes(trim($this->input->post('questionDesc'))),
                            'qg_image' => "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'],
                            'qg_marks' => $this->input->post('totalMarks'),
                            'qg_updated_on' => date("Y-m-d H:i:s"),
                            'qg_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    }
                } else {
                    if ($this->input->post("removeImage") != NULL) {
                        $subjectiveGroupQuestionInfo = array(
                            'qg_id' => $qg_id,
                            'qg_question' => addslashes(trim($this->input->post('questionDesc'))),
                            'qg_image' => NULL,
                            'qg_marks' => $this->input->post('totalMarks'),
                            'qg_updated_on' => date("Y-m-d H:i:s"),
                            'qg_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    } else {
                        $subjectiveGroupQuestionInfo = array(
                            'qg_id' => $qg_id,
                            'qg_question' => addslashes(trim($this->input->post('questionDesc'))),
                            'qg_marks' => $this->input->post('totalMarks'),
                            'qg_updated_on' => date("Y-m-d H:i:s"),
                            'qg_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                    }
                }
                $this->db->trans_start();
                $this->TaskAndQuizManagement->updateGroupQuestionInfo($subjectiveGroupQuestionInfo);
                $subQuestionsInfo = array();
                for ($i = 0; $i < sizeof($subQuestions); $i++) {
                    array_push($subQuestionsInfo, array(
                        'qb_question' => addslashes($subQuestions[$i]),
                        'qb_marks' => addslashes($subQuestionMarks[$i]),
                        'qg_id' => $qg_id,
                        'stm_id' => trim($this->input->post('subjectTopic')),
                        'qb_ques_type_flag' => "S",
                        'qb_added_on' => date("Y-m-d H:i:s"),
                        'qb_added_by' => $this->session->userdata("adminData")["smember_id"],
                        'qb_updated_on' => date("Y-m-d H:i:s"),
                        'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                    ));
                }
                $this->TaskAndQuizManagement->deleteQuestionsBy($qg_id);
                if ($this->TaskAndQuizManagement->createNewGeneralQuestionsMulti($subQuestionsInfo)) {
                    $this->db->trans_complete();
                    if (($questionImageFileName != "" && (!empty($_FILES['imageFile']['name'])) ) || ($this->input->post("removeImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $questionImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $questionImageFileName);
                        }
                    }
                    $this->session->set_flashdata('genQuestionTab', '');
                    $this->session->set_flashdata('compQuestionTab', 'active');
                    $this->session->set_flashdata('successMessage', 'Subjective Group Question Updated Successfully.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Updating Subjective Group Questiono. Try Later.');
                    redirect("admin/TasksAndQuizzes/subjectiveQuestions");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteGroupQuestion($qg_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $groupQuestionDeleteData = array(
                'qg_id' => $qg_id,
                'qg_updated_on' => date("Y-m-d H:i:s"),
                'qg_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'qg_delete_status' => 'T'
            );
            $this->session->set_flashdata('genQuestionTab', '');
            $this->session->set_flashdata('compQuestionTab', 'active');
            if ($this->TaskAndQuizManagement->updateGroupQuestionInfo($groupQuestionDeleteData)) {
                $this->session->set_flashdata('successMessage', 'Group Question Deleted Successfully.');
                redirect("admin/TasksAndQuizzes/subjectiveQuestions");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting Group Question. Try Later.');
                redirect("admin/TasksAndQuizzes/subjectiveQuestions");
            }
        } else {
            redirect("admin/");
        }
    }

    public function getSubjectiveGroupQuestionsBySubjectAndTopic() {
        $subjectId = $_POST['subject_id'];
        $topicIds = ($_POST['topic_id'] == "") ? array() : $_POST['topic_id'];
        $smemeber_id = $_POST['smemeber_id'];
        $group_question_info = $this->TaskAndQuizManagement->getAllGroupQuestionsOfUser($smemeber_id, "S", $topicIds, $subjectId)->result();
        $groupQuestionList = array();
        if (sizeof($group_question_info)) {
            $thisGroupQuestion = "";
            $srno = 0;
            for ($i = 0; $i < sizeof($group_question_info); $i++) {
                $record = $group_question_info[$i];
                $tempGroupQuestion = "";
                $tempGroupMarks = "";
                $tempGroupImage = "";
                $tempSrno = "";
                if ($thisGroupQuestion != $record->qg_question) {
                    $thisGroupQuestion = $record->qg_question;
                    $tempGroupQuestion = $record->qg_question;
                    $tempGroupMarks = $record->qg_marks;
                    $tempGroupImage = ($record->qg_image == NULL || $record->qg_image == "") ? "" : "<br><img src='" . base_url($record->qg_image) . "' width='25%' height='50%'/>";
                    $tempSrno = ++$srno;
                } else {
                    $tempGroupQuestion = "";
                    $tempGroupMarks = "";
                    $tempGroupImage = "";
                    $tempSrno = "";
                }
                $thisQuestionInfo = array(
                    'sqg_id' => $record->qg_id,
                    'srno' => $tempSrno,
                    'sqg_question' => stripslashes($tempGroupQuestion),
                    'sqg_marks' => $tempGroupMarks,
                    'sqg_image' => $tempGroupImage,
                    'sub_questions' => array(
                        'sqb_id' => $record->qb_id,
                        'sqb_question' => stripslashes($record->qb_question),
                        'sqb_marks' => $record->qb_marks
                    )
                );
                array_push($groupQuestionList, $thisQuestionInfo);
            }
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'available_question' => sizeof($groupQuestionList),
                'question_list' => $groupQuestionList,
                'message' => 'Group Questions Available'
            );
        } else {
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'available_question' => 0,
                'question_list' => $groupQuestionList,
                'message' => 'No Group Questions Available Under Selected Subject/Topic.'
            );
        }
        echo json_encode($responseData);
    }

    /* Request Handlers For Objective General Questions */

    public function objectiveQuestions() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['objectiveGenQuestion'] = $this->TaskAndQuizManagement->getAllGeneralQuestionsOfUser($this->session->userdata("adminData")['smember_id'], "O")->result();
            $this->load->view("admin/quizzes/objectiveQuestions", $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createObjectiveQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $this->load->view('admin/quizzes/addObjectiveGeneralQues', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewObjectiveGeneralQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select Any Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Please Select Any Topic.'));
            $this->form_validation->set_rules('question', 'Question', 'trim|required|max_length[1000]', array('required' => 'Question Can Not Be Blank.'));
            $this->form_validation->set_rules('questionMarks', 'Marks', 'trim|required|numeric', array('required' => 'Marks Can Not Be Blank.'));
            $this->form_validation->set_rules('questionNegMarks', 'Negative Marks', 'trim|required|numeric', array('required' => 'Negative Marks Can Not Be Blank.'));
            $this->form_validation->set_rules('correctAnswer', 'Correct Question', 'trim|required', array('required' => 'Please Select Correct Answer Option.'));
            if ($this->form_validation->run() == FALSE) {
                $this->createObjectiveQuestion();
            } else {
                $objectiveGenQestionInfo = array(
                    'qb_question' => addslashes(trim($this->input->post("question"))),
                    'qb_marks' => $this->input->post("questionMarks"),
                    'qb_negative_marks' => $this->input->post("questionNegMarks"),
                    'stm_id' => trim($this->input->post('subjectTopic')),
                    'qb_ques_type_flag' => "O",
                    'qb_opt_a' => addslashes(trim($this->input->post('option_a'))),
                    'qb_opt_b' => addslashes(trim($this->input->post('option_b'))),
                    'qb_opt_c' => addslashes(trim($this->input->post('option_c'))),
                    'qb_opt_d' => addslashes(trim($this->input->post('option_d'))),
                    'qb_correct_opt' => addslashes(trim($this->input->post('correctAnswer'))),
                    'qb_added_on' => date("Y-m-d H:i:s"),
                    'qb_added_by' => $this->session->userdata("adminData")["smember_id"],
                    'qb_updated_on' => date("Y-m-d H:i:s"),
                    'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->load->library('upload');
                if (!empty($_FILES['imageFile']['name'])) {
                    $genObjQuesImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $genObjQuesImg['allowed_types'] = 'jpeg|jpg|png';
                    $genObjQuesImg['max_size'] = '500';
                    $genObjQuesImg['file_ext_tolower'] = TRUE;
                    $genObjQuesImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($genObjQuesImg);
                    if (!$this->upload->do_upload('imageFile')) {
                        $this->session->set_flashdata('errorMessage', "Question Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['qb_image'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                }
                if (!empty($_FILES['option_a_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_a_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'A' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['qb_opt_a_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                }
                if (!empty($_FILES['option_b_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_b_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'B' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['qb_opt_b_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                }
                if (!empty($_FILES['option_c_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_c_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'C' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['qb_opt_c_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                }
                if (!empty($_FILES['option_d_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_d_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'C' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['qb_opt_d_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                }
                if ($this->TaskAndQuizManagement->createNewGeneralQuestion($objectiveGenQestionInfo)) {
                    $this->session->set_flashdata('successMessage', 'Objective Questions Saved Successfully');
                    if ($this->input->post("saveAndMove") !== null) {
                        redirect("admin/TasksAndQuizzes/objectiveQuestions");
                    } else {
                        $this->session->set_flashdata('selectedCourse', $this->input->post("subjectCourse"));
                        $this->session->set_flashdata('selectedSubject', $this->input->post("subject"));
                        $this->session->set_flashdata('selectedTopic', $this->input->post("subjectTopic"));
                        redirect("admin/TasksAndQuizzes/createObjectiveQuestion");
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Saving Objective Question. Try Later.');
                    redirect(current_url());
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editObjectiveGeneralQuestion($qb_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $viewData['questionInfo'] = $this->TaskAndQuizManagement->getGeneralQuestionInfoBy($qb_id)->result()[0];
            $this->load->view('admin/quizzes/editObjectiveGeneralQues', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateObjectiveGeneralQuestion() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $qb_id = $this->input->post("qb_id");
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select Any Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('subjectTopic', 'Subject Topic', 'trim|required', array('required' => 'Please Select Any Topic.'));
            $this->form_validation->set_rules('question', 'Question', 'trim|required|max_length[1000]', array('required' => 'Question Can Not Be Blank.'));
            $this->form_validation->set_rules('questionMarks', 'Marks', 'trim|required|numeric', array('required' => 'Marks Can Not Be Blank.'));
            $this->form_validation->set_rules('questionNegMarks', 'Negative Marks', 'trim|required|numeric', array('required' => 'Negative Marks Can Not Be Blank.'));
            $this->form_validation->set_rules('correctAnswer', 'Correct Question', 'trim|required', array('required' => 'Please Select Correct Answer Option.'));
            $questionImageFileName = "";
            $optionAImageFileName = "";
            $optionBImageFileName = "";
            $optionCImageFileName = "";
            $optionDImageFileName = "";
            if (trim($this->input->post('qb_image')) != "") {
                $questionImageFileName = substr($this->input->post('qb_image'), strripos($this->input->post('qb_image'), "/") + 1);
            }
            if (trim($this->input->post('oqb_opt_a_image')) != "") {
                $optionAImageFileName = substr($this->input->post('oqb_opt_a_image'), strripos($this->input->post('oqb_opt_a_image'), "/") + 1);
            }
            if (trim($this->input->post('oqb_opt_b_image')) != "") {
                $optionBImageFileName = substr($this->input->post('oqb_opt_b_image'), strripos($this->input->post('oqb_opt_b_image'), "/") + 1);
            }
            if (trim($this->input->post('oqb_opt_c_image')) != "") {
                $optionCImageFileName = substr($this->input->post('oqb_opt_c_image'), strripos($this->input->post('oqb_opt_c_image'), "/") + 1);
            }
            if (trim($this->input->post('oqb_opt_d_image')) != "") {
                $optionDImageFileName = substr($this->input->post('oqb_opt_d_image'), strripos($this->input->post('oqb_opt_d_image'), "/") + 1);
            }
            if ($this->form_validation->run() == FALSE) {
                $this->editObjectiveGeneralQuestion($qb_id);
            } else {
                $objectiveGenQestionInfo = array(
                    'qb_id' => $qb_id,
                    'qb_question' => addslashes(trim($this->input->post("question"))),
                    'qb_marks' => $this->input->post("questionMarks"),
                    'qb_negative_marks' => $this->input->post("questionNegMarks"),
                    'stm_id' => trim($this->input->post('subjectTopic')),
                    'qb_opt_a' => addslashes(trim($this->input->post('option_a'))),
                    'qb_opt_b' => addslashes(trim($this->input->post('option_b'))),
                    'qb_opt_c' => addslashes(trim($this->input->post('option_c'))),
                    'qb_opt_d' => addslashes(trim($this->input->post('option_d'))),
                    'qb_correct_opt' => addslashes(trim($this->input->post('correctAnswer'))),
                    'qb_updated_on' => date("Y-m-d H:i:s"),
                    'qb_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->load->library('upload');
                if (!empty($_FILES['imageFile']['name'])) {
                    $genObjQuesImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $genObjQuesImg['allowed_types'] = 'jpeg|jpg|png';
                    $genObjQuesImg['max_size'] = '500';
                    $genObjQuesImg['file_ext_tolower'] = TRUE;
                    $genObjQuesImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($genObjQuesImg);
                    if (!$this->upload->do_upload('imageFile')) {
                        $this->session->set_flashdata('errorMessage', "Question Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['qb_image'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                } else {
                    if ($this->input->post("removeImage") != NULL) {
                        $objectiveGenQestionInfo['qb_image'] = NULL;
                    }
                }

                if (!empty($_FILES['option_a_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_a_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'A' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['oqb_opt_a_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                } else {
                    if ($this->input->post("removeOptAImage") != NULL) {
                        $objectiveGenQestionInfo['oqb_opt_a_img'] = NULL;
                    }
                }
                if (!empty($_FILES['option_b_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_b_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'B' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['oqb_opt_b_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                } else {
                    if ($this->input->post("removeOptBImage") != NULL) {
                        $objectiveGenQestionInfo['oqb_opt_b_img'] = NULL;
                    }
                }
                if (!empty($_FILES['option_c_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_c_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'C' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['oqb_opt_c_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                } else {
                    if ($this->input->post("removeOptCImage") != NULL) {
                        $objectiveGenQestionInfo['oqb_opt_c_img'] = NULL;
                    }
                }
                if (!empty($_FILES['option_d_img']['name'])) {
                    $optionAImg['upload_path'] = './assets/admin/uploads/questionBank/';
                    $optionAImg['allowed_types'] = 'jpeg|jpg|png';
                    $optionAImg['max_size'] = '500';
                    $optionAImg['file_ext_tolower'] = TRUE;
                    $optionAImg['encrypt_name'] = TRUE;
                    $this->upload->initialize($optionAImg);
                    if (!$this->upload->do_upload('option_d_img')) {
                        $this->session->set_flashdata('errorMessage', "Option 'C' Image File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 500 KB Max. & Allowed Extension: Only *.png,*.jpg,*.jpeg.");
                        $this->createObjectiveQuestion();
                    } else {
                        $objectiveGenQestionInfo['oqb_opt_d_img'] = "/assets/admin/uploads/questionBank/" . $this->upload->data()['file_name'];
                    }
                } else {
                    if ($this->input->post("removeOptDImage") != NULL) {
                        $objectiveGenQestionInfo['oqb_opt_d_img'] = NULL;
                    }
                }
                if ($this->TaskAndQuizManagement->updateGenralQuestionInfo($objectiveGenQestionInfo)) {
                    if (($questionImageFileName != "" && (!empty($_FILES['imageFile']['name'])) ) || ($this->input->post("removeImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $questionImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $questionImageFileName);
                        }
                    }
                    if (($optionAImageFileName != "" && (!empty($_FILES['oqb_opt_a_image']['name'])) ) || ($this->input->post("removeOptAImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $optionAImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $optionAImageFileName);
                        }
                    }
                    if (($optionBImageFileName != "" && (!empty($_FILES['oqb_opt_b_image']['name'])) ) || ($this->input->post("removeOptBImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $optionBImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $optionBImageFileName);
                        }
                    }
                    if (($optionCImageFileName != "" && (!empty($_FILES['oqb_opt_c_image']['name'])) ) || ($this->input->post("removeOptCImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $optionCImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $optionCImageFileName);
                        }
                    }
                    if (($optionDImageFileName != "" && (!empty($_FILES['oqb_opt_d_image']['name'])) ) || ($this->input->post("removeOptDImage") != NULL)) {
                        if (file_exists("./assets/admin/uploads/questionBank/" . $optionDImageFileName)) {
                            unlink("./assets/admin/uploads/questionBank/" . $optionDImageFileName);
                        }
                    }
                    $this->session->set_flashdata('successMessage', 'Objective Questions Saved Successfully');
                    redirect("admin/TasksAndQuizzes/objectiveQuestions");
                } else {
                    $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting Model Paper. Try Later.');
                    redirect(current_url());
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function getObjectiveGeneralQuestionsBySubjectAndTopic() {
        $subjectId = $_POST['subject_id'];
        $topicIds = ($_POST['topic_id'] == "") ? array() : $_POST['topic_id'];
        $smemeber_id = $_POST['smemeber_id'];
        $gen_question_info = $this->TaskAndQuizManagement->getAllGeneralQuestionsOfUser($smemeber_id, "O", $topicIds, $subjectId)->result();
        $genQuestionList = array();
        if (sizeof($gen_question_info)) {
            for ($i = 0; $i < sizeof($gen_question_info); $i++) {
                $thisQuestionInfo = array(
                    'oqb_id' => $gen_question_info[$i]->qb_id,
                    'oqb_question' => stripslashes($gen_question_info[$i]->qb_question),
                    'oqb_image' => ($gen_question_info[$i]->qb_image == NULL || $gen_question_info[$i]->qb_image == "") ? "" : "<br><img src='" . base_url($gen_question_info[$i]->qb_image) . "' width='50%' height='50%'/>",
                    'oqb_opt_a' => stripslashes($gen_question_info[$i]->qb_opt_a),
                    'oqb_opt_a_img' => ($gen_question_info[$i]->qb_opt_a_img == NULL || $gen_question_info[$i]->qb_opt_a_img == "") ? "" : "<br><img src='" . base_url($gen_question_info[$i]->qb_opt_a_img) . "' width='50%' height='50%'/>",
                    'oqb_opt_b' => stripslashes($gen_question_info[$i]->qb_opt_b),
                    'oqb_opt_b_img' => ($gen_question_info[$i]->qb_opt_b_img == NULL || $gen_question_info[$i]->qb_opt_b_img == "") ? "" : "<br><img src='" . base_url($gen_question_info[$i]->qb_opt_b_img) . "' width='50%' height='50%'/>",
                    'oqb_opt_c' => stripslashes($gen_question_info[$i]->qb_opt_c),
                    'oqb_opt_c_img' => ($gen_question_info[$i]->qb_opt_c_img == NULL || $gen_question_info[$i]->qb_opt_c_img == "") ? "" : "<br><img src='" . base_url($gen_question_info[$i]->qb_opt_c_img) . "' width='50%' height='50%'/>",
                    'oqb_opt_d' => stripslashes($gen_question_info[$i]->qb_opt_d),
                    'oqb_opt_d_img' => ($gen_question_info[$i]->qb_opt_d_img == NULL || $gen_question_info[$i]->qb_opt_d_img == "") ? "" : "<br><img src='" . base_url($gen_question_info[$i]->qb_opt_d_img) . "' width='50%' height='50%'/>",
                    'oqb_correct_opt' => $gen_question_info[$i]->qb_correct_opt,
                    'oqb_marks' => stripslashes($gen_question_info[$i]->qb_marks)
                );
                array_push($genQuestionList, $thisQuestionInfo);
            }
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'available_question' => sizeof($gen_question_info),
                'question_list' => $genQuestionList,
                'message' => 'General Questions Available'
            );
        } else {
            $responseData = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash(),
                'available_question' => 0,
                'question_list' => $genQuestionList,
                'message' => 'No General Questions Available Under Selected Subject/Topic.'
            );
        }
        echo json_encode($responseData);
    }

    /* Request Handlers For Subjective Model Papers */

    public function subjectiveModelPapers() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['modelPapers'] = $this->TaskAndQuizManagement->getAllModelExamPapersOfUser($this->session->userdata("adminData")["smember_id"], "S")->result();
            $this->load->view('admin/quizzes/modelPapers', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createSubjectiveModelPaper() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $this->load->view('admin/quizzes/createSubjectiveModelPaper', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewModelExamPaper() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select A Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('modelPaperTitle', 'Model Paper Title', 'trim|required', array('required' => 'Please Enter Model Paper Title.'));
            if ($this->form_validation->run() == FALSE) {
                $this->createSubjectiveModelPaper();
            } else {
                $selectedGenQuestions = $this->input->post('selectedGenQuestions');
                $selectedGroupQuestions = $this->input->post('selectedGroupQuestions');
                $newModelPaperInfo = array(
                    'mepm_title' => addslashes(trim($this->input->post('modelPaperTitle'))),
                    'mepm_description' => addslashes(trim($this->input->post('modelPaperDesc'))),
                    'sm_id' => $this->input->post('subject'),
                    'mepm_type' => $this->input->post('modelPaperType'),
                    'mepm_added_on' => date("Y-m-d H:i:s"),
                    'mepm_added_by' => $this->session->userdata("adminData")["smember_id"],
                    'mepm_updated_on' => date("Y-m-d H:i:s"),
                    'mepm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->db->trans_start();
                $modelPaperQuestionMap = array();
                $mepm_id = $this->TaskAndQuizManagement->createNewModelPaper($newModelPaperInfo);
                for ($i = 0; $i < sizeof($selectedGenQuestions); $i++) {
                    array_push($modelPaperQuestionMap, array(
                        'mepm_id' => $mepm_id,
                        'qb_id' => $selectedGenQuestions[$i]
                    ));
                }
                for ($i = 0; $i < sizeof($selectedGroupQuestions); $i++) {
                    array_push($modelPaperQuestionMap, array(
                        'mepm_id' => $mepm_id,
                        'qb_id' => $selectedGroupQuestions[$i]
                    ));
                }
                if ($this->TaskAndQuizManagement->createNewModelPaperQuestionMappingMulti($modelPaperQuestionMap)) {
                    $this->db->trans_complete();
                    $this->session->set_flashdata('successMessage', 'Model Paper Created Successfully.');
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Creating Model Paper. Try Later.');
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function updateModelExamPaper() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $model_paper_type = $this->input->post("mepmType");
            $mpemUpdateData = array(
                'mepm_id' => trim($this->input->post('mepmIdEdit')),
                'mepm_title' => addslashes(trim($this->input->post('modelPaperTitleEdit'))),
                'mepm_description' => addslashes(trim($this->input->post('modelPaperDescEdit'))),
                'mepm_updated_on' => date("Y-m-d H:i:s"),
                'mepm_updated_by' => $this->session->userdata("adminData")["smember_id"]
            );
            if ($this->TaskAndQuizManagement->updateModelExamPaperInfo($mpemUpdateData)) {
                $this->session->set_flashdata('successMessage', 'Model Paper Info Updated Successfully.');
                if ($model_paper_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Updating Model Info. Try Later.');
                if ($model_paper_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function toggleModelPaperStatus($mepm_id, $toUpdateStatus, $model_paper_type) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $mpemUpdateData = array(
                'mepm_id' => $mepm_id,
                'mepm_updated_on' => date("Y-m-d H:i:s"),
                'mepm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'mepm_active_status' => $toUpdateStatus
            );
            if ($this->TaskAndQuizManagement->updateModelExamPaperInfo($mpemUpdateData)) {
                $this->session->set_flashdata('successMessage', 'Model Paper Status Updated Successfully.');
                if ($model_paper_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Updating Model Paper Status. Try Later.');
                if ($model_paper_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteModelPaper($mepm_id, $model_paper_type) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $mpemDeleteData = array(
                'mepm_id' => $mepm_id,
                'mepm_updated_on' => date("Y-m-d H:i:s"),
                'mepm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'mepm_delete_status' => 'T'
            );
            if ($this->TaskAndQuizManagement->updateModelExamPaperInfo($mpemDeleteData)) {
                $this->session->set_flashdata('successMessage', 'Model Paper Deleted Successfully.');
                if ($model_paper_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting Model Paper. Try Later.');
                if ($model_paper_type == "S") {
                    redirect("admin/TasksAndQuizzes/subjectiveModelPapers");
                } else {
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function getModelPaperInfo() {
        $mepm_id = $_POST['mepm_id'];
        $model_paper_info = $this->TaskAndQuizManagement->getModelExamPaperInfoBy($mepm_id)->result()[0];
        $model_paper_gen_questions = $this->TaskAndQuizManagement->getModelExamPaperGeneralQuestionsBy($mepm_id)->result();
        $model_paper_group_questions = $this->TaskAndQuizManagement->getModelExamPaperGroupQuestionsBy($mepm_id)->result();
        $maximumMarks = 0;
        $allGenQuestions = array();
        $allGroupQuestions = array();
        /* All General Questions */
        for ($i = 0; $i < sizeof($model_paper_gen_questions); $i++) {
            array_push($allGenQuestions, array(
                'sr_no' => ($i + 1) . ".",
                'sqb_id' => $model_paper_gen_questions[$i]->qb_id,
                'sqb_question' => stripslashes($model_paper_gen_questions[$i]->qb_question),
                'sqb_image' => ($model_paper_gen_questions[$i]->qb_image != NULL || $model_paper_gen_questions[$i]->qb_image != "") ? "<br><img src='" . base_url($model_paper_gen_questions[$i]->qb_image) . "' width='50%'>" : "",
                'sqb_marks' => $model_paper_gen_questions[$i]->qb_marks
            ));
            $maximumMarks += $model_paper_gen_questions[$i]->qb_marks;
        }
        /* All General Questions */
        /* All Group Questions */
        $thisGroupQuestion = "";
        $srno = 0;
        for ($i = 0; $i < sizeof($model_paper_group_questions); $i++) {
            $record = $model_paper_group_questions[$i];
            $tempGroupQuestion = "";
            $tempGroupMarks = "";
            $tempGroupImage = "";
            $tempSrno = "";
            if ($thisGroupQuestion != $record->qg_question) {
                $thisGroupQuestion = $record->qg_question;
                $tempGroupQuestion = $record->qg_question;
                $tempGroupMarks = $record->qg_marks;
                $tempGroupImage = ($record->qg_image == NULL || $record->qg_image == "") ? "" : "<br><center><img src='" . base_url($record->qg_image) . "'/></center>";
                $tempSrno = ++$srno;
                $maximumMarks += $record->qg_marks;
            } else {
                $tempGroupQuestion = "";
                $tempGroupMarks = "";
                $tempGroupImage = "";
                $tempSrno = "";
            }
            $thisQuestionInfo = array(
                'sr_no' => $tempSrno . ".",
                'sqg_id' => $record->qg_id,
                'sqg_question' => "<b>" . stripslashes($tempGroupQuestion) . "</b><br>",
                'sqg_marks' => $tempGroupMarks,
                'sqg_image' => $tempGroupImage,
                'sub_questions' => array(
                    'sqb_id' => $record->qb_id,
                    'sqb_question' => stripslashes($record->qb_question),
                    'sqb_marks' => $record->qb_marks
                )
            );
            array_push($allGroupQuestions, $thisQuestionInfo);
        }

        /* All Group Questions */
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'mepm_id' => $model_paper_info->mepm_id,
            'mepm_title' => stripslashes($model_paper_info->mepm_title),
            'mepm_description' => stripslashes($model_paper_info->mepm_description),
            'subject_id' => $model_paper_info->sm_id,
            'subject_name' => stripslashes($model_paper_info->sm_name),
            'subject_code' => stripslashes($model_paper_info->sm_code),
            'subject_sem' => ($model_paper_info->course_time_mgmt_flag == "Y") ? $model_paper_info->sm_semester . " Year" : $model_paper_info->sm_semester . " Sem",
            'course_id' => $model_paper_info->course_id,
            'course_name' => stripslashes($model_paper_info->course_name),
            'maximum_marks' => $maximumMarks,
            'mepm_gen_questions' => $allGenQuestions,
            'mepm_group_questions' => $allGroupQuestions
        );
        echo json_encode($responseData);
    }

    /* Request Handlers For Objective Model Papers */

    public function objectiveModelPapers() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions()->result();
            $viewData['objectiveModelPapers'] = $this->TaskAndQuizManagement->getAllModelExamPapersOfUser($this->session->userdata("adminData")["smember_id"], "O")->result();
            $this->load->view('admin/quizzes/objectiveModelPapers', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createObjectiveModelPaper() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['courses'] = $this->CourseManagement->getActiveAndNonDeletedCourses()->result();
            $this->load->view('admin/quizzes/createObjectiveModelPaper', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewObjectiveModelExamPaper() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subjectCourse', 'Course', 'trim|required', array('required' => 'Please Select A Course.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('modelPaperTitle', 'Model Paper Title', 'trim|required', array('required' => 'Please Enter Model Paper Title.'));
            if ($this->form_validation->run() == FALSE) {
                $this->createObjectiveModelPaper();
            } else {
                $selectedGenQuestions = $this->input->post('selectedGenQuestions');
                $newObjectiveModelPaperInfo = array(
                    'mepm_title' => addslashes(trim($this->input->post('modelPaperTitle'))),
                    'mepm_description' => addslashes(trim($this->input->post('modelPaperDesc'))),
                    'sm_id' => $this->input->post('subject'),
                    'mepm_type' => "O",
                    'mepm_added_on' => date("Y-m-d H:i:s"),
                    'mepm_added_by' => $this->session->userdata("adminData")["smember_id"],
                    'mepm_updated_on' => date("Y-m-d H:i:s"),
                    'mepm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->db->trans_start();
                $objectiveModelPaperQuestionMap = array();
                $omepm_id = $this->TaskAndQuizManagement->createNewModelPaper($newObjectiveModelPaperInfo);
                for ($i = 0; $i < sizeof($selectedGenQuestions); $i++) {
                    array_push($objectiveModelPaperQuestionMap, array(
                        'mepm_id' => $omepm_id,
                        'qb_id' => $selectedGenQuestions[$i]
                    ));
                }
                if ($this->TaskAndQuizManagement->createNewModelPaperQuestionMappingMulti($objectiveModelPaperQuestionMap)) {
                    $this->db->trans_complete();
                    $this->session->set_flashdata('successMessage', 'Objective Model Paper Created Successfully.');
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Creating Objective Model Paper. Try Later.');
                    redirect("admin/TasksAndQuizzes/objectiveModelPapers");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function getObjectiveModelPaperInfo() {
        $mepm_id = $_POST['omepm_id'];
        $model_paper_info = $this->TaskAndQuizManagement->getModelExamPaperInfoBy($mepm_id)->result()[0];
        $model_paper_gen_questions = $this->TaskAndQuizManagement->getModelExamPaperGeneralQuestionsBy($mepm_id)->result();
        $maximumMarks = 0;
        $allGenQuestions = array();
        /* All General Questions */
        for ($i = 0; $i < sizeof($model_paper_gen_questions); $i++) {
            array_push($allGenQuestions, array(
                'sr_no' => ($i + 1) . ".",
                'oqb_id' => $model_paper_gen_questions[$i]->qb_id,
                'oqb_question' => stripslashes($model_paper_gen_questions[$i]->qb_question),
                'oqb_image' => ($model_paper_gen_questions[$i]->qb_image != NULL || $model_paper_gen_questions[$i]->qb_image != "") ? "<br><img src='" . base_url($model_paper_gen_questions[$i]->qb_image) . "' width='50%'>" : "",
                'oqb_opt_a' => stripslashes($model_paper_gen_questions[$i]->qb_opt_a),
                'oqb_opt_a_img' => ($model_paper_gen_questions[$i]->qb_opt_a_img != NULL || $model_paper_gen_questions[$i]->qb_opt_a_img != "") ? "<br><img src='" . base_url($model_paper_gen_questions[$i]->qb_opt_a_img) . "' width='50%'>" : "",
                'oqb_opt_b' => stripslashes($model_paper_gen_questions[$i]->qb_opt_b),
                'oqb_opt_b_img' => ($model_paper_gen_questions[$i]->qb_opt_b_img != NULL || $model_paper_gen_questions[$i]->qb_opt_b_img != "") ? "<br><img src='" . base_url($model_paper_gen_questions[$i]->qb_opt_b_img) . "' width='50%'>" : "",
                'oqb_opt_c' => stripslashes($model_paper_gen_questions[$i]->qb_opt_c),
                'oqb_opt_c_img' => ($model_paper_gen_questions[$i]->qb_opt_c_img != NULL || $model_paper_gen_questions[$i]->qb_opt_c_img != "") ? "<br><img src='" . base_url($model_paper_gen_questions[$i]->qb_opt_c_img) . "' width='50%'>" : "",
                'oqb_opt_d' => stripslashes($model_paper_gen_questions[$i]->qb_opt_d),
                'oqb_opt_d_img' => ($model_paper_gen_questions[$i]->qb_opt_d_img != NULL || $model_paper_gen_questions[$i]->qb_opt_d_img != "") ? "<br><img src='" . base_url($model_paper_gen_questions[$i]->qb_opt_d_img) . "' width='50%'>" : "",
                'oqb_marks' => $model_paper_gen_questions[$i]->qb_marks
            ));
            $maximumMarks += $model_paper_gen_questions[$i]->qb_marks;
        }
        /* All General Questions */
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'omepm_id' => $model_paper_info->mepm_id,
            'omepm_title' => stripslashes($model_paper_info->mepm_title),
            'omepm_description' => stripslashes($model_paper_info->mepm_description),
            'subject_name' => stripslashes($model_paper_info->sm_name),
            'subject_code' => stripslashes($model_paper_info->sm_code),
            'subject_sem' => ($model_paper_info->course_time_mgmt_flag == "Y") ? $model_paper_info->sm_semester . " Year" : $model_paper_info->sm_semester . " Sem",
            'course_name' => stripslashes($model_paper_info->course_name),
            'maximum_marks' => $maximumMarks,
            'omepm_gen_questions' => $allGenQuestions
        );
        echo json_encode($responseData);
    }

    public function getAllModelPaperBySubjectForDropDown() {
        $sm_id = $_POST['sm_id'];
        $mepm_id = (isset($_POST['mepm_id'])) ? $_POST['mepm_id'] : "";
        $query = $this->TaskAndQuizManagement->getAllModelExamPapersOfUserBySubject($this->session->userdata("adminData")["smember_id"], $sm_id);
        $modelPaperList = $query->result();
        $options = "";
        for ($i = 0; $i < (sizeof($modelPaperList)); $i++) {
            $selected = "";
            if ($mepm_id != "" && ($modelPaperList[$i]->mepm_id == $mepm_id )) {
                $selected = "selected";
            }
            $mepmType = ($modelPaperList[$i]->mepm_type == "S") ? "Subjective" : (($modelPaperList[$i]->mepm_type == "O") ? "Objective" : "Miscelleneous");
            $options .= "<option value=" . $modelPaperList[$i]->mepm_id . " " . $selected . ">" . stripslashes($modelPaperList[$i]->mepm_title) . " (" . $mepmType . ")" . "</option>";
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'model_paper_list' => $options
        );
        echo json_encode($responseData);
    }

    /* Request Handlers For Model Paper Scheduling & Related Stuffs */

    public function modelPaperSchedules() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $modelPaperInfo = array();
            $modelPaperSchedules = array();
            if (isset($_POST['fetchSchedules'])) {
                $selectedModelPaper = trim($this->input->post('modelPaper'));
                if ($selectedModelPaper != "") {
                    $modelPaperInfo = $this->TaskAndQuizManagement->getModelExamPaperInfoBy($selectedModelPaper)->result();
                    $modelPaperSchedules = $this->TaskAndQuizManagement->getAllSchedulesOfModelPaperBy($selectedModelPaper)->result();
                    $this->session->set_flashdata('errorMessage', NULL);
                } else {
                    $this->session->set_flashdata('errorMessage', "Please Select Any Model Paper To Get Its Schedule.");
                }
            }
            $viewData['subjects'] = $this->SubjectManagement->getAllActiveNonDeletedSubjects()->result();
            $viewData['modelPaperInfo'] = $modelPaperInfo;
            $viewData['modelPaperSchedules'] = $modelPaperSchedules;
            $this->load->view('admin/quizzes/modelPaperSchedules', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createNewSchedule() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions(array('C'))->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllActiveNonDeletedSubjects()->result();
            $this->load->view('admin/quizzes/scheduleModelPaper', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveModelPaperSchedule() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('modelPaper', 'Model Paper', 'trim|required', array('required' => 'Please Select Any Model Paper.'));
            $this->form_validation->set_rules('scheduleStartDate', 'Start Date', 'trim|required', array('required' => 'Please Enter/Choose Start Date.'));
            $this->form_validation->set_rules('scheduleEndDate', 'End Date', 'trim|required', array('required' => 'Please Enter/Choose End Date.'));
            $this->form_validation->set_rules('allowedAttempts', 'Allowed Attempts', 'trim|required', array('required' => 'Please Select Allowed Attempts.'));
            $selectedStudents = $this->input->post('selectedStudents');
            if ($this->form_validation->run() == FALSE) {
                $this->createNewSchedule();
            } else if (!sizeof($selectedStudents)) {
                $this->session->set_flashdata('errorMessage', "Please Select At Least One Student To Schedule Model Paper.");
                $this->createNewSchedule();
            } else {
                $newModelPaperStudentAllot = array();
                $newScheduleInfo = array(
                    'mepsch_start_date' => date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', trim($this->input->post("scheduleStartDate"))))),
                    'mepsch_end_date' => date("Y-m-d 23:59:59", strtotime(str_replace('/', '-', trim($this->input->post("scheduleEndDate"))))),
                    'mepsch_is_result_to_show' => trim($this->input->post('resultShow')),
                    'mepsch_is_detailed_result_to_show' => (trim($this->input->post('detailedResultShow')) == "") ? "F" : trim($this->input->post('detailedResultShow')),
                    'mepsch_allowed_attempts' => trim($this->input->post("allowedAttempts")),
                    'mepm_id' => trim($this->input->post("modelPaper")),
                    'mepsch_schedule_on' => date("Y-m-d H:i:s"),
                    'mepsch_scheduled_by' => $this->session->userdata("adminData")["smember_id"],
                    'mepsch_updated_on' => date("Y-m-d H:i:s"),
                    'mepsch_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->db->trans_start();
                $schedule_id = $this->TaskAndQuizManagement->createNewModelPaperSchedule($newScheduleInfo);
                for ($i = 0; $i < sizeof($selectedStudents); $i++) {
                    array_push($newModelPaperStudentAllot, array(
                        'mepm_id' => trim($this->input->post("modelPaper")),
                        'tspi_id' => $selectedStudents[$i],
                        'mepsch_id' => $schedule_id,
                        'mepsa_allowed_attempts' => trim($this->input->post("allowedAttempts"))
                    ));
                }
                if (sizeof($newModelPaperStudentAllot)) {
                    if ($this->TaskAndQuizManagement->createNewModelPaperStudentAllotmentMulti($newModelPaperStudentAllot)) {
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'Model Paper Scheduled Successfully.');
                        redirect("admin/TasksAndQuizzes/modelPaperSchedules");
                    } else {
                        $this->session->set_flashdata('errorMessage', 'Student Allotment Error Occured While Scheduling Model Paper. Try Later.');
                        redirect("admin/TasksAndQuizzes/modelPaperSchedules");
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', 'Allotment Failed! No Students Selected For Scheduling. Please Select Student(s).');
                    redirect("admin/TasksAndQuizzes/modelPaperSchedules");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editModelPaperScheduleStatus($mepsch_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['subjects'] = $this->SubjectManagement->getAllActiveNonDeletedSubjects()->result();
            $viewData['scheduleInfo'] = $this->TaskAndQuizManagement->getModelPaperScheduleInfoBy($mepsch_id)->result()[0];
            $this->load->view('admin/quizzes/editModelPaperSchedule', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateModelPaperSchedule() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $mepsch_id = $this->input->post("mepsch_id");
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('modelPaper', 'Model Paper', 'trim|required', array('required' => 'Please Select Any Model Paper.'));
            $this->form_validation->set_rules('scheduleStartDate', 'Start Date', 'trim|required', array('required' => 'Please Enter/Choose Start Date.'));
            $this->form_validation->set_rules('scheduleEndDate', 'End Date', 'trim|required', array('required' => 'Please Enter/Choose End Date.'));
            $this->form_validation->set_rules('allowedAttempts', 'Allowed Attempts', 'trim|required', array('required' => 'Please Select Allowed Attempts.'));
            $selectedStudents = $this->input->post('selectedStudents');
            if ($this->form_validation->run() == FALSE) {
                $this->editModelPaperScheduleStatus($mepsch_id);
            } else if (!sizeof($selectedStudents)) {
                $this->session->set_flashdata('errorMessage', "Please Select At Least One Student To Schedule Model Paper.");
                $this->editModelPaperScheduleStatus($mepsch_id);
            } else {
                $newModelPaperStudentAllot = array();
                $scheduleUpdatedInfo = array(
                    'mepsch_id' => $mepsch_id,
                    'mepsch_start_date' => date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', trim($this->input->post("scheduleStartDate"))))),
                    'mepsch_end_date' => date("Y-m-d 23:59:59", strtotime(str_replace('/', '-', trim($this->input->post("scheduleEndDate"))))),
                    'mepsch_is_result_to_show' => trim($this->input->post('resultShow')),
                    'mepsch_is_detailed_result_to_show' => (trim($this->input->post('detailedResultShow')) == "") ? "F" : trim($this->input->post('detailedResultShow')),
                    'mepsch_allowed_attempts' => trim($this->input->post("allowedAttempts")),
                    'mepm_id' => trim($this->input->post("modelPaper")),
                    'mepsch_updated_on' => date("Y-m-d H:i:s"),
                    'mepsch_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->db->trans_start();
                if ($this->TaskAndQuizManagement->updateModelExamPaperScheduleInfo($scheduleUpdatedInfo)) {
                    $this->TaskAndQuizManagement->deleteModelExamPaperStudentAllotment($mepsch_id);
                    for ($i = 0; $i < sizeof($selectedStudents); $i++) {
                        array_push($newModelPaperStudentAllot, array(
                            'mepm_id' => trim($this->input->post("modelPaper")),
                            'tspi_id' => $selectedStudents[$i],
                            'mepsch_id' => $mepsch_id,
                            'mepsa_allowed_attempts' => trim($this->input->post("allowedAttempts"))
                        ));
                    }
                    if ($this->TaskAndQuizManagement->createNewModelPaperStudentAllotmentMulti($newModelPaperStudentAllot)) {
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'Schedule Updated Successfully.');
                        redirect("admin/TasksAndQuizzes/modelPaperSchedules");
                    } else {
                        $this->session->set_flashdata('errorMessage', 'Student Allotment Error Occured While Updating Model Paper Schedule. Try Later.');
                        redirect("admin/TasksAndQuizzes/modelPaperSchedules");
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', 'Allotment Failed! No Students Selected For Scheduling. Please Select Student(s).');
                    redirect("admin/TasksAndQuizzes/modelPaperSchedules");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function toggleModelPaperScheduleStatus($mepsch_id, $toUpdateStatus) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $scheduleUpdateData = array(
                'mepsch_id' => $mepsch_id,
                'mepsch_updated_on' => date("Y-m-d H:i:s"),
                'mepsch_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'mepsch_active_status' => $toUpdateStatus
            );
            if ($this->TaskAndQuizManagement->updateModelExamPaperScheduleInfo($scheduleUpdateData)) {
                $this->session->set_flashdata('successMessage', 'Model Paper Schedule Updated Successfully.');
                redirect("admin/TasksAndQuizzes/modelPaperSchedules");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Updating Model Paper Schedule. Try Later.');
                redirect("admin/TasksAndQuizzes/modelPaperSchedules");
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteModelPaperSchedule($mepsch_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $scheduleUpdateData = array(
                'mepsch_id' => $mepsch_id,
                'mepsch_updated_on' => date("Y-m-d H:i:s"),
                'mepsch_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'mepsch_delete_status' => 'T'
            );
            if ($this->TaskAndQuizManagement->updateModelExamPaperScheduleInfo($scheduleUpdateData)) {
                $this->session->set_flashdata('successMessage', 'Model Paper Schedule Deleted Successfully.');
                redirect("admin/TasksAndQuizzes/modelPaperSchedules");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting Model Paper Schedule. Try Later.');
                redirect("admin/TasksAndQuizzes/modelPaperSchedules");
            }
        } else {
            redirect("admin/");
        }
    }

    public function getModelPaperAttemptInfo() {
        $mepsch_id = $_POST['mepsch_id'];
        $studentAttemptInfo = array();
        $allottedStudentsInfo = $this->TaskAndQuizManagement->getAllottedModelPapersBySchedule($mepsch_id)->result();
        if (sizeof($allottedStudentsInfo)) {
            for ($i = 0; $i < sizeof($allottedStudentsInfo); $i++) {
                $student_info = $this->StudentManagement->getStudentPersonalInfoAndPhotoSignBy($allottedStudentsInfo[$i]->tspi_id)->result()[0];
                $studentAttemptDetails = $this->TaskAndQuizManagement->getModelPaperAttemptResponseByStudent($allottedStudentsInfo[$i]->tspi_id, $allottedStudentsInfo[$i]->mepm_id)->result();
                if (sizeof($studentAttemptDetails)) {
                    $maximumMarks = 0.0;
                    $obtainedMarks = 0.0;
                    $totalAttempts = sizeof($this->TaskAndQuizManagement->getModelPaperAttemptByStudent($allottedStudentsInfo[$i]->tspi_id, $allottedStudentsInfo[$i]->mepm_id)->result());
                    for ($j = 0; $j < sizeof($studentAttemptDetails); $j++) {
                        $maximumMarks += $studentAttemptDetails[$j]->qb_marks;
                        if ($studentAttemptDetails[$j]->meprm_obj_resp == $studentAttemptDetails[$j]->meprm_correct_resp) {
                            $obtainedMarks += $studentAttemptDetails[$j]->qb_marks;
                        } else {
                            $obtainedMarks -= $studentAttemptDetails[$j]->qb_negative_marks;
                        }
                    }
                    array_push($studentAttemptInfo, array(
                        'stu_id' => $student_info->tspi_id,
                        'stu_enrollment_no' => ($student_info->tspi_form_no == $student_info->tspi_enrollment_no) ? "-" : stripslashes($student_info->tspi_enrollment_no),
                        'stu_name' => stripslashes($student_info->tspi_name),
                        'result' => $obtainedMarks . "/" . $maximumMarks,
                        'attempts_used' => $totalAttempts,
                        'allowed_attempts' => ($allottedStudentsInfo[$i]->mepsch_allowed_attempts == 0) ? "Unlimited Attempts" : $allottedStudentsInfo[$i]->mepsch_allowed_attempts
                    ));
                } else {
                    array_push($studentAttemptInfo, array(
                        'stu_id' => $student_info->tspi_id,
                        'stu_enrollment_no' => ($student_info->tspi_form_no == $student_info->tspi_enrollment_no) ? "-" : stripslashes($student_info->tspi_enrollment_no),
                        'stu_name' => stripslashes($student_info->tspi_name),
                        'result' => "Not Available",
                        'attempts_used' => 0,
                        'allowed_attempts' => ($allottedStudentsInfo[$i]->mepsch_allowed_attempts == 0) ? "Unlimited Attempts" : $allottedStudentsInfo[$i]->mepsch_allowed_attempts
                    ));
                }
            }
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'student_attempt_info' => $studentAttemptInfo
        );
        echo json_encode($responseData);
    }

    public function unlockModelPaperAttempt() {
        $mepsch_id = $_POST['mepsch_id'];
        $tspi_id = $_POST['tspi_id'];
        $allottedStudentsInfo = $this->TaskAndQuizManagement->getAllottedModelPapersBySchedule($mepsch_id, '', $tspi_id)->result()[0];
        $mepm_id = $allottedStudentsInfo->mepm_id;
        $allowed_attempts = $allottedStudentsInfo->mepsch_allowed_attempts;
        if ($allowed_attempts == 1) {
            $this->db->trans_start();
            $this->TaskAndQuizManagement->deleteModelPaperStudentAttempt($mepsch_id, $mepm_id, $tspi_id, false);
            $this->TaskAndQuizManagement->deleteModelPaperStudentResponse($mepsch_id, $mepm_id, $tspi_id);
            $this->db->trans_complete();
        } else {
            $this->TaskAndQuizManagement->deleteModelPaperStudentAttempt($mepsch_id, $mepm_id, $tspi_id, true);
        }

        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'unlock_response' => 1
        );
        echo json_encode($responseData);
    }

    /* Request Handler For E-Content Management */

    public function eContents() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $filterRecords = array();
            if (isset($_POST['fetchEContents'])) {
                $searchKeyword = trim($this->input->post('title'));
                $selectedSession = trim($this->input->post('session'));
                $selectedSubject = trim($this->input->post('subject'));
                $selectedStartDate = (trim($this->input->post("startDate")) == "") ? "" : date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', trim($this->input->post("startDate")))));
                $selectedEndDate = (trim($this->input->post("endDate")) == "") ? "" : date("Y-m-d 23:59:59", strtotime(str_replace('/', '-', trim($this->input->post("endDate")))));
                $selectedRangeAppliedWith = (trim($this->input->post("dateRangeAppliedWith")) == "") ? "" : trim($this->input->post("dateRangeAppliedWith"));
                $filterRecords = $this->TaskAndQuizManagement->getAllEContentsBy($this->session->userdata("adminData")["smember_id"], "F", $searchKeyword, $selectedSession, $selectedSubject, $selectedStartDate, $selectedEndDate, $selectedRangeAppliedWith)->result();
            } else {
                $selectedSession = $this->SessionManagement->getCurrentSessionInfo()->result()[0]->session_id;
                $filterRecords = $this->TaskAndQuizManagement->getAllEContentsBy($this->session->userdata("adminData")["smember_id"], "F", '', $selectedSession, '', '', '', '', '')->result();
            }
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions()->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllotedSubjectBy($this->session->userdata("adminData")["smember_id"], '', '')->result();
            $viewData['econtents'] = $filterRecords;
            $this->load->view('admin/quizzes/eContents', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createNewEContent() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions(array('C'))->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllotedSubjectBy($this->session->userdata("adminData")["smember_id"], $this->SessionManagement->getCurrentSessionInfo()->result()[0]->session_id, '')->result();
            $this->load->view('admin/quizzes/createEContent', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewEContent() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('session', 'Session', 'trim|required', array('required' => 'Session Selection Is Required.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('course', 'Course', 'trim|required', array('required' => 'Course Selection Is Required.'));
            $this->form_validation->set_rules('title', 'E-Content Title', 'trim|required', array('required' => 'Please Enter E-Content Title.'));
            if ($this->form_validation->run() == FALSE) {
                $this->createNewEContent();
            } else if (empty($_FILES['file']['name'])) {
                $this->form_validation->set_rules('file', 'File', 'required', array('required' => 'E-Content File Is Required.'));
                $this->form_validation->run();
                $this->createNewEContent();
            } else {
                $eContentFileNameWithPath = "";
                $configEContentFile['upload_path'] = './assets/admin/uploads/econtents/';
                $configEContentFile['allowed_types'] = 'pdf|ppt|pptx|doc|docx|xls|xlsx|rar|zip|txt|csv|png|jpg|jpeg';
                $configEContentFile['max_size'] = '2048';
                $configEContentFile['file_ext_tolower'] = TRUE;
                $configEContentFile['encrypt_name'] = TRUE;
                $this->load->library('upload', $configEContentFile);
                if (!$this->upload->do_upload('file')) {
                    $this->session->set_flashdata('errorMessage', "E-Content File Can Not Be Uploaded. File Size 2 MB Max. & Allowed Extension: Only *.pdf,*.ppt(x),*.doc(x),*.xls(x),*.rar,*.zip,*.txt,*.csv,*.png,*.jpg,*.jpeg.");
                    $this->createNewEContent();
                } else {
                    $eContentFileNameWithPath = "/assets/admin/uploads/econtents/" . $this->upload->data()['file_name'];
                    $newEContentInfo = array(
                        'ecm_title' => trim(addslashes($this->input->post("title"))),
                        'ecm_description' => trim(addslashes($this->input->post("description"))),
                        'ecm_file' => $eContentFileNameWithPath,
                        'sm_id' => trim($this->input->post('subject')),
                        'session_id' => trim($this->input->post("session")),
                        'ecm_added_on' => date("Y-m-d H:i:s"),
                        'ecm_added_by' => $this->session->userdata("adminData")["smember_id"],
                        'ecm_updated_on' => date("Y-m-d H:i:s"),
                        'ecm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                    );
                    if ($this->TaskAndQuizManagement->createNewEContent($newEContentInfo)) {
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'E-Content Saved Successfully.');
                        redirect("admin/TasksAndQuizzes/eContents");
                    } else {
                        $this->session->set_flashdata('errorMessage', 'An Error Occured While Saving E-Content. Try Later.');
                        redirect(current_url());
                    }
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editEContent($ecm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['econtentInfo'] = $this->TaskAndQuizManagement->getEContentInfoBy($ecm_id)->result()[0];
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions(array('C'))->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllotedSubjectBy($this->session->userdata("adminData")["smember_id"], $this->SessionManagement->getCurrentSessionInfo()->result()[0]->session_id, '')->result();
            $this->load->view('admin/quizzes/editEContent', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateEContent() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $ecm_id = trim($this->input->post("ecm_id"));
            $this->form_validation->set_rules('session', 'Session', 'trim|required', array('required' => 'Session Selection Is Required.'));
            $this->form_validation->set_rules('subject', 'Subject', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('course', 'Course', 'trim|required', array('required' => 'Course Selection Is Required.'));
            $this->form_validation->set_rules('title', 'E-Content Title', 'trim|required', array('required' => 'Please Enter E-Content Title.'));
            $eContentCurrentFileName = substr($this->input->post('ecm_file_path'), strripos($this->input->post('ecm_file_path'), "/") + 1);
            if ($this->form_validation->run() == FALSE) {
                $this->editEContent($ecm_id);
            } else {
                if (empty($_FILES['file']['name'])) {
                    $eContentUpdatedInfo = array(
                        'ecm_id' => $ecm_id,
                        'ecm_title' => trim(addslashes($this->input->post("title"))),
                        'ecm_description' => trim(addslashes($this->input->post("description"))),
                        'sm_id' => trim($this->input->post('subject')),
                        'session_id' => trim($this->input->post("session")),
                        'ecm_updated_on' => date("Y-m-d H:i:s"),
                        'ecm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                    );
                    if ($this->TaskAndQuizManagement->updateEContentInfo($eContentUpdatedInfo)) {
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'E-Content Saved Successfully.');
                        redirect("admin/TasksAndQuizzes/eContents");
                    } else {
                        $this->session->set_flashdata('errorMessage', 'An Error Occured While Saving E-Content. Try Later.');
                        redirect(current_url());
                    }
                } else {
                    $eContentFileNameWithPath = "";
                    $configEContentFile['upload_path'] = './assets/admin/uploads/econtents/';
                    $configEContentFile['allowed_types'] = 'pdf|ppt|pptx|doc|docx|xls|xlsx|rar|zip|txt|csv|png|jpg|jpeg';
                    $configEContentFile['max_size'] = '2048';
                    $configEContentFile['file_ext_tolower'] = TRUE;
                    $configEContentFile['encrypt_name'] = TRUE;
                    $this->load->library('upload', $configEContentFile);
                    if (!$this->upload->do_upload('file')) {
                        $this->session->set_flashdata('errorMessage', "E-Content File Can Not Be Uploaded. File Size 2 MB Max. & Allowed Extension: Only *.pdf,*.ppt(x),*.doc(x),*.xls(x),*.rar,*.zip,*.txt,*.csv,*.png,*.jpg,*.jpeg.");
                        $this->editEContent($ecm_id);
                    } else {
                        $eContentFileNameWithPath = "/assets/admin/uploads/econtents/" . $this->upload->data()['file_name'];
                        $eContentUpdatedInfo = array(
                            'ecm_id' => $ecm_id,
                            'ecm_title' => trim(addslashes($this->input->post("title"))),
                            'ecm_description' => trim(addslashes($this->input->post("description"))),
                            'ecm_file' => $eContentFileNameWithPath,
                            'sm_id' => trim($this->input->post('subject')),
                            'session_id' => trim($this->input->post("session")),
                            'ecm_updated_on' => date("Y-m-d H:i:s"),
                            'ecm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                        );
                        if ($this->TaskAndQuizManagement->updateEContentInfo($eContentUpdatedInfo)) {
                            $this->db->trans_complete();
                            if (file_exists("./assets/admin/uploads/econtents/" . $eContentCurrentFileName)) {
                                unlink("./assets/admin/uploads/econtents/" . $eContentCurrentFileName);
                            }
                            $this->session->set_flashdata('successMessage', 'E-Content Saved Successfully.');
                            redirect("admin/TasksAndQuizzes/eContents");
                        } else {
                            $this->session->set_flashdata('errorMessage', 'An Error Occured While Saving E-Content. Try Later.');
                            redirect(current_url());
                        }
                    }
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function toggleEContentStatus($ecm_id, $toUpdateStatus) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $eContentUpdateData = array(
                'ecm_id' => $ecm_id,
                'ecm_updated_on' => date("Y-m-d H:i:s"),
                'ecm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'ecm_active_status' => $toUpdateStatus
            );
            if ($this->TaskAndQuizManagement->updateEContentInfo($eContentUpdateData)) {
                $this->session->set_flashdata('successMessage', 'E-Content Status Updated Successfully.');
                redirect("admin/TasksAndQuizzes/eContents");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Updating E-Content Status. Try Later.');
                redirect(current_url());
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteEContent($ecm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $eContentUpdateData = array(
                'ecm_id' => $ecm_id,
                'ecm_updated_on' => date("Y-m-d H:i:s"),
                'ecm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                'ecm_delete_status' => 'T'
            );
            if ($this->TaskAndQuizManagement->updateEContentInfo($eContentUpdateData)) {
                $this->session->set_flashdata('successMessage', 'E-Content Deleted Successfully.');
                redirect("admin/TasksAndQuizzes/eContents");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting E-Content. Try Later.');
                redirect(current_url());
            }
        } else {
            redirect("admin/");
        }
    }

    public function getAllEContentsForDropDown() {
        $sm_id = $_POST['subject_id'];
        $session_id = $_POST['session_id'];
        $ecm_id = (isset($_POST['ecm_id'])) ? $_POST['ecm_id'] : "";
        $query = $this->TaskAndQuizManagement->getAllEContentsBy($this->session->userdata("adminData")["smember_id"], "F", '', $session_id, '', $sm_id, '', '', '');
        $eContentList = $query->result();
        $options = "";
        for ($i = 0; $i < (sizeof($eContentList)); $i++) {
            $selected = "";
            if ($ecm_id != "" && ($eContentList[$i]->ecm_id == $ecm_id )) {
                $selected = "selected";
            }
            $options .= "<option value=" . $eContentList[$i]->ecm_id . " " . $selected . ">" . stripslashes($eContentList[$i]->ecm_title) . "</option>";
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'econtent_list' => $options
        );
        echo json_encode($responseData);
    }

    /* Request Handlers Related To E-Content Assignments */

    public function eContentAssigments() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $filterRecords = array();
            if (isset($_POST['fetchEContentsSchedules'])) {
                $searchKeyword = trim($this->input->post('title'));
                $selectedSession = trim($this->input->post('session'));
                $selectedSubject = trim($this->input->post('subject'));
                $selectedEContent = trim($this->input->post('econtent'));
                $selectedStartDate = (trim($this->input->post("startDate")) == "") ? "" : date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', trim($this->input->post("startDate")))));
                $selectedEndDate = (trim($this->input->post("endDate")) == "") ? "" : date("Y-m-d 23:59:59", strtotime(str_replace('/', '-', trim($this->input->post("endDate")))));
                $filterRecords = $this->TaskAndQuizManagement->getAllEContentSchedulesBy($this->session->userdata("adminData")["smember_id"], 'F', $searchKeyword, $selectedSession, $selectedSubject, $selectedEContent, $selectedStartDate, $selectedEndDate)->result();
            } else {
                $filterRecords = $this->TaskAndQuizManagement->getAllEContentSchedulesBy($this->session->userdata("adminData")["smember_id"], 'F', '', $this->SessionManagement->getCurrentSessionInfo()->result()[0]->session_id, '', '', '', '')->result();
            }
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions()->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllotedSubjectBy($this->session->userdata("adminData")["smember_id"], '', '')->result();
            $viewData['econtents'] = $this->TaskAndQuizManagement->getAllEContentsBy($this->session->userdata("adminData")["smember_id"], 'F', '', '', '', '', '', '', '')->result();
            $viewData['econtentAssignments'] = $filterRecords;
            $this->load->view('admin/quizzes/eContentAssignments', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function assignNewEContent() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions()->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllotedSubjectBy($this->session->userdata("adminData")["smember_id"], $this->SessionManagement->getCurrentSessionInfo()->result()[0]->session_id, '')->result();
            $this->load->view('admin/quizzes/assignEContent', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function makeEContentAssignment() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('session', 'Session', 'trim|required', array('required' => 'Please Select Any Session.'));
            $this->form_validation->set_rules('subject', 'Start Date', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('econtent', 'End Date', 'trim|required', array('required' => 'Please Select Any E-Content.'));
            $this->form_validation->set_rules('scheduleStartDate', 'Start Date', 'trim|required', array('required' => 'Please Enter/Choose Start Date.'));
            $this->form_validation->set_rules('scheduleEndDate', 'End Date', 'trim|required', array('required' => 'Please Enter/Choose End Date.'));
            $selectedStudents = $this->input->post('selectedStudents');
            if (!sizeof($selectedStudents)) {
                $this->session->set_flashdata('errorMessage', "Please Select At Least One Student To Assign E-Content.");
                $this->assignNewEContent();
            } else {
                $newEContentStudentAssign = array();
                $newEContentSchedule = array(
                    'ecm_id' => trim($this->input->post("econtent")),
                    'ecsm_start_date' => date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', trim($this->input->post("scheduleStartDate"))))),
                    'ecsm_end_date' => date("Y-m-d 23:59:59", strtotime(str_replace('/', '-', trim($this->input->post("scheduleEndDate"))))),
                    'ecsm_note' => trim(addslashes($this->input->post("note"))),
                    'ecsm_scheduled_by' => $this->session->userdata("adminData")["smember_id"],
                    'ecsm_scheduled_on' => date("Y-m-d H:i:s"),
                    'ecsm_schedule_updated_on' => date("Y-m-d H:i:s")
                );
                $this->db->trans_start();
                $schedule_id = $this->TaskAndQuizManagement->createNewEContentSchedule($newEContentSchedule);
                for ($i = 0; $i < sizeof($selectedStudents); $i++) {
                    array_push($newEContentStudentAssign, array(
                        'ecsm_id' => $schedule_id,
                        'tspi_id' => $selectedStudents[$i]
                    ));
                }
                if (sizeof($newEContentStudentAssign)) {
                    if ($this->TaskAndQuizManagement->createNewEContentAssignmentMulti($newEContentStudentAssign)) {
                        $this->session->set_flashdata('successMessage', 'E-Content Assigned Successfully.');
                        redirect("admin/TasksAndQuizzes/eContentAssigments");
                    } else {
                        $this->session->set_flashdata('errorMessage', 'E-Content Assignment To Student Failed Due To Some Errors. Try Later.');
                        redirect(current_url());
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', 'E-Content Assignment Failed! No Students Selected. Please Select Student(s).');
                    redirect(current_url());
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editEContentAssignment($ecsm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['econtentScheduleInfo'] = $this->TaskAndQuizManagement->getEContentScheduleInfoBy($ecsm_id)->result()[0];
            $viewData['sessions'] = $this->SessionManagement->getNonDeletedActiveSessions()->result();
            $viewData['subjects'] = $this->SubjectManagement->getAllotedSubjectBy($this->session->userdata("adminData")["smember_id"], $this->SessionManagement->getCurrentSessionInfo()->result()[0]->session_id, '')->result();
            $this->load->view('admin/quizzes/editEContentAssignment', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateEContentAssignment() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $ecsm_id = $this->input->post("ecsm_id");
            $this->form_validation->set_rules('session', 'Session', 'trim|required', array('required' => 'Please Select Any Session.'));
            $this->form_validation->set_rules('subject', 'Start Date', 'trim|required', array('required' => 'Please Select Any Subject.'));
            $this->form_validation->set_rules('econtent', 'End Date', 'trim|required', array('required' => 'Please Select Any E-Content.'));
            $this->form_validation->set_rules('scheduleStartDate', 'Start Date', 'trim|required', array('required' => 'Please Enter/Choose Start Date.'));
            $this->form_validation->set_rules('scheduleEndDate', 'End Date', 'trim|required', array('required' => 'Please Enter/Choose End Date.'));
            $selectedStudents = $this->input->post('selectedStudents');
            if (!sizeof($selectedStudents)) {
                $this->session->set_flashdata('errorMessage', "Please Select At Least One Student To Assign E-Content.");
                $this->editEContentAssignment($ecsm_id);
            } else {
                $newEContentStudentAssign = array();
                $eContentSchedule = array(
                    'ecsm_id' => $ecsm_id,
                    'ecsm_start_date' => date("Y-m-d 00:00:00", strtotime(str_replace('/', '-', trim($this->input->post("scheduleStartDate"))))),
                    'ecsm_end_date' => date("Y-m-d 23:59:59", strtotime(str_replace('/', '-', trim($this->input->post("scheduleEndDate"))))),
                    'ecsm_note' => trim(addslashes($this->input->post("note"))),
                    'ecsm_schedule_updated_on' => date("Y-m-d H:i:s")
                );
                $this->db->trans_start();
                if ($this->TaskAndQuizManagement->updateEContentScheduleInfo($eContentSchedule)) {
                    $this->TaskAndQuizManagement->deleteEContentStudentAssignment($ecsm_id);
                    for ($i = 0; $i < sizeof($selectedStudents); $i++) {
                        array_push($newEContentStudentAssign, array(
                            'ecsm_id' => $ecsm_id,
                            'tspi_id' => $selectedStudents[$i]
                        ));
                    }
                    if ($this->TaskAndQuizManagement->createNewEContentAssignmentMulti($newEContentStudentAssign)) {
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'E-Content Assignment Updated Successfully.');
                        redirect("admin/TasksAndQuizzes/eContentAssigments");
                    } else {
                        $this->session->set_flashdata('errorMessage', 'An Error Occured While Updating Assignment Info. Try Later.');
                        redirect(current_url());
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', 'Assignment Failed! No Students Selected For Assigning. Please Select Student(s).');
                    redirect(current_url());
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function toggleEContentScheduleStatus($ecsm_id, $toUpdateStatus) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $eContentScheduleUpdateData = array(
                'ecsm_id' => $ecsm_id,
                'ecsm_schedule_updated_on' => date("Y-m-d H:i:s"),
                'ecsm_active_status' => $toUpdateStatus
            );
            if ($this->TaskAndQuizManagement->updateEContentScheduleInfo($eContentScheduleUpdateData)) {
                $this->session->set_flashdata('successMessage', 'E-Content Schedule Status Updated Successfully.');
                redirect("admin/TasksAndQuizzes/eContentAssigments");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Updating E-Content Schedule Status. Try Later.');
                redirect(current_url());
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteEContentSchedule($ecsm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $eContentScheduleUpdateData = array(
                'ecsm_id' => $ecsm_id,
                'ecsm_schedule_updated_on' => date("Y-m-d H:i:s"),
                'ecsm_delete_status' => 'T'
            );
            if ($this->TaskAndQuizManagement->updateEContentScheduleInfo($eContentScheduleUpdateData)) {
                $this->session->set_flashdata('successMessage', 'E-Content Schedule Deleted Successfully.');
                redirect("admin/TasksAndQuizzes/eContentAssigments");
            } else {
                $this->session->set_flashdata('errorMessage', 'Some Error Occurred While Deleting E-Content Schedule. Try Later.');
                redirect(current_url());
            }
        } else {
            redirect("admin/");
        }
    }

}

KBHT - 2023