<?php
include('../includes/db.php');

$response = array('status' => 'error', 'message' => 'Unknown error');

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $class_id = intval($_POST['class_id']);
    $section_id = intval($_POST['section_id']);
    $exam_id = intval($_POST['exam_id']);
    $subject_id = intval($_POST['subject_id']);
    $academic_year = isset($_POST['academic_year']) ? $_POST['academic_year'] : '';
    
    // Validate inputs
    if(empty($class_id) || empty($section_id) || empty($exam_id) || empty($subject_id)) {
        $response['message'] = 'All required fields must be filled';
        echo json_encode($response);
        exit;
    }
    
    // Get class, section, exam, and subject details
    $class_query = "SELECT class FROM classes WHERE class_id = ?";
    $stmt = $conn->prepare($class_query);
    $stmt->bind_param("i", $class_id);
    $stmt->execute();
    $class_result = $stmt->get_result()->fetch_assoc();
    $class_name = $class_result['class'];
    $stmt->close();
    
    $section_query = "SELECT section_name FROM sections WHERE section_id = ?";
    $stmt = $conn->prepare($section_query);
    $stmt->bind_param("i", $section_id);
    $stmt->execute();
    $section_result = $stmt->get_result()->fetch_assoc();
    $section_name = $section_result['section_name'];
    $stmt->close();
    
    $exam_query = "SELECT exam_type, exm_year FROM examination_type WHERE id = ?";
    $stmt = $conn->prepare($exam_query);
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $exam_result = $stmt->get_result()->fetch_assoc();
    $exam_name = $exam_result['exam_type'] . ' - ' . $exam_result['exm_year'];
    $stmt->close();
    
    $subject_query = "SELECT subject_code, subject_name, theory_full_marks, internal_full_marks 
                     FROM subjects WHERE id = ?";
    $stmt = $conn->prepare($subject_query);
    $stmt->bind_param("i", $subject_id);
    $stmt->execute();
    $subject_result = $stmt->get_result()->fetch_assoc();
    $subject_code = $subject_result['subject_code'];
    $subject_name = $subject_result['subject_name'];
    $theory_marks = intval($subject_result['theory_full_marks']);
    $internal_marks = intval($subject_result['internal_full_marks']);
    $stmt->close();
    
    // Get academic year ID
    if(empty($academic_year)) {
        $current_year = date('Y');
        $next_year = $current_year + 1;
        $academic_year = $current_year . '-' . $next_year;
    }
    
    // Get academic_year_id
    $year_query = "SELECT year_id FROM academic_years WHERE ay_ad LIKE ? OR ay_ad = ?";
    $year_stmt = $conn->prepare($year_query);
    $search_year = "%" . explode('-', $academic_year)[0] . "%";
    $year_stmt->bind_param("ss", $search_year, $academic_year);
    $year_stmt->execute();
    $year_result = $year_stmt->get_result();
    $academic_year_id = $year_result->num_rows > 0 ? $year_result->fetch_assoc()['year_id'] : null;
    $year_stmt->close();
    
    // Get students in this class-section
    $student_query = "SELECT s.student_id, s.regd_id, s.symbol_no, s.name as student_name, 
                             s.photo, scsd.class_id, scsd.section_id
                      FROM students s
                      JOIN student_class_section_data scsd ON s.student_id = scsd.student_id
                      WHERE scsd.class_id = ? 
                        AND scsd.section_id = ?
                        AND scsd.status = 'active'
                      ORDER BY s.student_id, s.name";
    
    $stmt = $conn->prepare($student_query);
    $stmt->bind_param("ii", $class_id, $section_id);
    $stmt->execute();
    $student_result = $stmt->get_result();
    
    $students = array();
    while($row = $student_result->fetch_assoc()) {
        // Get existing marks from marks table
        $marks_query = "SELECT marks, mark_type, full_marks
                       FROM marks 
                       WHERE student_id = ? 
                         AND exam_type = ? 
                         AND subject_id = ? 
                         AND class_id = ? 
                         AND section_id = ?
                         AND (academic_year_id = ? OR academic_year_id IS NULL OR academic_year_id = '')";
        
        $marks_stmt = $conn->prepare($marks_query);
        $marks_stmt->bind_param("iiiiii", $row['student_id'], $exam_id, $subject_id, $class_id, $section_id, $academic_year_id);
        $marks_stmt->execute();
        $marks_result = $marks_stmt->get_result();
        
        // Initialize mark variables
        $row['theory_marks'] = '';
        $row['internal_marks'] = ''; // Will use 'practical' mark_type for internal marks
        $row['remarks'] = '';
        
        if($marks_result->num_rows > 0) {
            while($mark_row = $marks_result->fetch_assoc()) {
                if($mark_row['mark_type'] == 'theory') {
                    $row['theory_marks'] = $mark_row['marks'];
                } elseif($mark_row['mark_type'] == 'practical') {
                    $row['internal_marks'] = $mark_row['marks']; // 'practical' type stores internal marks
                }
                $row['remarks'] = $mark_row['remarks'];
            }
        }
        
        $marks_stmt->close();
        
        // Use symbol_no as roll number if available
        $row['roll_no'] = $row['symbol_no'] ?: $row['student_id'];
        $students[] = $row;
    }
    $stmt->close();
    
    // Prepare response data
    $response['status'] = 'success';
    $response['data'] = array(
        'class_name' => $class_name,
        'section_name' => $section_name,
        'exam_name' => $exam_name,
        'subject_name' => $subject_name,
        'subject_code' => $subject_code,
        'academic_year' => $academic_year,
        'full_marks_theory' => $theory_marks,
        'full_marks_internal' => $internal_marks,
        'has_theory' => $theory_marks > 0,
        'has_internal' => $internal_marks > 0,
        'total_students' => count($students),
        'students' => $students
    );
} else {
    $response['message'] = 'Invalid request method';
}

echo json_encode($response);
?>