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

// 1. Capture parameters (Stream ID removed)
$class_id   = (int)($_GET['class_id']   ?? 0);
$section_id = (int)($_GET['section_id'] ?? 0);
$subject_id = (int)($_GET['subject_id'] ?? 0);
$term_id    = (int)($_GET['term_id']    ?? 0);
$medium_id  = (int)($_GET['medium']     ?? 0); 

// 2. Validation Logic
if (!$class_id || !$subject_id || !$term_id || !$medium_id) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required filters (Class, Subject, Term, or Medium).']);
    exit;
}

if (!defined('APP_YEAR_ID') || APP_YEAR_ID <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Academic year not set.']);
    exit;
}

try {
    // 3. Get max_marks for the specific term
    $stmtTerm = $pdo->prepare("SELECT max_marks FROM exam_terms WHERE id = ?");
    $stmtTerm->execute([$term_id]);
    $maxAllowed = $stmtTerm->fetchColumn() ?: 100;

    // 4. Handle Filters (Stream SQL removed)
    $sectionSQL = ($section_id > 0) ? " AND e.section_id = :sec " : "";
    $mediumSQL  = " AND e.medium_id = :med_id "; 

    $sql = "SELECT 
                s.id as student_id, 
                e.roll_no, 
                s.student_name,  
                m.theory_marks, 
                m.practical_marks
            FROM students s
            INNER JOIN enrollments e ON s.id = e.student_id
            LEFT JOIN marks_entry m ON s.id = m.student_id 
                AND m.subject_id = :sub 
                AND m.exam_term_id = :term
                AND m.academic_year_id = :year
            WHERE e.class_id = :class 
            $sectionSQL
            $mediumSQL
            AND e.academic_year_id = :year
            AND s.status = 1 
            ORDER BY CAST(e.roll_no AS UNSIGNED) ASC";

    $stmt = $pdo->prepare($sql);
    
    // 5. Construct Parameter Array (Stream parameter removed)
    $params = [
        ':sub'    => $subject_id,
        ':term'   => $term_id,
        ':class'  => $class_id,
        ':med_id' => $medium_id, 
        ':year'   => APP_YEAR_ID
    ];
    
    if ($section_id > 0) $params[':sec'] = $section_id;

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

    echo json_encode([
        'status' => 'success',
        'data' => $students,
        'max_allowed' => (int)$maxAllowed 
    ]);

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>