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

// Capture IDs from the JS fetch request
$sid = isset($_GET['student_id']) ? (int)$_GET['student_id'] : null;
$yid = (!empty($_GET['academic_year_id'])) ? (int)$_GET['academic_year_id'] : (defined('APP_YEAR_ID') ? APP_YEAR_ID : null);

try {
    if (!$sid) throw new Exception("No Student ID provided.");
    if (!$yid) throw new Exception("No Academic Year ID provided.");

    /* ==========================================================
       1. FETCH STUDENT INFO BASED ON ENROLLMENT YEAR
       Removed 'st.stream_name' and 'LEFT JOIN streams'
    ========================================================== */
    $studentSql = "SELECT 
            s.student_name, s.father_name, s.address,
            e.roll_no, e.academic_year_id,
            c.class_name, ay.year_name,
            ay.start_date as ay_start, ay.end_date as ay_end,
            sec.section_name,
            m.medium_name 
        FROM students s
        INNER JOIN enrollments e ON s.id = e.student_id
        INNER JOIN academic_years ay ON e.academic_year_id = ay.id
        INNER 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 = :sid 
        AND e.academic_year_id = :yid 
        LIMIT 1";
    
    $stmtS = $pdo->prepare($studentSql);
    $stmtS->execute([':sid' => $sid, ':yid' => $yid]);
    $studentInfo = $stmtS->fetch(PDO::FETCH_ASSOC);

    if (!$studentInfo) {
        throw new Exception("Student not found in enrollment records for the selected year.");
    }

    $filterStart = $_GET['start_date'] ?? $studentInfo['ay_start'];
    $filterEnd = $_GET['end_date'] ?? $studentInfo['ay_end'];

    /* ==========================================================
       2. FETCH FEE HISTORY
    ========================================================== */
    $historySql = "SELECT 
                        fa.id, fa.due_month, ft.fee_title, 
                        fa.total_amount as assigned_amount,
                        (SELECT IFNULL(SUM(amount_paid), 0) FROM fee_payments 
                         WHERE fee_assign_id = fa.id 
                         AND payment_date BETWEEN :start AND :end) as period_paid,
                        (SELECT IFNULL(SUM(discount_amount), 0) FROM fee_payments 
                         WHERE fee_assign_id = fa.id 
                         AND payment_date BETWEEN :start AND :end) as period_discount
                    FROM fee_assign fa
                    INNER JOIN fee_types ft ON fa.fee_type_id = ft.id
                    INNER JOIN enrollments e ON fa.student_id = e.student_id
                    WHERE fa.student_id = :sid 
                    AND e.academic_year_id = :yid
                    ORDER BY fa.id ASC";

    $stmtH = $pdo->prepare($historySql);
    $stmtH->execute([
        ':sid' => $sid, 
        ':yid' => $yid,
        ':start' => $filterStart,
        ':end' => $filterEnd
    ]);
    $history = $stmtH->fetchAll(PDO::FETCH_ASSOC);

    // 3. Summarize Data
    $summary = [
        "total_expected" => 0,
        "total_collected" => 0,
        "total_discount" => 0,
        "total_outstanding" => 0
    ];

    foreach ($history as $row) {
        $summary["total_expected"] += (float)$row['assigned_amount'];
        $summary["total_collected"] += (float)$row['period_paid'];
        $summary["total_discount"] += (float)$row['period_discount'];
    }
    $summary["total_outstanding"] = $summary["total_expected"] - ($summary["total_collected"] + $summary["total_discount"]);

    echo json_encode([
        "status" => "success",
        "details" => $studentInfo,
        "history" => $history,
        "financial_summary" => $summary
    ]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>