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

$student_id = $_GET['student_id'] ?? 0;

try {
    // 1. Fetch School Name from school_setting table
    $stmtSchool = $pdo->prepare("SELECT school_name FROM school_settings LIMIT 1");
    $stmtSchool->execute();
    $school = $stmtSchool->fetch(PDO::FETCH_ASSOC);
    $schoolName = $school['school_name'] ?? 'Our School';

    // 2. Fetch Student Details
    $stmtUser = $pdo->prepare("
        SELECT s.student_name, s.parent_phone 
        FROM students s
        JOIN enrollments e ON s.id = e.student_id
        WHERE s.id = ? 
        LIMIT 1
    ");
    $stmtUser->execute([$student_id]);
    $student = $stmtUser->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        echo json_encode(["status" => false, "msg" => "Student not found in active enrollments."]);
        exit;
    }

    // 3. Fetch Unpaid Fees (Current and Past only)
    $sqlFees = "SELECT 
                    ft.fee_title, 
                    fa.due_date,
                    fa.due_month,
                    CASE 
                        WHEN fa.remaining_amount > 0 THEN fa.remaining_amount 
                        ELSE fa.total_amount 
                    END as balance 
                FROM fee_assign fa
                JOIN fee_types ft ON fa.fee_type_id = ft.id
                WHERE fa.student_id = :sid 
                AND fa.payment_status = 'unpaid'
                AND (fa.remaining_amount > 0 OR fa.total_amount > 0)
                AND fa.due_date <= CURRENT_DATE"; 
    
    $stmtFees = $pdo->prepare($sqlFees);
    $stmtFees->execute([':sid' => $student_id]);
    $fees = $stmtFees->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        "status" => true,
        "school_name" => $schoolName,
        "student_name" => $student['student_name'],
        "parent_phone" => $student['parent_phone'],
        "data" => $fees
    ]);

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