<?php
session_start();
require_once 'config.php'; // Ensure this path is correct

header('Content-Type: application/json');

$response = [
    'success' => false,
    'message' => 'Invalid request.',
    'data' => []
];

// --- MODIFICATION START ---
// Get academic_year and term from GET parameters
$academic_year = isset($_GET['academic_year']) ? (int)$_GET['academic_year'] : 0;
$term = isset($_GET['term']) ? trim($_GET['term']) : '';

// Add validation for academic_year and term
if ($academic_year === 0 || empty($term)) {
    $response['message'] = 'Academic year and term are required.';
    echo json_encode($response);
    exit();
}
// --- MODIFICATION END ---


if (isset($_GET['class_id']) && isset($_GET['stream']) && isset($_SESSION['school_id'])) {
    $class_id = (int)$_GET['class_id'];
    $stream = trim($_GET['stream']); // Trim whitespace from stream
    $school_id = (int)$_SESSION['school_id'];

    // Validate class_id belongs to the current school and get class_name
    $class_name = '';
    $sql_validate_class = "SELECT class_name FROM classes WHERE class_id = ? AND school_id = ?";
    if ($stmt_validate = $conn->prepare($sql_validate_class)) {
        $stmt_validate->bind_param("ii", $class_id, $school_id);
        $stmt_validate->execute();
        $stmt_validate->store_result();
        if ($stmt_validate->num_rows === 0) {
            $response['message'] = 'Unauthorized access or class not found.';
            echo json_encode($response);
            $stmt_validate->close();
            $conn->close();
            exit();
        }
        $stmt_validate->bind_result($class_name_db);
        $stmt_validate->fetch();
        $class_name = $class_name_db;
        $stmt_validate->close();
    } else {
        $response['message'] = 'Database error during class validation: ' . $conn->error;
        echo json_encode($response);
        $conn->close();
        exit();
    }

    // Fetch subjects assigned to this class and their assigned teachers for the specific stream
    // --- MODIFICATION START (SQL Query) ---
    // Added academic_year AND term to the LEFT JOIN conditions
    $sql = "SELECT cs.subject_id, s.subject_name,
                    (SELECT COUNT(st.user_id) FROM students st
                     WHERE st.class_id = ? AND st.school_id = ?
                       AND (st.stream = ? OR (st.stream IS NULL AND ? = ''))
                    ) AS student_count_in_stream,
                    cst1.teacher_user_id AS teacher1_id, u1.username AS teacher1_name,
                    cst2.teacher_user_id AS teacher2_id, u2.username AS teacher2_name,
                    cst3.teacher_user_id AS teacher3_id, u3.username AS teacher3_name
             FROM class_subjects cs
             JOIN subjects s ON cs.subject_id = s.subject_id
             LEFT JOIN class_subject_teachers cst1 ON cs.class_id = cst1.class_id
                AND cs.subject_id = cst1.subject_id
                AND cst1.stream = ?
                AND cst1.academic_year = ? -- NEW
                AND cst1.term = ?         -- NEW
                AND cst1.assignment_slot = 1
             LEFT JOIN users u1 ON cst1.teacher_user_id = u1.id
             LEFT JOIN class_subject_teachers cst2 ON cs.class_id = cst2.class_id
                AND cs.subject_id = cst2.subject_id
                AND cst2.stream = ?
                AND cst2.academic_year = ? -- NEW
                AND cst2.term = ?         -- NEW
                AND cst2.assignment_slot = 2
             LEFT JOIN users u2 ON cst2.teacher_user_id = u2.id
             LEFT JOIN class_subject_teachers cst3 ON cs.class_id = cst3.class_id
                AND cs.subject_id = cst3.subject_id
                AND cst3.stream = ?
                AND cst3.academic_year = ? -- NEW
                AND cst3.term = ?         -- NEW
                AND cst3.assignment_slot = 3
             LEFT JOIN users u3 ON cst3.teacher_user_id = u3.id
             WHERE cs.class_id = ? AND s.school_id = ?
             ORDER BY s.subject_name ASC";
    // --- MODIFICATION END (SQL Query) ---

    if ($stmt = $conn->prepare($sql)) {
        // --- MODIFICATION START (bind_param) ---
        // Original: "iisssssii" (9 params)
        // Now: We have the original 9, plus 3x (academic_year, term) = 6 new params for the LEFT JOINs
        // So, 9 + 6 = 15 parameters
        // Types:
        // class_id (int)
        // school_id (int)
        // stream (string)
        // stream (string)
        // cst1.stream (string)
        // cst1.academic_year (int) -- NEW
        // cst1.term (string)      -- NEW
        // cst2.stream (string)
        // cst2.academic_year (int) -- NEW
        // cst2.term (string)      -- NEW
        // cst3.stream (string)
        // cst3.academic_year (int) -- NEW
        // cst3.term (string)      -- NEW
        // cs.class_id (int)
        // s.school_id (int)
        // Total: 5 'i's and 10 's's -> "iisssisissisii"
        $stmt->bind_param("iisssisissisii",
            $class_id,             // 1. st.class_id
            $school_id,            // 2. st.school_id
            $stream,               // 3. st.stream (for student count)
            $stream,               // 4. (st.stream IS NULL AND ? = '') (for student count)
            $stream,               // 5. cst1.stream
            $academic_year,        // 6. cst1.academic_year -- NEW
            $term,                 // 7. cst1.term          -- NEW
            $stream,               // 8. cst2.stream
            $academic_year,        // 9. cst2.academic_year -- NEW
            $term,                 // 10. cst2.term         -- NEW
            $stream,               // 11. cst3.stream
            $academic_year,        // 12. cst3.academic_year -- NEW
            $term,                 // 13. cst3.term         -- NEW
            $class_id,             // 14. cs.class_id
            $school_id             // 15. s.school_id
        );
        // --- MODIFICATION END (bind_param) ---

        if ($stmt->execute()) {
            $result = $stmt->get_result();
            $subjects_data = [];
            while ($row = $result->fetch_assoc()) {
                $row['student_count'] = $row['student_count_in_stream'];
                unset($row['student_count_in_stream']);
                $subjects_data[] = $row;
            }
            $response['success'] = true;
            $response['message'] = 'Subjects and assigned teachers fetched successfully.';
            $response['data'] = $subjects_data;
        } else {
            $response['message'] = 'Error fetching subjects and teachers: ' . $stmt->error;
        }
        $stmt->close();
    } else {
        $response['message'] = 'Database error (prepare fetch subjects): ' . $conn->error;
    }

    $conn->close();
} else {
    // If initial GET parameters (class_id, stream, school_id) are missing
    $response['message'] = 'Class ID, stream, or school ID not provided.';
}

echo json_encode($response);
?>