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

// Validate ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid Student ID"]);
    exit;
}

try {
    // REMOVED: e.stream_id from the SELECT list
    $sql = "SELECT 
                s.*, 
                e.roll_no, 
                e.class_id, 
                e.section_id, 
                e.medium_id,
                e.academic_year_id
            FROM students s
            LEFT JOIN enrollments e ON s.id = e.student_id
            WHERE s.id = :id 
            AND e.academic_year_id = :year_id 
            LIMIT 1";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':id' => $id,
        ':year_id' => APP_YEAR_ID // Ensure this constant exists in config.php
    ]);
    
    $student = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($student) {
        // Force success to true for the JS logic
        $student['success'] = true; 
        
        // Return clean JSON
        echo json_encode($student);
    } else {
        // Helpful debug: if student exists in 'students' table but not 'enrollments'
        echo json_encode([
            "success" => false, 
            "message" => "Student data found, but no enrollment record exists for the current academic year."
        ]);
    }

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