<?php
require("../../includes/config.php");

header('Content-Type: application/json');

// 1. Sanitize and Validate Input
$sid = isset($_GET['student_id']) ? (int)$_GET['student_id'] : null;
$yid = isset($_GET['year_id']) ? (int)$_GET['year_id'] : APP_YEAR_ID; 

if (!$sid || !$yid) {
    echo json_encode(['status' => 'error', 'message' => 'Valid Student ID and Year ID are required']);
    exit;
}

try {
    // 2. Get Student Details (Stream logic removed)
    $sStmt = $pdo->prepare("SELECT 
                                s.student_name, s.father_name,
                                s.id as student_id,
                                e.roll_no,
                                c.class_name,
                                sec.section_name,
                                m.medium_name 
                            FROM students s 
                            JOIN enrollments e ON s.id = e.student_id 
                            JOIN classes c ON e.class_id = c.id 
                            LEFT JOIN sections sec ON e.section_id = sec.id
                            LEFT JOIN mediums m ON e.medium_id = m.id
                            WHERE s.id = ? 
                            AND e.academic_year_id = ?
                            LIMIT 1");
    $sStmt->execute([$sid, $yid]);
    $student = $sStmt->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        echo json_encode(['status' => 'error', 'message' => 'Student enrollment not found for selected year']);
        exit;
    }

    // Ensure null fields return empty strings for clean JS display
    $student['section_name'] = $student['section_name'] ?? '';
    $student['medium_name'] = $student['medium_name'] ?? '';
    // REMOVED: stream_name cleanup

    // 3. Fetch Pending Fees
    $fStmt = $pdo->prepare("SELECT 
                                fa.id,
                                fa.fee_type_id,
                                fa.total_amount,
                                fa.remaining_amount,
                                fa.due_month,
                                ft.fee_title
                            FROM fee_assign fa
                            JOIN fee_types ft ON fa.fee_type_id = ft.id
                            JOIN enrollments e ON fa.student_id = e.student_id
                            WHERE fa.student_id = ? 
                            AND e.academic_year_id = ?
                            AND fa.remaining_amount > 0 
                            AND fa.payment_status != 'paid'");
    $fStmt->execute([$sid, $yid]);
    $fees = $fStmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'student' => $student,
        'pending_fees' => $fees
    ]);

} catch (PDOException $e) {
    error_log("Student Summary API Error: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Internal Server Error']);
}
?>