<?php
/**
 * Fee Collection Form
 *
 * Upload to: /gmind/branch/Views/fees/collect.php
 */

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$csrf = htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8');

$courseFee = (float)($student['course_fee'] ?? 0);
$feePaid   = (float)($student['fee_paid'] ?? 0);
$feeDue    = (float)($student['fee_due'] ?? 0);
?>
<style>
    .fee-form-card { background:#fff; border-radius:12px; box-shadow:0 2px 8px rgba(0,0,0,0.06); margin-bottom:18px; }
    .fee-form-card .card-header { background:linear-gradient(135deg,#16a085,#117a65); color:#fff; border-radius:12px 12px 0 0 !important; padding:16px 22px; font-weight:700; }
    .fee-form-card .card-body { padding:24px; }
    .info-banner { background:linear-gradient(135deg, rgba(22,160,133,0.08), rgba(17,122,101,0.04)); border-left:4px solid #16a085; padding:14px 18px; border-radius:8px; margin-bottom:20px; }
    .form-label { font-weight:600; color:#2c1e4a; font-size:0.9rem; margin-bottom:6px; }
    .form-control, .form-select { border-radius:8px; padding:10px 12px; border:1px solid #d0d5dd; }
    .form-control:focus, .form-select:focus { border-color:#16a085; box-shadow:0 0 0 3px rgba(22,160,133,0.1); }
    .btn-submit { background:linear-gradient(135deg,#16a085,#117a65); color:#fff; padding:14px 32px; border:none; border-radius:8px; font-weight:700; font-size:1rem; cursor:pointer; }
    .btn-submit:hover { transform:translateY(-1px); box-shadow:0 4px 12px rgba(22,160,133,0.3); }
    .btn-cancel { background:#f3f4f6; color:#6b7280; padding:14px 28px; border-radius:8px; text-decoration:none; font-weight:600; }
    .summary-row { display:flex; justify-content:space-between; padding:8px 0; border-bottom:1px dashed #e5e7eb; font-size:0.9rem; }
    .summary-row:last-child { border-bottom:none; }
    .summary-row .label { color:#6b7280; }
    .summary-row .value { font-weight:700; color:#2c1e4a; }
</style>

<div class="container-fluid py-4">
    <div style="margin-bottom:14px;">
        <a href="<?= $bp ?>/branch/fees" style="color:#16a085;text-decoration:none;font-size:0.88rem;">
            <i class="fas fa-arrow-left"></i> Back to Fee Dashboard
        </a>
    </div>

    <h2 style="color:#0d3b3b; font-weight:700; margin-bottom:6px;">
        <i class="fas fa-hand-holding-usd"></i> Collect Fee
    </h2>
    <p class="text-muted mb-3" style="font-size:0.9rem;">
        Student: <strong><?= htmlspecialchars($student['name'] ?? '', ENT_QUOTES) ?></strong>
        (<?= htmlspecialchars($student['enrollment_no'] ?? '', ENT_QUOTES) ?>)
    </p>

    <div class="info-banner">
        <strong>Course Fee:</strong> &#8377; <?= number_format($courseFee, 2) ?> |
        <strong>Already Paid:</strong> &#8377; <?= number_format($feePaid, 2) ?> |
        <strong>Balance Due:</strong> &#8377; <?= number_format($feeDue, 2) ?>
    </div>

    <?php if ($feeDue <= 0): ?>
    <div style="background:linear-gradient(135deg,#16a34a,#15803d); color:#fff; padding:20px; border-radius:10px; text-align:center; margin-bottom:20px;">
        <i class="fas fa-check-circle" style="font-size:2rem;"></i>
        <h3 style="margin:10px 0 4px;">FULL FEE PAID</h3>
        <p style="margin:0; opacity:0.95;">This student has cleared all dues. No further collection allowed.</p>
    </div>
    <div style="text-align:center;">
        <a href="<?= $bp ?>/branch/students/<?= (int)$student['id'] ?>" class="btn-cancel">
            <i class="fas fa-arrow-left"></i> Back to Student
        </a>
        <a href="<?= $bp ?>/branch/fees" class="btn-cancel">
            <i class="fas fa-rupee-sign"></i> Fee Dashboard
        </a>
    </div>
    <?php else: ?>

    <div class="row">
        <!-- Form Column -->
        <div class="col-md-7">
            <div class="card fee-form-card">
                <div class="card-header">
                    <i class="fas fa-credit-card"></i> Payment Details
                </div>
                <div class="card-body">
                    <form method="POST" action="<?= $bp ?>/branch/fees/collect/<?= (int)$student['id'] ?>/store" id="feeForm" onsubmit="return validateAmount();">
                        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">

                        <div class="mb-3">
                            <label class="form-label">Amount (&#8377;) <span style="color:#dc2626;">*</span></label>
                            <input type="number" name="amount" id="amountInput" class="form-control" required min="1" step="0.01"
                                   value="<?= htmlspecialchars(number_format($feeDue, 2, '.', ''), ENT_QUOTES) ?>"
                                   max="<?= htmlspecialchars(number_format($feeDue, 2, '.', ''), ENT_QUOTES) ?>"
                                   oninput="checkAmount();">
                            <small class="text-muted">
                                <i class="fas fa-info-circle"></i> Maximum allowed: <strong>&#8377; <?= number_format($feeDue, 2) ?></strong> (balance due). Partial payments allowed.
                            </small>
                            <small id="amountError" style="color:#dc2626; font-size:0.78rem; display:none; margin-top:4px;">
                                <i class="fas fa-exclamation-triangle"></i> Amount cannot exceed balance due.
                            </small>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Payment Mode</label>
                                <select name="payment_mode" class="form-select" id="paymentMode">
                                    <option value="cash">Cash</option>
                                    <option value="online">Online</option>
                                    <option value="upi">UPI</option>
                                    <option value="wallet">Wallet</option>
                                    <option value="cheque">Cheque</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Payment Date</label>
                                <input type="date" name="payment_date" class="form-control" value="<?= date('Y-m-d') ?>">
                            </div>
                        </div>

                        <div class="mb-3" id="txnIdGroup" style="display:none;">
                            <label class="form-label">Transaction ID / Cheque No</label>
                            <input type="text" name="transaction_id" class="form-control" placeholder="Enter transaction reference">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Remarks (Optional)</label>
                            <textarea name="remarks" class="form-control" rows="2" placeholder="Any notes about this payment..."></textarea>
                        </div>

                        <div class="d-flex justify-content-between flex-wrap gap-2 mt-4">
                            <a href="<?= $bp ?>/branch/fees" class="btn-cancel">
                                <i class="fas fa-times"></i> Cancel
                            </a>
                            <button type="submit" class="btn-submit">
                                <i class="fas fa-check"></i> Collect &amp; Generate Receipt
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Payment History Column -->
        <div class="col-md-5">
            <div class="card fee-form-card">
                <div class="card-header" style="background:linear-gradient(135deg,#6c3fe8,#4a2db8);">
                    <i class="fas fa-history"></i> Payment History
                </div>
                <div class="card-body">
                    <?php if (!empty($payments)): ?>
                        <?php foreach ($payments as $p): ?>
                        <div class="summary-row">
                            <div>
                                <div style="font-weight:600; color:#2c1e4a;">
                                    &#8377; <?= number_format((float)$p['amount'], 2) ?>
                                </div>
                                <div class="text-muted" style="font-size:0.78rem;">
                                    <?= !empty($p['payment_date']) ? date('d M Y', strtotime($p['payment_date'])) : '—' ?>
                                    | <?= htmlspecialchars(ucfirst($p['payment_mode'] ?? 'cash'), ENT_QUOTES) ?>
                                </div>
                                <?php if (!empty($p['receipt_no'])): ?>
                                <div class="text-muted" style="font-size:0.75rem;"><?= htmlspecialchars($p['receipt_no'], ENT_QUOTES) ?></div>
                                <?php endif; ?>
                            </div>
                            <div>
                                <a href="<?= $bp ?>/branch/fees/receipt/<?= (int)$p['id'] ?>" target="_blank" class="btn-fee-action" style="background:#dbeafe; color:#2563eb; padding:5px 10px; border-radius:6px; font-size:0.75rem; text-decoration:none;">
                                    <i class="fas fa-file-pdf"></i>
                                </a>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="text-align:center; padding:30px 10px; color:#9ca3af;">
                            <i class="fas fa-inbox" style="font-size:2rem; opacity:0.3;"></i>
                            <p class="mt-2 mb-0">No previous payments.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// Show transaction ID field for non-cash modes
document.getElementById('paymentMode')?.addEventListener('change', function() {
    const txnGroup = document.getElementById('txnIdGroup');
    if (this.value === 'cash') {
        txnGroup.style.display = 'none';
    } else {
        txnGroup.style.display = 'block';
    }
});

// Amount validation — cannot exceed balance due
const maxAmount = <?= json_encode((float)$feeDue) ?>;
const amountInput = document.getElementById('amountInput');
const amountError = document.getElementById('amountError');

function checkAmount() {
    if (!amountInput || !amountError) return;
    const val = parseFloat(amountInput.value) || 0;
    if (val > maxAmount) {
        amountError.style.display = 'block';
        amountError.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Amount (₹' + val.toFixed(2) + ') exceeds balance due (₹' + maxAmount.toFixed(2) + '). Maximum allowed: ₹' + maxAmount.toFixed(2);
    } else {
        amountError.style.display = 'none';
    }
}

function validateAmount() {
    if (!amountInput) return true; // form hidden (full paid)
    const val = parseFloat(amountInput.value) || 0;
    if (val <= 0) {
        alert('Amount must be greater than zero.');
        return false;
    }
    if (val > maxAmount) {
        alert('Amount (₹' + val.toFixed(2) + ') exceeds balance due (₹' + maxAmount.toFixed(2) + '). Maximum allowed: ₹' + maxAmount.toFixed(2));
        amountInput.value = maxAmount.toFixed(2);
        return false;
    }
    return true;
}
</script>
