<?php
header("Content-Type: application/json");
require("../../includes/config.php");

// Get input parameters
$class_id   = $_GET['class_id'] ?? '';
$section_id = $_GET['section_id'] ?? ''; 

if (empty($class_id)) {
    echo json_encode([]);
    exit;
}

try {
    // REMOVED: st.stream_name and JOIN on streams table
    $sql = "SELECT 
                s.id, 
                s.student_name, 
                e.roll_no, 
                e.promotion_status, 
                sec.section_name
            FROM students s
            JOIN enrollments e ON s.id = e.student_id
            LEFT JOIN sections sec ON e.section_id = sec.id
            WHERE e.class_id = :class_id 
            AND e.academic_year_id = :year_id";

    $params = [
        ':class_id' => $class_id,
        ':year_id'  => APP_YEAR_ID
    ];

    // Filter by section_id if provided
    if (!empty($section_id)) {
        $sql .= " AND e.section_id = :section_id";
        $params[':section_id'] = $section_id;
    }

    $sql .= " ORDER BY e.roll_no ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($students);
} catch (Exception $e) {
    // Error handling
    echo json_encode(["error" => $e->getMessage()]);
}
?>