<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once dirname(__DIR__, 2) . '/ai/fee_balance.php';
require_once dirname(__DIR__) . '/helpers.php';
header('Content-Type: application/json');
if (!isset($_SESSION['parent_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
$conn = portalGetConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false]); exit; }
$studentId = (int) ($_POST['student_id'] ?? 0);
$parentId = (int) $_SESSION['parent_id'];
if (!portalParentOwnsStudent($conn, $parentId, $studentId)) {
    echo json_encode(['success'=>false, 'message'=>'Unauthorized']); exit;
}
$student = portalGetStudent($conn, $studentId, $parentId);
$year = portalCurrentYear($conn);
$feeBreakdown = [];
$paymentHistory = [];
$feedingSummary = [];
$totals = ['total_fees' => 0.0, 'total_paid' => 0.0, 'total_outstanding' => 0.0];
$className = (string) ($student['class'] ?? '');

foreach (rbcStudentFeeBreakdown($conn, $studentId, $className, $year) as $row) {
    $feeBreakdown[] = [
        'id'       => $row['id'],
        'fee_type' => $row['fee_type'],
        'amount'   => $row['amount'],
        'due_date' => $row['due_date'],
        'paid'     => $row['paid'],
        'balance'  => $row['remaining'],
    ];
    $totals['total_fees'] += $row['amount'];
    $totals['total_paid'] += $row['paid'];
    $totals['total_outstanding'] += $row['remaining'];
}

$payStmt = $conn->prepare("SELECT id, receipt_number, amount_paid, payment_method, payment_date, status FROM payments WHERE student_id = ? ORDER BY payment_date DESC");
$payStmt->bind_param('i', $studentId);
$payStmt->execute();
$payResult = $payStmt->get_result();
while ($row = $payResult->fetch_assoc()) { $paymentHistory[] = $row; }
$payStmt->close();
$feedStmt = $conn->prepare("SELECT week_start, amount_paid, payment_date FROM weekly_feeding_payments WHERE student_id = ? ORDER BY week_start DESC LIMIT 12");
$feedStmt->bind_param('i', $studentId);
$feedStmt->execute();
$feedResult = $feedStmt->get_result();
while ($row = $feedResult->fetch_assoc()) { $feedingSummary[] = $row; }
$feedStmt->close();
echo json_encode([
    'success' => true,
    'fee_breakdown' => $feeBreakdown,
    'payment_history' => $paymentHistory,
    'feeding_summary' => $feedingSummary,
    'total_fees' => $totals['total_fees'],
    'total_paid' => $totals['total_paid'],
    'total_outstanding' => $totals['total_outstanding'],
]);
