<?php
require_once 'config.php'; // Adjusted path

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

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

if (!isset($_GET['school_id']) || !is_numeric($_GET['school_id']) ||
    !isset($_GET['academic_year']) || empty($_GET['academic_year']) ||
    !isset($_GET['term_name']) || empty($_GET['term_name'])) {
    $response['message'] = 'Missing required parameters (school_id, academic_year, term_name).';
    echo json_encode($response);
    exit;
}

$school_id = $_GET['school_id'];
$academic_year = $_GET['academic_year'];
$term_name = $_GET['term_name'];

// Query classes that are active for the selected school, academic year, and term
// This involves joining with academic_years_terms and class_streams or similar
$sql = "SELECT DISTINCT c.class_id, c.class_name
        FROM classes c
        JOIN class_streams cs ON c.class_id = cs.class_id
        JOIN academic_years_terms ayt ON cs.academic_year_term_id = ayt.id
        WHERE c.school_id = ?
        AND ayt.academic_year = ?
        AND ayt.term_name = ?
        ORDER BY c.class_name";

if ($conn instanceof mysqli) {
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("iss", $school_id, $academic_year, $term_name);
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $response['data'][] = $row;
                }
                $response['success'] = true;
            } else {
                $response['message'] = 'No classes found for the given criteria.';
            }
        } else {
            $response['message'] = 'Failed to execute statement: ' . $stmt->error;
            error_log("SQL Execute Error (get_classes.php): " . $stmt->error);
        }
        $stmt->close();
    } else {
        $response['message'] = 'Failed to prepare statement: ' . $conn->error;
        error_log("SQL Prepare Error (get_classes.php): " . $conn->error);
    }
    $conn->close();
} else {
    $response['message'] = 'Database connection error.';
    error_log("Database connection \$conn not available in get_classes.php.");
}

echo json_encode($response);
?>