<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once '../ai/fee_balance.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }

$conn = portalGetConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }
$parentId = (int) $_SESSION['parent_id'];
$children = portalGetChildren($conn, $parentId);
$selectedChildId = (int) ($_GET['child_id'] ?? ($children[0]['id'] ?? 0));
if ($selectedChildId > 0 && !portalParentOwnsStudent($conn, $parentId, $selectedChildId)) {
    header('Location: dashboard.php?error=unauthorized');
    exit;
}
$student = $selectedChildId > 0 ? portalGetStudent($conn, $selectedChildId, $parentId) : null;
$year = portalCurrentYear($conn);
$feeBreakdown = [];
$paymentHistory = [];
$feedingSummary = [];
$totals = ['total_fees' => 0.0, 'total_paid' => 0.0, 'total_outstanding' => 0.0];
$availableCredit = $student ? rbcAvailableCredit($conn, $selectedChildId) : 0.0;

if ($student) {
    $className = (string) ($student['class'] ?? '');
    foreach (rbcStudentFeeBreakdown($conn, $selectedChildId, $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, transaction_id AS receipt_number, amount_paid, payment_method, payment_date,
                'success' AS status
         FROM payments
         WHERE student_id = ?
         ORDER BY payment_date DESC, id DESC
         LIMIT 20"
    );
    $payStmt->bind_param('i', $selectedChildId);
    $payStmt->execute();
    $payResult = $payStmt->get_result();
    while ($row = $payResult->fetch_assoc()) { $paymentHistory[] = $row; }
    $payStmt->close();

    $feedStmt = $conn->prepare(
        "SELECT week_start, amount_paid, paid_at AS payment_date
         FROM weekly_feeding_payments
         WHERE student_id = ?
         ORDER BY week_start DESC
         LIMIT 12"
    );
    $feedStmt->bind_param('i', $selectedChildId);
    $feedStmt->execute();
    $feedResult = $feedStmt->get_result();
    while ($row = $feedResult->fetch_assoc()) { $feedingSummary[] = $row; }
    $feedStmt->close();
}

echo portalPageStart('Fees', 'fees', 'Fee Statement');
?>
<?= portalChildSwitcher($children, $selectedChildId, 'fees.php') ?>

<div class="portal-summary-grid">
    <div class="portal-summary-card total"><div class="small">Total Fees</div><div class="value"><?= portalFormatCurrency($totals['total_fees']) ?></div></div>
    <div class="portal-summary-card paid"><div class="small">Paid</div><div class="value"><?= portalFormatCurrency($totals['total_paid']) ?></div></div>
    <div class="portal-summary-card outstanding"><div class="small">Outstanding</div><div class="value"><?= portalFormatCurrency($totals['total_outstanding']) ?></div></div>
    <?php if ($availableCredit > 0.005): ?>
    <div class="portal-summary-card paid"><div class="small">Available Credit</div><div class="value"><?= portalFormatCurrency($availableCredit) ?></div></div>
    <?php endif; ?>
</div>
<?php if ($availableCredit > 0.005): ?>
<div class="alert alert-success py-2 small mb-3">
    <i class="fas fa-hand-holding-usd me-1"></i>
    You have <?= portalFormatCurrency($availableCredit) ?> in available credit. Contact the school office to have it applied to your next payment.
</div>
<?php endif; ?>

<div class="portal-card">
    <div class="portal-section-title d-flex justify-content-between align-items-center flex-wrap gap-2">
        <span>Fee Breakdown</span>
        <?php if ($totals['total_outstanding'] > 0 && hasModule('online_payments')): ?>
        <div class="d-flex gap-2">
            <a href="checkout.php?student_id=<?= $selectedChildId ?>&child_id=<?= $selectedChildId ?>&scope=term" class="btn btn-sm btn-primary">
                Pay <?= htmlspecialchars(getCurrentTerm()) ?> in Full
            </a>
            <a href="checkout.php?student_id=<?= $selectedChildId ?>&child_id=<?= $selectedChildId ?>&scope=all" class="btn btn-sm btn-outline-primary">
                Pay All Outstanding
            </a>
        </div>
        <?php endif; ?>
    </div>
<?php
$_ps_code    = getSettingValue('paystack_subaccount_code');
$_ps_enabled = getSettingValue('paystack_split_enabled');
if (!empty($_ps_code) && $_ps_enabled === '1'): ?>
    <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:6px;padding:8px 12px;margin-bottom:12px;font-size:0.85rem;color:#1e40af;">
        &#x1F512; Online payments are processed securely by Paystack and settle directly to
        <strong><?= htmlspecialchars((string)(getSettingValue('school_name') ?? 'the school')) ?></strong>.
    </div>
<?php endif; ?>
    <div class="portal-table-wrap">
        <table class="portal-table">
            <thead><tr><th>Fee Type</th><th>Amount</th><th>Paid</th><th>Balance</th><th>Due Date</th><th>Status</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($feeBreakdown as $fee): $status = ((float) $fee['balance'] <= 0) ? 'Paid' : (((float) $fee['paid'] > 0) ? 'Partial' : 'Unpaid'); ?>
                <tr>
                    <td><?= htmlspecialchars((string) $fee['fee_type']) ?></td>
                    <td><?= portalFormatCurrency((float) $fee['amount']) ?></td>
                    <td><?= portalFormatCurrency((float) $fee['paid']) ?></td>
                    <td><?= portalFormatCurrency((float) $fee['balance']) ?></td>
                    <td><?= htmlspecialchars((string) $fee['due_date']) ?></td>
                    <td><span class="portal-badge <?= strtolower($status) ?>"><?= htmlspecialchars($status) ?></span></td>
                    <td>
                        <?php if ((float) $fee['balance'] > 0): ?>
                            <a href="checkout.php?student_id=<?= $selectedChildId ?>&fee_ids=<?= urlencode((string) $fee['id']) ?>&child_id=<?= $selectedChildId ?>" class="btn btn-sm btn-outline-primary">Pay Online</a>
                        <?php else: ?>
                            <span class="portal-muted small">Settled</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$feeBreakdown): ?><tr><td colspan="7" class="portal-muted">No fees found.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="portal-card">
    <div class="portal-section-title">Payment History</div>
    <div class="portal-table-wrap">
        <table class="portal-table">
            <thead><tr><th>Date</th><th>Receipt No</th><th>Amount</th><th>Method</th><th>Status</th><th>Receipt</th></tr></thead>
            <tbody>
            <?php foreach ($paymentHistory as $payment): ?>
                <tr>
                    <td><?= htmlspecialchars((string) $payment['payment_date']) ?></td>
                    <td><?= htmlspecialchars((string) ($payment['receipt_number'] ?? '')) ?></td>
                    <td><?= portalFormatCurrency((float) $payment['amount_paid']) ?></td>
                    <td><?= htmlspecialchars((string) ($payment['payment_method'] ?? '')) ?></td>
                    <td><?= htmlspecialchars((string) ($payment['status'] ?? 'paid')) ?></td>
                    <td><a href="../payment_receipt.php?payment_id=<?= (int) $payment['id'] ?>" target="_blank">View Receipt</a></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$paymentHistory): ?><tr><td colspan="6" class="portal-muted">No payment history found.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="portal-card">
    <div class="portal-section-title">Feeding Fee Weekly Summary</div>
    <div class="portal-table-wrap">
        <table class="portal-table">
            <thead><tr><th>Week</th><th>Amount Paid</th><th>Date Recorded</th></tr></thead>
            <tbody>
            <?php foreach ($feedingSummary as $feeding): ?>
                <tr>
                    <td><?= htmlspecialchars((string) $feeding['week_start']) ?></td>
                    <td><?= portalFormatCurrency((float) $feeding['amount_paid']) ?></td>
                    <td><?= htmlspecialchars((string) $feeding['payment_date']) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$feedingSummary): ?><tr><td colspan="3" class="portal-muted">No feeding fee payments found.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?= portalPageEnd('fees') ?>
