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

$response = ['status' => 'error', 'fees' => [], 'students' => []];

$class_id = $_GET['class_id'] ?? null;
$session_id = $_GET['session_id'] ?? null;
$medium_id = $_GET['medium_id'] ?? null;

// Validation: Medium is now a required filter for accurate assignment
if (!$class_id || !$session_id || !$medium_id) {
    echo json_encode(['status' => 'error', 'message' => 'Class, Session, and Medium are required.']);
    exit;
}

try {
    /**
     * 1. Fetch Fees
     * Filter by Class, Session, and MEDIUM. (Stream logic removed)
     */
    $feeSql = "SELECT id, fee_title, amount 
               FROM fee_types 
               WHERE class_id = :class_id 
               AND academic_year_id = :session_id
               AND medium_id = :medium_id
               AND status = 1";
               
    $feeStmt = $pdo->prepare($feeSql);
    $feeStmt->execute([
        ':class_id' => $class_id, 
        ':session_id' => $session_id,
        ':medium_id' => $medium_id
    ]);
    $response['fees'] = $feeStmt->fetchAll(PDO::FETCH_ASSOC);

   /**
     * 2. Fetch Students
     * Joined with enrollments and mediums. (Stream logic removed)
     */
    $studentSql = "SELECT 
            s.id, 
            e.roll_no, 
            s.student_name,
            e.promotion_status,
            m.medium_name 
        FROM enrollments e
        JOIN students s ON e.student_id = s.id
        LEFT JOIN mediums m ON e.medium_id = m.id
        WHERE e.class_id = :class_id 
          AND e.academic_year_id = :session_id 
          AND e.medium_id = :medium_id
          AND s.status = '1'
          AND e.promotion_status != 'dropped'
        ORDER BY CAST(e.roll_no AS UNSIGNED) ASC";

    $stuStmt = $pdo->prepare($studentSql);
    $stuStmt->execute([
        ':class_id' => $class_id, 
        ':session_id' => $session_id,
        ':medium_id' => $medium_id
    ]);
    $response['students'] = $stuStmt->fetchAll(PDO::FETCH_ASSOC);

    $response['status'] = 'success';

} catch (PDOException $e) {
    $response['message'] = 'Database Error: ' . $e->getMessage();
}

echo json_encode($response);
?>