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

/**
 * Get Global Academic Year ID from config.
 */
$global_year_id = defined('APP_YEAR_ID') ? APP_YEAR_ID : 0;

// Get Class ID from the request
$class_id = $_GET['class_id'] ?? '';

if (empty($class_id)) {
    echo json_encode(["status" => false, "msg" => "Class ID or 'all' is required."]);
    exit;
}

try {
    // 1. Updated SQL Query with Section and Medium Joins (Stream removed)
    $sql = "SELECT 
                s.id, 
                s.student_name, 
                s.student_photo, 
                s.parent_phone, 
                s.dob,
                e.roll_no, 
                c.class_name, 
                sec.section_name, 
                m.medium_name,    -- Added medium
                e.academic_year_id,
                ay.year_name
            FROM students s
            JOIN enrollments e ON s.id = e.student_id
            JOIN classes c ON e.class_id = c.id
            JOIN academic_years ay ON e.academic_year_id = ay.id
            LEFT JOIN sections sec ON e.section_id = sec.id
            LEFT JOIN mediums m ON e.medium_id = m.id    -- Added Join
            WHERE e.academic_year_id = :year_id";

    // Build query based on selection
    $params = [':year_id' => $global_year_id];

    if ($class_id !== 'all') {
        $sql .= " AND e.class_id = :class_id";
        $params[':class_id'] = $class_id;
    }

    // Sort by Class Name, then Section, then Roll No
    $sql .= " ORDER BY c.class_name ASC, sec.section_name ASC, e.roll_no ASC";

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

    if ($students) {
        echo json_encode([
            "status" => true,
            "count" => count($students),
            "data" => $students
        ]);
    } else {
        $error_msg = ($class_id === 'all') 
            ? "No students enrolled for this academic year." 
            : "No students found in this class.";
            
        echo json_encode([
            "status" => false, 
            "msg" => $error_msg
        ]);
    }

} catch (Exception $e) {
    echo json_encode([
        "status" => false, 
        "msg" => "Database error: " . $e->getMessage()
    ]);
}
?>