<?php
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Exam_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    public function getExamByID($id = null)
    {
        $sql = "SELECT `e`.*, `exam_term`.`name` as `term_name`, `b`.`name` as `branch_name` FROM `exam` as `e` INNER JOIN `branch` as `b` ON `b`.`id` = `e`.`branch_id` LEFT JOIN `exam_term` ON `exam_term`.`id` = `e`.`term_id` WHERE `e`.`id` = {$this->db->escape($id)}";
        return $this->db->query($sql)->row();
    }

    public function searchExamStudentsByRank($class_ID = '', $section_ID = '', $session_ID = '', $exam_ID = '', $branch_id = '')
    {
        $this->db->select('e.*,CONCAT_WS(" ",first_name, last_name) as fullname,register_no,c.name as class_name,se.name as section_name,exam_rank.rank,exam_rank.principal_comments,exam_rank.teacher_comments');
        $this->db->from('enroll as e');
        $this->db->join('student as s', 'e.student_id = s.id', 'inner');
        $this->db->join('login_credential as l', 'l.user_id = s.id and l.role = 7', 'inner');
        $this->db->join('class as c', 'e.class_id = c.id', 'left');
        $this->db->join('section as se', 'e.section_id=se.id', 'left');
        $this->db->join('exam_rank', 'exam_rank.enroll_id=e.id and exam_rank.exam_id = ' . $this->db->escape($exam_ID), 'left');
        $this->db->where('e.class_id', $class_ID);
        if (!empty($section_ID)) {
            $this->db->where('e.section_id', $section_ID);
        }
        $this->db->where('e.branch_id', $branch_id);
        $this->db->where('e.session_id', $session_ID);
        $this->db->order_by('exam_rank.rank', 'ASC');
        $this->db->where('l.active', 1);
        return $this->db->get()->result();
    }

    public function getExamList()
    {
        $this->db->select('e.*,b.name as branch_name, st.term_name');
        $this->db->from('exam as e');
        $this->db->join('branch as b', 'b.id = e.branch_id', 'left');
        $this->db->join('schoolterm as st', 'st.id = e.session_term_id', 'left');
        if (!is_superadmin_loggedin()) {
            $this->db->where('e.branch_id', get_loggedin_branch_id());
        }
        $this->db->where('e.session_id', get_session_id());
        $this->db->order_by('e.id', 'asc');
        return $this->db->get()->result_array();
    }

    public function exam_save($data)
    {
        $arrayExam = array(
            'name' => $data['name'],
            'branch_id' => $this->application_model->get_branch_id(),
            'term_id' => $data['term_id'],
            'session_term_id' => $data['term_id'],
            'type_id' => $data['type_id'],
            'mark_distribution' => json_encode($data['mark_distribution']),
            'remark' => $data['remark'],
            'session_id' => get_session_id(),
            'status' => (isset($_POST['exam_publish']) ? 1 : 0),
            'publish_result' => 0,
        );
        if (!isset($data['exam_id'])) {
            $this->db->insert('exam', $arrayExam);
        } else {
            $this->db->where('id', $data['exam_id']);
            $this->db->update('exam', $arrayExam);
        }
    }

    public function termSave($post)
    {
        $arrayTerm = array(
            'name' => $post['term_name'],
            'branch_id' => $this->application_model->get_branch_id(),
            'session_id' => get_session_id(),
        );
        if (!isset($post['term_id'])) {
            $this->db->insert('exam_term', $arrayTerm);
        } else {
            if (!is_superadmin_loggedin()) {
                $this->db->where('branch_id', get_loggedin_branch_id());
            }
            $this->db->where('id', $post['term_id']);
            $this->db->update('exam_term', $arrayTerm);
        }
    }

    public function hallSave($post)
    {
        $arrayHall = array(
            'hall_no' => $post['hall_no'],
            'seats' => $post['no_of_seats'],
            'branch_id' => $this->application_model->get_branch_id(),
        );
        if (!isset($post['hall_id'])) {
            $this->db->insert('exam_hall', $arrayHall);
        } else {
            if (!is_superadmin_loggedin()) {
                $this->db->where('branch_id', get_loggedin_branch_id());
            }
            $this->db->where('id', $post['hall_id']);
            $this->db->update('exam_hall', $arrayHall);
        }
    }
    public function gradeSave($data)
    {
        $arrayData = array(
            'branch_id' => $this->application_model->get_branch_id(),
            'name' => $data['name'],
            'grade_point' => $data['grade_point'],
            'lower_mark' => $data['lower_mark'],
            'upper_mark' => $data['upper_mark'],
            'remark' => $data['remark'],
            'marksheet_id' => $data['template_id'],
           // 'classes_id' => is_array($data['classes_id']) ? implode(',', $data['classes_id']) : '', // Save as comma-separated string
        );
    
        if (!isset($data['grade_id'])) {
            $this->db->insert('grade', $arrayData);
        } else {
            if (!is_superadmin_loggedin()) {
                $this->db->where('branch_id', get_loggedin_branch_id());
            }
            $this->db->where('id', $data['grade_id']);
            $this->db->update('grade', $arrayData);
        }
    }
    


    public function getGradeById($grade_id)
    {
        $this->db->select('grade.*, marksheet_template.name as marksheet_name');
        $this->db->from('grade');
        $this->db->join('marksheet_template', 'marksheet_template.id = grade.marksheet_id', 'left');
        $this->db->where('grade.id', $grade_id);
        $grade = $this->db->get()->row_array();
    
        log_message('debug', 'Grade Data: ' . json_encode($grade)); // Log output for debugging
    
        return $grade;
    }
    

    

    public function get_grade($mark, $branch_id)
    {
        $this->db->where('branch_id', $branch_id);
        $query = $this->db->get('grade');
        $grades = $query->result_array();
        foreach ($grades as $row) {
            if ($mark >= $row['lower_mark'] && $mark <= $row['upper_mark']) {
                return $row;
            }
        }
    }


    public function get_marksheet_grade($mark, $branch_id, $marksheet_template_id)
{
    $this->db->where('branch_id', $branch_id);
    $this->db->where('marksheet_id', $marksheet_template_id); // Add template filter
    $query = $this->db->get('grade');
    $grades = $query->result_array();
    
    foreach ($grades as $row) {
        if ($mark >= $row['lower_mark'] && $mark <= $row['upper_mark']) {
            return $row;
        }
    }
    return null; // Return null if no grade is found
}



    public function getSubjectList($examID, $classID, $sectionID, $sessionID)
    {
        $branchID = $this->application_model->get_branch_id();
        $this->db->select('t.*,s.name as subject_name');
        $this->db->from('timetable_exam as t');
        $this->db->join('subject as s', 's.id = t.subject_id', 'inner');
        $this->db->where('t.exam_id', $examID);
        $this->db->where('t.class_id', $classID);
        $this->db->where('t.section_id', $sectionID);
        $this->db->where('t.session_id', $sessionID);
        $this->db->where('t.branch_id', $branchID);
        $this->db->group_by('t.subject_id');
        return $this->db->get()->result_array();
    }



    // public function generate_class_position($classID, $sectionID, $sessionID, $examID, $branchID)
    // {
    //     // 1) Get enrollment records for this class/section/session/branch
    //     $enrolls = $this->db->select('id, student_id')
    //         ->from('enroll')
    //         ->where('class_id', $classID)
    //         ->where('section_id', $sectionID)
    //         ->where('session_id', $sessionID)
    //         ->where('branch_id', $branchID)
    //         ->get()
    //         ->result_array();
    
    //     if (empty($enrolls)) {
    //         return []; // No enrolled students found
    //     }
    
    //     // Collect unique student IDs from enrollments
    //     $student_ids = array_unique(array_column($enrolls, 'student_id'));
    
    //     // 2) Get all mark rows for these student_ids for the given exam & class/section/session/branch
    //     $marks = $this->db->select('student_id, percentage')
    //         ->from('mark')
    //         ->where_in('student_id', $student_ids)
    //         ->where('exam_id', $examID)
    //         ->where('class_id', $classID)
    //         ->where('section_id', $sectionID)
    //         ->where('session_id', $sessionID)
    //         ->where('branch_id', $branchID)
    //         ->get()
    //         ->result_array();
    
    //     if (empty($marks)) {
    //         return []; // No marks found for these students
    //     }
    
    //     // 3) Parse each mark's JSON percentage, sum the scores, and accumulate totals per student
    //     $studentData = [];
    //     foreach ($marks as $row) {
    //         $student_id = $row['student_id'];
    //         // Decode the JSON string (e.g., {"16":"70.00","17":"60.00"})
    //         $jsonScores = json_decode($row['percentage'], true);
    //         $sum = 0;
    //         if (!empty($jsonScores)) {
    //             foreach ($jsonScores as $val) {
    //                 $sum += floatval($val);
    //             }
    //         }
    
    //         // Initialize if not already set
    //         if (!isset($studentData[$student_id])) {
    //             $studentData[$student_id] = [
    //                 'total' => 0,
    //                 'count' => 0
    //             ];
    //         }
    //         $studentData[$student_id]['total'] += $sum;
    //         // Each row in 'mark' represents one subject, so increment count
    //         $studentData[$student_id]['count']++;
    //     }
    
    //     // 4) Compute each student's average percentage and merge with enroll_id for reference
    //     $ranked_students = [];
    //     foreach ($studentData as $student_id => $data) {
    //         $avg = 0;
    //         if ($data['count'] > 0) {
    //             $avg = $data['total'] / $data['count'];
    //         }
    //         // Find the corresponding enroll_id for this student from the $enrolls array
    //         $enroll_id = 0;
    //         foreach ($enrolls as $enroll) {
    //             if ($enroll['student_id'] == $student_id) {
    //                 $enroll_id = $enroll['id'];
    //                 break;
    //             }
    //         }
    //         $ranked_students[] = [
    //             'enroll_id'     => $enroll_id,
    //             'student_id'    => $student_id,
    //             'avg_percentage'=> $avg
    //         ];
    //     }
    
    //     // 5) Sort students by average percentage in descending order (highest first)
    //     usort($ranked_students, function ($a, $b) {
    //         return $b['avg_percentage'] <=> $a['avg_percentage'];
    //     });
    
    //     // 6) Assign ranks (handling ties if needed)
    //     $position = 1;
    //     $count = 1;
    //     $last_score = null;
    //     foreach ($ranked_students as &$row) {
    //         $current_score = $row['avg_percentage'];
    //         // Update rank if this student's score is lower than the previous one
    //         if ($last_score === null || $current_score < $last_score) {
    //             $position = $count;
    //         }
    //         $row['rank'] = $position;
    //         $last_score = $current_score;
    //         $count++;
    //     }
    //     unset($row);
    
    //     // 7) Insert or update the exam_rank table for each student
    //     foreach ($ranked_students as $student) {
    //         $enroll_id = $student['enroll_id'];
    //         $rank = $student['rank'];
    //         // Check if a record already exists
    //         $existing = $this->db->get_where('exam_rank', [
    //             'enroll_id' => $enroll_id,
    //             'exam_id'   => $examID
    //         ])->row();
    
    //         $data = [
    //             'enroll_id' => $enroll_id,
    //             'exam_id'   => $examID,
    //             'rank'      => $rank
    //         ];
    
    //         if ($existing) {
    //             // Update existing record
    //             $this->db->where('enroll_id', $enroll_id)
    //                 ->where('exam_id', $examID)
    //                 ->update('exam_rank', $data);
    //         } else {
    //             // Insert new record
    //             $this->db->insert('exam_rank', $data);
    //         }
    //     }
    
    //     return $ranked_students;
    // }
    
    


    public function generate_class_position(
        $classID,
        $sectionID,
        $sessionID,
        $examID,
        $branchID
    ) {
        // 1) Get enrollment records for this class/section/session/branch
        $enrolls = $this->db->select('id, student_id')
            ->from('enroll')
            ->where('class_id', $classID)
            ->where('section_id', $sectionID)
            ->where('session_id', $sessionID)
            ->where('branch_id', $branchID)
            ->get()
            ->result_array();
    
        if (empty($enrolls)) {
            return []; // No enrolled students found
        }
    
        // Collect unique student IDs from enrollments
        $student_ids = array_unique(array_column($enrolls, 'student_id'));
    
        // 2) Get all mark rows for these student_ids for the given exam & class/section/session/branch
        $marks = $this->db->select('student_id, percentage')
            ->from('mark')
            ->where_in('student_id', $student_ids)
            ->where('exam_id', $examID)
            ->where('class_id', $classID)
            ->where('section_id', $sectionID)
            ->where('session_id', $sessionID)
            ->where('branch_id', $branchID)
            ->get()
            ->result_array();
    
        if (empty($marks)) {
            return []; // No marks found for these students
        }
    
        // 3) Parse each mark's JSON, sum the scores, and accumulate totals per student
        $studentData = [];
        foreach ($marks as $row) {
            $student_id = $row['student_id'];
            // Example: percentage = '{"16":"70.00","17":"60.00"}'
            $jsonScores = json_decode($row['percentage'], true);
    
            $sum = 0;
            if (!empty($jsonScores)) {
                foreach ($jsonScores as $val) {
                    $sum += floatval($val);
                }
            }
    
            if (!isset($studentData[$student_id])) {
                $studentData[$student_id] = [
                    'total' => 0,   // sum of all subjects
                    'count' => 0    // how many subjects
                ];
            }
    
            $studentData[$student_id]['total'] += $sum;
            $studentData[$student_id]['count']++;
        }
    
        // 4) Compute each student's average + store total in $ranked_students
        $ranked_students = [];
        foreach ($studentData as $student_id => $data) {
            $total_score = $data['total'];
            $avg = ($data['count'] > 0) ? ($total_score / $data['count']) : 0;
    
            // Find the corresponding enroll_id
            $enroll_id = 0;
            foreach ($enrolls as $en) {
                if ($en['student_id'] == $student_id) {
                    $enroll_id = $en['id'];
                    break;
                }
            }
    
            $ranked_students[] = [
                'enroll_id'     => $enroll_id,
                'student_id'    => $student_id,
                'total_score'   => $total_score,     // << NEW: store the total
                'avg_percentage'=> $avg
            ];
        }
    
        // 5) Sort students by average (descending)
        usort($ranked_students, function ($a, $b) {
            return $b['avg_percentage'] <=> $a['avg_percentage'];
        });
    
        // 6) Assign ranks (ties get same rank if avg is the same)
        $position = 1;
        $count = 1;
        $last_score = null;
        foreach ($ranked_students as &$row) {
            $current_score = $row['avg_percentage'];
            if ($last_score === null || $current_score < $last_score) {
                $position = $count;
            }
            $row['rank'] = $position;
            $last_score = $current_score;
            $count++;
        }
        unset($row);
    
        // 7) Insert or update exam_rank for each student
        foreach ($ranked_students as $student) {
            $enroll_id = $student['enroll_id'];
            $rank      = $student['rank'];
    
            $existing = $this->db->get_where('exam_rank', [
                'enroll_id' => $enroll_id,
                'exam_id'   => $examID
            ])->row();
    
            $data = [
                'enroll_id' => $enroll_id,
                'exam_id'   => $examID,
                'rank'      => $rank
            ];
    
            if ($existing) {
                $this->db
                    ->where('enroll_id', $enroll_id)
                    ->where('exam_id', $examID)
                    ->update('exam_rank', $data);
            } else {
                $this->db->insert('exam_rank', $data);
            }
        }
    
        return $ranked_students; 
        // e.g. [
        //   [
        //     'enroll_id' => 292,
        //     'student_id' => 510,
        //     'total_score' => 130,
        //     'avg_percentage' => 65,
        //     'rank' => 1
        //   ],
        //   ...
        // ]
    }
    


    public function getTimetableDetail($classID, $sectionID, $examID, $subjectID, $termID)
    {
        $this->db->select('timetable_exam.mark_distribution');
        $this->db->from('timetable_exam');
        $this->db->join('exam', 'exam.id = timetable_exam.exam_id', 'left');
       
        $this->db->where('timetable_exam.class_id', $classID);
        $this->db->where('timetable_exam.section_id', $sectionID);
        $this->db->where('timetable_exam.exam_id', $examID);
        $this->db->where('timetable_exam.subject_id', $subjectID);
       $this->db->where('exam.session_term_id', $termID);
        $this->db->where('timetable_exam.session_id', get_session_id());
        return $this->db->get()->row_array();
    }




    // public function getTimetableDetail($classID, $sectionID, $examID, $subjectID, $termID)
    // {
    //     $this->db->select('timetable_exam.mark_distribution');
    //     $this->db->from('timetable_exam');
    //     $this->db->join('exam', 'exam.id = timetable_exam.exam_id', 'left');
    //   //  $this->db->join('exam_mark_distribution', 'exam_mark_distribution.id = JSON_UNQUOTE(JSON_EXTRACT(timetable_exam.mark_distribution, "$.*.5"))', 'left'); // Joining based on mark_distribution field
        
    //     // Apply filters
    //     $this->db->where('timetable_exam.class_id', $classID);
    //     $this->db->where('timetable_exam.section_id', $sectionID);
    //     $this->db->where('timetable_exam.exam_id', $examID);
    //     $this->db->where('timetable_exam.subject_id', $subjectID);
    //     $this->db->where('exam.session_term_id', $termID);
    //     $this->db->where('timetable_exam.session_id', get_session_id());
    //   //  $this->db->where('exam_mark_distribution.is_assignment', 0); // Filter where is_assignment = 1
    
    //     return $this->db->get()->row_array();
    // }
    




    public function getEvaluate($termID, $subjectID)
    {
        $this->db->select('
            homework.*, 
            CONCAT_WS(" ", s.first_name, s.last_name) as fullname, 
            s.register_no, 
            e.student_id, 
            e.roll, 
            subject.name as subject_name, 
            class.name as class_name, 
            section.name as section_name, 
            he.id as ev_id, 
            he.status as ev_status, 
            he.remark as ev_remarks, 
            he.marks as ev_marks, 
            he.rank, 
            hs.message, 
            hs.enc_name, 
            SUM(he.marks) as total_marks
        ');
        $this->db->from('homework');
        $this->db->join('enroll as e', 'e.class_id = homework.class_id AND e.section_id = homework.section_id AND e.session_id = homework.session_id', 'inner');
        $this->db->join('student as s', 'e.student_id = s.id', 'inner');
        $this->db->join('homework_evaluation as he', 'he.homework_id = homework.id AND he.student_id = e.student_id', 'left');
        $this->db->join('homework_submit as hs', 'hs.homework_id = homework.id AND hs.student_id = e.student_id', 'left');
        $this->db->join('subject', 'subject.id = homework.subject_id', 'left');
        $this->db->join('class', 'class.id = homework.class_id', 'left');
        $this->db->join('section', 'section.id = homework.section_id', 'left');
        $this->db->join('schoolterm as st', 'st.id = homework.session_term_id', 'left'); // Join the schoolterm table
    
        // Add condition for session term ID
        $this->db->where('homework.session_term_id', $termID);
        $this->db->where('homework.subject_id', $subjectID);
    
        // Add conditions for the start_date and end_date from the schoolterm table
        $this->db->where('homework.evaluation_date >=', 'st.start_date', false);
        $this->db->where('homework.evaluation_date <=', 'st.end_date', false);
    
        // Filter by branch if not superadmin
        if (!is_superadmin_loggedin()) {
            $this->db->where('homework.branch_id', get_loggedin_branch_id());
        }
    
        // Filter by current session
        $this->db->where('homework.session_id', get_session_id());
    
        // Group by student to calculate total marks for each student
        $this->db->group_by('e.student_id');
    
        // Order by homework ID in descending order
        $this->db->order_by('homework.id', 'desc');
    
        return $this->db->get()->result_array();
    }
    



    public function getAssignmentEvaluate($homeworkID)
{
    $this->db->select('
        homework.*, 
        CONCAT_WS(" ", s.first_name, s.last_name) as fullname, 
        s.register_no, 
        e.student_id, 
        e.roll, 
        subject.name as subject_name, 
        class.name as class_name, 
        section.name as section_name, 
        he.id as ev_id, 
        he.status as ev_status, 
        he.remark as ev_remarks, 
        he.marks as ev_marks, 
        he.rank, 
        hs.message, 
        hs.enc_name,
        SUM(CASE 
            WHEN he.evaluation_date >= st.start_date AND he.evaluation_date <= st.end_date 
            THEN he.marks 
            ELSE 0 
        END) as total_marks
    ');
    $this->db->from('homework');
    $this->db->join('enroll as e', 'e.class_id = homework.class_id AND e.section_id = homework.section_id AND e.session_id = homework.session_id', 'inner');
    $this->db->join('student as s', 'e.student_id = s.id', 'inner');
    $this->db->join('homework_evaluation as he', 'he.homework_id = homework.id AND he.student_id = e.student_id', 'left');
    $this->db->join('homework_submit as hs', 'hs.homework_id = homework.id AND hs.student_id = e.student_id', 'left');
    $this->db->join('subject', 'subject.id = homework.subject_id', 'left');
    $this->db->join('class', 'class.id = homework.class_id', 'left');
    $this->db->join('section', 'section.id = homework.section_id', 'left');
    $this->db->join('schoolterm as st', 'st.id = homework.session_term_id', 'left'); // Join the schoolterm table
    $this->db->where('homework.id', $homeworkID);

    // Ensure the evaluation date is within the start_date and end_date of the school term
    $this->db->where('homework.evaluation_date >=', 'st.start_date', false);
    $this->db->where('homework.evaluation_date <=', 'st.end_date', false);

    if (!is_superadmin_loggedin()) {
        $this->db->where('homework.branch_id', get_loggedin_branch_id());
    }

    $this->db->where('homework.session_id', get_session_id());
    $this->db->order_by('homework.id', 'desc');
    $this->db->group_by('e.student_id'); // Group by student to calculate total marks for each student
    return $this->db->get()->result_array();
}






    public function getMarkAndStudent($branchID, $classID, $sectionID, $examID, $subjectID)
    {
        $this->db->select('en.*,st.first_name,st.last_name,st.register_no,st.category_id,m.mark as get_mark,IFNULL(m.absent, 0) as get_abs,subject.name as subject_name, m.teacher_comments, m.principal_comments');
        $this->db->from('enroll as en');
        $this->db->join('student as st', 'st.id = en.student_id', 'inner');
        $this->db->join('mark as m', 'm.student_id = en.student_id and m.class_id = en.class_id and m.section_id = en.section_id and m.exam_id = ' . $this->db->escape($examID) . ' and m.subject_id = ' . $this->db->escape($subjectID), 'left');
        $this->db->join('subject', 'subject.id = m.subject_id', 'left');
        $this->db->where('en.class_id', $classID);
        $this->db->where('en.section_id', $sectionID);
        $this->db->where('en.branch_id', $branchID);
        $this->db->where('en.session_id', get_session_id());
        $this->db->order_by('en.roll', 'ASC');
        return $this->db->get()->result_array();
    }

    public function getStudentReportCard($studentID, $examID, $sessionID, $classID = '', $sectionID = '')
    {
        $result = array();

        $this->db->select('s.*,CONCAT_WS(" ",s.first_name, s.last_name) as name,e.id as enrollID,e.roll,e.branch_id,e.session_id,e.class_id,e.section_id,c.name as class,se.name as section,sc.name as category,IFNULL(p.father_name,"N/A") as father_name,IFNULL(p.mother_name,"N/A") as mother_name,br.name as institute_name,br.email as institute_email,br.address as institute_address,br.mobileno as institute_mobile_no');
        $this->db->from('enroll as e');
        $this->db->join('student as s', 'e.student_id = s.id', 'inner');
        $this->db->join('class as c', 'e.class_id = c.id', 'left');
        $this->db->join('section as se', 'e.section_id = se.id', 'left');
        $this->db->join('student_category as sc', 's.category_id=sc.id', 'left');
        $this->db->join('parent as p', 'p.id=s.parent_id', 'left');
        $this->db->join('branch as br', 'br.id = e.branch_id', 'left');
        $this->db->where('e.student_id', $studentID);
        $this->db->where('e.session_id', $sessionID);
        if (!empty($classID))
            $this->db->where('e.class_id', $classID);
        if (!empty($sectionID))
            $this->db->where('e.section_id', $sectionID);
        $result['student'] = $this->db->get()->row_array();

        $this->db->select('m.percentage as get_mark,IFNULL(m.absent, 0) as get_abs,subject.name as subject_name, te.mark_distribution, m.subject_id');
        $this->db->from('mark as m');
        $this->db->join('subject', 'subject.id = m.subject_id', 'left');
        $this->db->join('timetable_exam as te', 'te.exam_id = m.exam_id and te.class_id = m.class_id and te.section_id = m.section_id and te.subject_id = m.subject_id', 'left');
        $this->db->where('m.exam_id', $examID);
        $this->db->where('m.student_id', $studentID);
        $this->db->where('m.session_id', $sessionID);
        if (!empty($classID))
            $this->db->where('m.class_id', $classID);
        if (!empty($sectionID))
            $this->db->where('m.section_id', $sectionID);
        $this->db->group_by('m.subject_id');
        $this->db->order_by('subject.id', 'ASC');
        $result['exam'] = $this->db->get()->result_array();
        return $result;
    }

}
