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

class Endofterm extends Admin_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('smsgateway');
        $this->load->library('mailsmsconf');
        $this->load->model('classteacher_model');
        $this->load->model('setting_model');
        $this->load->model('class_model');    
        $this->load->model('student_model');  
        $this->load->model('section_model');
        $this->load->model('subject_model');
        $this->load->model('mark_model');
        $this->load->model('exam_model');
        $this->load->model('examresult_model');
        $this->load->model('examschedule_model');
        $this->load->helper(['url', 'form']);
    }

    public function report()
    {
        if (!$this->rbac->hasPrivilege('exam', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'End Term Report');
        $this->session->set_userdata('sub_menu', 'endofterm/report');

        $data['settinglist'] = $this->setting_model->get();
        $data['levels'] = $this->class_model->get();
        $data['studentlist'] = $this->student_model->get();
        $section_result = $this->section_model->get();
        $data['sectionlist'] = $section_result;
        $data['exams'] = $this->exam_model->get_exams();
        $data['terms'] = ['Term 1', 'Term 2', 'Term 3'];
        
        $this->load->view('layout/header', $data);
        $this->load->view('reports/endtermreport', $data);
        $this->load->view('layout/footer', $data);
    }

   public function generate_report()
{
    $term         = $this->input->post('term');
    $class_id     = $this->input->post('class_id');
    $section_id   = $this->input->post('section_id');
    $student_from = $this->input->post('student_from');
    $student_to   = $this->input->post('student_to');
    $exam_id      = $this->input->post('exam_id');

    if (empty($term) || empty($class_id) || empty($section_id) || empty($student_from) || empty($student_to) || empty($exam_id)) {
        echo json_encode(['success' => false, 'message' => 'Please select all required fields.']);
        return;
    }

    // ------------------------------------------------
    // GET STUDENTS IN RANGE FOR SELECTED CLASS & SECTION
    // ------------------------------------------------
    $students = $this->db
        ->select('s.*')
        ->from('students s')
        ->join('student_session ss', 'ss.student_id = s.id')
        ->where('ss.class_id', $class_id)
        ->where('ss.section_id', $section_id)
        ->where('s.id >=', $student_from)
        ->where('s.id <=', $student_to) // this ensures the range
      // optional: keep in ascending order
        ->get()
        ->result_array();

    if (empty($students)) {
        echo json_encode(['success' => false, 'message' => 'No students found in this class/section for the selected range.']);
        return;
    }

    $class   = $this->class_model->get($class_id);
    $section = $this->section_model->get($section_id);
    $exam    = $this->exam_model->get($exam_id);
    $settings = $this->setting_model->get(); // school info

    $reports = [];

    foreach ($students as $student) {
        $subjects_marks = $this->get_student_marks($student['id'], $exam_id);

        if (empty($subjects_marks)) continue;

        $total_actual = array_sum(array_column($subjects_marks, 'actual_mark'));
        $total_possible = array_sum(array_column($subjects_marks, 'possible_mark'));

        $reports[] = [
            'student_name'    => $student['firstname'] . ' ' . $student['lastname'],
            'admission_no'    => $student['admission_no'] ?? '',
            'class_name'      => $class['class'] ?? '',
            'section_name'    => $section['section'] ?? '',
            'exam_name'       => $exam['name'] ?? 'Exam',
            'term'            => $term,
            'year'            => date('Y'),
            'subjects_marks'  => $subjects_marks,
            'total_actual'    => $total_actual,
            'total_possible'  => $total_possible,
            'teacher_comment' => $this->generate_teacher_comment($total_actual, $total_possible),
            'head_comment'    => $this->generate_head_comment($total_actual, $total_possible),
            'school_logo'     => !empty($settings[0]['image']) ? base_url('uploads/school_content/logo/' . $settings[0]['image']) : '',
            'school_name'     => $settings[0]['name'] ?? '',
            'school_address'  => $settings[0]['address'] ?? '',
            'school_phone'    => $settings[0]['phone'] ?? '',
        ];
    }

    echo json_encode(['success' => true, 'students' => $reports]);
    exit;
}

/**
 * Fetch marks for a student for a specific exam
 */
private function get_student_marks($student_id, $exam_id)
{
    $this->db->select('
        er.get_marks AS actual_mark,
        es.exam_id,
        es.passing_marks,
        es.full_marks,
        s.name AS subject_name
    ');
    $this->db->from('exam_results er');
    $this->db->join('exam_schedules es', 'es.id = er.exam_schedule_id');
    $this->db->join('teacher_subjects ts', 'ts.id = es.teacher_subject_id');
    $this->db->join('subjects s', 's.id = ts.subject_id');

    $this->db->where('er.student_id', $student_id);
    $this->db->where('es.exam_id', $exam_id);
    $this->db->where('er.attendence', 'pre'); // optional

    $query = $this->db->get();
    $marks_data = [];

    foreach ($query->result_array() as $row) {
        $grade_row = $this->get_grade_from_db($row['actual_mark']);

       $subject_comment = $this->generate_subject_comment(
            $row['actual_mark'], 
            $row['passing_marks']
        );

        $marks_data[] = [
            'subject'           => $row['subject_name'],
            'actual_mark'       => $row['actual_mark'],
            'possible_mark'     => $row['full_marks'],
            'pass_mark'         => $row['passing_marks'],
            'grade'             => $grade_row['name'] ?? '',
            'grade_description' => $grade_row['description'] ?? '',
            'comment'           => $subject_comment
        ];

    }

    return $marks_data; // ✅ return the array
}


private function get_grade_from_db($mark)
{
    $this->db->where('mark_from <=', $mark);
    $this->db->where('mark_upto >=', $mark);
    $query = $this->db->get('grades'); // your grades table
    return $query->row_array(); // returns ['name'=>'A', 'description'=>'Excellent']
}
private function generate_subject_comment($mark, $pass_mark)
{
    $percentage = ($mark / 100) * 100; // since full mark is 100

    if ($mark >= 85) {
        return "Excellent understanding of the subject.";
    } elseif ($mark >= 70) {
        return "Very good performance in this subject.";
    } elseif ($mark >= $pass_mark) {
        return "Satisfactory performance. Can improve with more effort.";
    } else {
        return "Below expected standard. Needs improvement and more practice.";
    }
}


    private function generate_teacher_comment($total_actual, $total_possible)
    {
        $percentage = ($total_actual / $total_possible) * 100;
        
        if($percentage >= 85) {
            return "Excellent performance! Shows consistent dedication and understanding of all subjects. Maintain this outstanding work ethic.";
        } elseif($percentage >= 70) {
            return "Very good performance. Demonstrates strong understanding of most concepts. Continue working hard for even better results.";
        } elseif($percentage >= 60) {
            return "Satisfactory performance. Shows improvement but needs to focus more on weak areas. Keep pushing forward.";
        } else {
            return "Needs improvement. Should dedicate more time to studies and seek help in challenging subjects.";
        }
    }

    private function generate_head_comment($total_actual, $total_possible)
    {
        $percentage = ($total_actual / $total_possible) * 100;
        
        if($percentage >= 85) {
            return "Outstanding academic achievement! A model student who exemplifies excellence. Continue to shine.";
        } elseif($percentage >= 70) {
            return "Commendable performance. Shows great potential for further improvement. Keep up the good work.";
        } elseif($percentage >= 60) {
            return "Satisfactory progress. With more effort and focus, can achieve better results next term.";
        } else {
            return "Requires immediate attention and additional support. Parents are encouraged to monitor progress closely.";
        }
    }
}
?>