<?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()
{
    // Get form data
    $term       = $this->input->post('term');
    $class_id   = $this->input->post('class_id');      // Level
    $section_id = $this->input->post('section_id');    // Class/Section
    $student_id = $this->input->post('student_id');
    $exam_id    = $this->input->post('exam_id');

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

    // Get student info
    $student = $this->student_model->get($student_id);
    if (empty($student)) {
        echo json_encode(['success' => false, 'message' => 'Student not found.']);
        return;
    }

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


    // Get marks
    $subjects_marks = $this->get_student_marks($student_id, $exam_id);

    if (empty($subjects_marks)) {
        echo json_encode(['success' => false, 'message' => 'No marks found for this student.']);
        return;
    }

    // Calculate totals
    $total_actual   = 0;
    $total_possible = 0;

    foreach ($subjects_marks as $mark) {
        $total_actual   += $mark['actual_mark'];
        $total_possible += $mark['possible_mark'];
    }

    // Teacher & Head comments
    $teacher_comment = $this->generate_teacher_comment($total_actual, $total_possible);
    $head_comment    = $this->generate_head_comment($total_actual, $total_possible);

    // Prepare response
    $report_data = [
        'success'         => true,
        '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' => $teacher_comment,
        'head_comment'    => $head_comment
    ];

    // Send JSON response
    header('Content-Type: application/json');
    echo json_encode($report_data);
    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.";
        }
    }
}
?>