<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once dirname(__DIR__) . '/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.');
}

// Ensure coupon columns exist (added in coupon-integration release)
foreach ([
    'coupon_id'       => "ADD COLUMN coupon_id INT NULL DEFAULT NULL",
    'discount_amount' => "ADD COLUMN discount_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00",
    'original_amount' => "ADD COLUMN original_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00",
] as $col => $ddl) {
    $chk = $conn->query("SHOW COLUMNS FROM online_payments LIKE '{$col}'");
    if ($chk && $chk->num_rows === 0) {
        $conn->query("ALTER TABLE online_payments {$ddl}");
    }
}

$parentId = (int) $_SESSION['parent_id'];

function portalCheckoutE(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function portalNormalizeBaseUrlHost(string $baseUrl): string
{
    $trimmed = rtrim($baseUrl, '/');
    $host = parse_url($trimmed, PHP_URL_HOST);
    return $host ?: preg_replace('#^https?://#i', '', $trimmed) ?: 'localhost';
}

function portalPositiveIntArrayFromCsv(?string $csv): array
{
    if ($csv === null || trim($csv) === '') {
        return [];
    }
    $ids = [];
    foreach (explode(',', $csv) as $item) {
        $item = trim($item);
        if (ctype_digit($item) && (int) $item > 0) {
            $ids[] = (int) $item;
        }
    }
    return array_values(array_unique($ids));
}

function portalFetchStudent(mysqli $conn, int $studentId): ?array
{
    $stmt = $conn->prepare(
        "SELECT id, student_id, first_name, last_name, class, father_name, father_phone, mother_name, mother_phone, email
         FROM students WHERE id = ? LIMIT 1"
    );
    $stmt->bind_param('i', $studentId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function portalPaymentMethodLabel(string $method): string
{
    return [
        'card'           => 'Card',
        'momo_mtn'       => 'MTN Mobile Money',
        'momo_vodafone'  => 'Vodafone Cash',
        'momo_airteltigo'=> 'AirtelTigo Money',
    ][$method] ?? $method;
}

function portalGatewayLabel(string $gateway): string
{
    return ['paystack' => 'Paystack', 'hubtel' => 'Hubtel'][$gateway] ?? ucfirst($gateway);
}

$studentId      = isset($_GET['student_id']) && ctype_digit((string) $_GET['student_id']) ? (int) $_GET['student_id'] : 0;
$requestedFeeIds= portalPositiveIntArrayFromCsv($_GET['fee_ids'] ?? '');
$scope          = trim((string) ($_GET['scope'] ?? ''));
$childId        = isset($_GET['child_id'])   && ctype_digit((string) $_GET['child_id'])   ? (int) $_GET['child_id']   : $studentId;

// Verify ownership
if ($studentId > 0 && !portalParentOwnsStudent($conn, $parentId, $studentId)) {
    header('Location: dashboard.php?error=unauthorized');
    exit;
}

$paystackSecret   = trim((string) (getSettingValue('paystack_secret_key')  ?: ($config['paystack']['secret_key']  ?? '')));
$paystackPublic   = trim((string) (getSettingValue('paystack_public_key')   ?: ($config['paystack']['public_key']  ?? '')));
$hubtelClientId     = trim((string) getSettingValue('hubtel_client_id'));
$hubtelClientSecret = trim((string) getSettingValue('hubtel_client_secret'));
$availableGateways  = [
    'paystack' => ($paystackSecret !== '' || $paystackPublic !== ''),
    'hubtel'   => ($hubtelClientId !== '' && $hubtelClientSecret !== ''),
];
$hasAnyGateway = in_array(true, $availableGateways, true);

$student = $studentId > 0 ? portalFetchStudent($conn, $studentId) : null;

/**
 * Resolve which outstanding items to show: explicit ids (fee_ids=1,2,3, the
 * original single/specific-item entry point), scope=term (this child's
 * current-term outstanding items — "pay this term in full"), scope=all
 * (everything outstanding), or nothing (matches the original "invalid
 * selection" empty state rather than silently defaulting to "all").
 */
$checkoutContext = ['current_term' => '', 'max_weeks_covered' => 1, 'items' => []];
if ($student) {
    if ($scope === 'term') {
        $checkoutContext = rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], portalCurrentYear($conn), null, getCurrentTerm());
    } elseif ($scope === 'all') {
        $checkoutContext = rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], portalCurrentYear($conn));
    } elseif ($requestedFeeIds !== []) {
        $checkoutContext = rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], portalCurrentYear($conn), $requestedFeeIds);
    }
}
$fees        = $checkoutContext['items'];
$hasFeedingItem = array_reduce($fees, static fn(bool $c, array $f): bool => $c || $f['is_feeding'], false);
$totalAmount = array_reduce($fees, static fn(float $sum, array $fee): float => $sum + (float) $fee['remaining'], 0.0);
$errorMessage = '';
$waitingPayment = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postStudentId   = isset($_POST['student_id'])    && ctype_digit((string) $_POST['student_id']) ? (int) $_POST['student_id'] : 0;
    $postChildId     = isset($_POST['child_id'])      && ctype_digit((string) $_POST['child_id'])   ? (int) $_POST['child_id']   : $postStudentId;
    $selectedFeeIds  = portalPositiveIntArrayFromCsv($_POST['selected_fee_ids'] ?? '');
    $weeksCovered    = max(1, intval($_POST['weeks_covered'] ?? 1));
    $paymentMethod   = $_POST['payment_method']  ?? '';
    $gateway         = trim((string) ($_POST['payment_gateway'] ?? ''));
    $payerName       = trim((string) ($_POST['payer_name']      ?? ''));
    $payerPhone      = trim((string) ($_POST['payer_phone']     ?? ''));
    $payerEmail      = trim((string) ($_POST['payer_email']     ?? ''));
    $momoNumber           = trim((string) ($_POST['momo_number']     ?? ''));
    $childId              = $postChildId;
    $appliedCouponId      = intval($_POST['coupon_id'] ?? 0) ?: null;
    $appliedDiscountAmt   = max(0.0, (float) ($_POST['discount_amount'] ?? 0));

    // Re-verify ownership on POST
    if ($postStudentId > 0 && !portalParentOwnsStudent($conn, $parentId, $postStudentId)) {
        header('Location: dashboard.php?error=unauthorized');
        exit;
    }

    $student = $postStudentId > 0 ? portalFetchStudent($conn, $postStudentId) : null;
    $postContext = $student
        ? rbcCheckoutFeeContext($conn, $postStudentId, (string) $student['class'], portalCurrentYear($conn), $selectedFeeIds)
        : ['max_weeks_covered' => 1, 'items' => []];
    $fees = $postContext['items'];
    $weeksCovered = min($weeksCovered, max(1, $postContext['max_weeks_covered']));

    if ($paymentMethod === 'card') {
        $gateway = 'paystack';
    }

    if (!$student) {
        $errorMessage = 'Student not found.';
    } elseif ($fees === []) {
        $errorMessage = 'Select at least one fee item.';
    } elseif (!in_array($paymentMethod, ['card', 'momo_mtn', 'momo_vodafone', 'momo_airteltigo'], true)) {
        $errorMessage = 'Choose a valid payment method.';
    } elseif ($paymentMethod === 'card' && !$availableGateways['paystack']) {
        $errorMessage = 'Paystack is not configured for card payments.';
    } elseif ($paymentMethod !== 'card' && !in_array($gateway, ['paystack', 'hubtel'], true)) {
        $errorMessage = 'Choose a valid payment gateway.';
    } elseif ($paymentMethod !== 'card' && !$availableGateways[$gateway]) {
        $errorMessage = portalGatewayLabel($gateway) . ' is not configured.';
    } elseif ($paymentMethod !== 'card' && $gateway === 'hubtel' && $momoNumber === '') {
        $errorMessage = 'Enter the Mobile Money number for Hubtel payments.';
    }

    // Unconditional (not nested in the elseif chain above) so a 'card'
    // payment — which matches its own branch above and would otherwise
    // never reach a trailing `else` — still gets its amount computed. This
    // was a real pre-existing bug: card payments never recomputed
    // $totalAmount from $fees at all, so they charged the leftover default
    // instead of what was actually owed.
    if ($errorMessage === '') {
        $totalAmount = array_reduce($fees, static fn(float $sum, array $fee): float => $sum + (float) $fee['remaining'], 0.0);
        if ($totalAmount <= 0) {
            $errorMessage = 'Invalid payment amount.';
        }
    }

    if ($errorMessage === '') {
        $receiptNumber  = 'RCP' . date('YmdHis') . random_int(100, 999);
        $feeIdsJson     = json_encode(array_column($fees, 'fee_structure_id'), JSON_UNESCAPED_UNICODE);
        $currency       = getSettingValue('payment_currency') ?: 'GHS';
        $gatewayReference = $receiptNumber;
        $pendingStatus  = 'pending';

        // Apply coupon discount
        $originalAmount     = $totalAmount;
        $appliedDiscountAmt = min($appliedDiscountAmt, $originalAmount);
        $totalAmount        = max(0.01, $originalAmount - $appliedDiscountAmt);

        $stmt = $conn->prepare(
            "INSERT INTO online_payments
             (student_id, parent_name, parent_phone, parent_email, fee_structure_ids, weeks_covered, amount, currency, payment_method, gateway, gateway_reference, gateway_status, status, receipt_number, coupon_id, discount_amount, original_amount)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->bind_param(
            'issssidsssssssidd',
            $postStudentId,
            $payerName,
            $payerPhone,
            $payerEmail,
            $feeIdsJson,
            $weeksCovered,
            $totalAmount,
            $currency,
            $paymentMethod,
            $gateway,
            $gatewayReference,
            $pendingStatus,
            $pendingStatus,
            $receiptNumber,
            $appliedCouponId,
            $appliedDiscountAmt,
            $originalAmount
        );

        if ($stmt->execute()) {
            $paymentId = (int) $stmt->insert_id;
            $stmt->close();

            if ($gateway === 'paystack') {
                $email = $payerEmail !== ''
                    ? $payerEmail
                    : (!empty($student['email']) ? $student['email'] : 'noreply@' . portalNormalizeBaseUrlHost(BASE_URL));
                $paystackPayload = [
                    'email'        => $email,
                    'amount'       => (int) round($totalAmount * 100),
                    'reference'    => $receiptNumber,
                    'callback_url' => rtrim(BASE_URL, '/') . '/payment_callback.php',
                    'metadata'     => ['student_id' => $postStudentId, 'payment_id' => $paymentId],
                ];
                $paystackPayload['channels'] = ($paymentMethod === 'card') ? ['card'] : ['mobile_money'];
                $response = initializePaystackPayment($paystackPayload);

                if (!empty($response['data']['status']) && !empty($response['data']['data']['authorization_url'])) {
                    header('Location: ' . $response['data']['data']['authorization_url']);
                    exit;
                }

                $update = $conn->prepare("UPDATE online_payments SET status='failed', gateway_status=?, gateway_response=? WHERE id=?");
                $gStatus   = (string) ($response['data']['message'] ?? 'failed');
                $gResponse = json_encode($response, JSON_UNESCAPED_UNICODE);
                $update->bind_param('ssi', $gStatus, $gResponse, $paymentId);
                $update->execute();
                $update->close();
                $errorMessage = 'Unable to initialize the ' . strtolower(portalPaymentMethodLabel($paymentMethod)) . ' payment at the moment.';
            } else {
                $hubtelResponse = hubtelRequestPayment($totalAmount, $momoNumber, $receiptNumber, $postStudentId, $paymentId);
                $gStatus   = (string) ($hubtelResponse['ResponseCode'] ?? ($hubtelResponse['status'] ?? 'pending'));
                $gResponse = json_encode($hubtelResponse, JSON_UNESCAPED_UNICODE);
                $update = $conn->prepare("UPDATE online_payments SET gateway_status=?, gateway_response=? WHERE id=?");
                $update->bind_param('ssi', $gStatus, $gResponse, $paymentId);
                $update->execute();
                $update->close();
                $waitingPayment = [
                    'id'           => $paymentId,
                    'reference'    => $receiptNumber,
                    'amount'       => $totalAmount,
                    'method_label' => portalPaymentMethodLabel($paymentMethod) . ' via ' . portalGatewayLabel($gateway),
                ];
            }
        } else {
            $stmt->close();
            $errorMessage = 'Unable to save the payment request.';
        }
    }
}

$studentName      = $student ? trim(($student['first_name'] ?? '') . ' ' . ($student['last_name'] ?? '')) : '';
$defaultPayerName = $student ? trim((string) ($student['father_name'] ?? '')) : '';
if ($defaultPayerName === '' && $student) {
    $defaultPayerName = trim((string) ($student['mother_name'] ?? ''));
}
$defaultPayerPhone = $student ? (trim((string) ($student['father_phone'] ?? '')) ?: trim((string) ($student['mother_phone'] ?? ''))) : '';
$defaultPayerEmail = $student ? trim((string) ($student['email'] ?? '')) : '';

echo portalPageStart('Checkout', 'fees', 'Pay Fees');
?>
<style>
.checkout-method-card { border: 1px solid #dee2e6; border-radius: .75rem; padding: 1rem; cursor: pointer; transition: border-color .15s, box-shadow .15s; }
.checkout-method-card:hover { border-color: var(--portal-primary, #1a73e8); box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.checkout-method-card input[type=radio] { margin-right: .6rem; }
.checkout-summary-box { background: linear-gradient(135deg, rgba(26,115,232,.07), rgba(52,168,83,.07)); border-radius: .75rem; padding: 1rem; margin-bottom: 1.25rem; }
.checkout-waiting { background: #fff9db; border: 1px solid #ffe066; border-radius: .75rem; padding: 1.25rem; margin-bottom: 1.25rem; }
</style>

<div class="portal-card">
    <a href="fees.php?child_id=<?= $childId ?>" class="portal-back-link" style="display:inline-flex;align-items:center;gap:.4rem;color:var(--portal-primary,#1a73e8);text-decoration:none;margin-bottom:1rem;">
        <i class="fas fa-arrow-left"></i> Back to Fees
    </a>

    <?php if ($errorMessage !== ''): ?>
        <div class="alert alert-danger"><?= portalCheckoutE($errorMessage) ?></div>
    <?php endif; ?>

    <?php if ($waitingPayment !== null): ?>
        <div class="checkout-waiting">
            <h5><i class="fas fa-clock me-2 text-warning"></i>Waiting for Payment Confirmation</h5>
            <p class="mb-2">Your <?= portalCheckoutE($waitingPayment['method_label']) ?> request has been sent for <strong>GHS <?= number_format((float) $waitingPayment['amount'], 2) ?></strong>.</p>
            <p class="mb-3">Reference: <strong><?= portalCheckoutE($waitingPayment['reference']) ?></strong></p>
            <div class="d-flex gap-2 flex-wrap">
                <a href="../payment_receipt.php?id=<?= (int) $waitingPayment['id'] ?>" class="btn btn-warning btn-sm"><i class="fas fa-sync-alt me-1"></i>Check Payment Status</a>
                <a href="fees.php?child_id=<?= $childId ?>" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i>Back to Fees</a>
            </div>
        </div>
    <?php endif; ?>

    <?php if (!$student): ?>
        <div class="alert alert-warning">Invalid student or fee selection. <a href="fees.php">Go back to Fees</a>.</div>
    <?php elseif (!$hasAnyGateway): ?>
        <div class="alert alert-warning">No payment gateway is configured. Please contact the school office.</div>
    <?php else: ?>
        <div class="checkout-summary-box">
            <div class="row g-2">
                <div class="col-6">
                    <div class="small text-muted">Student</div>
                    <div class="fw-semibold"><?= portalCheckoutE($studentName) ?></div>
                </div>
                <div class="col-6">
                    <div class="small text-muted">Class</div>
                    <div class="fw-semibold"><?= portalCheckoutE((string) ($student['class'] ?? '')) ?></div>
                </div>
            </div>
        </div>

        <form method="post" id="portalCheckoutForm">
            <input type="hidden" name="student_id" value="<?= (int) $student['id'] ?>">
            <input type="hidden" name="child_id"   value="<?= $childId ?>">
            <input type="hidden" name="selected_fee_ids" id="selected_fee_ids" value="<?= portalCheckoutE(implode(',', array_column($fees, 'fee_structure_id'))) ?>">

            <div class="portal-section-title">Selected Fees</div>
            <?php if (count($fees) > 1): ?>
            <div class="form-check mb-2">
                <input class="form-check-input" type="checkbox" id="selectAllTermCheckbox">
                <label class="form-check-label small" for="selectAllTermCheckbox">
                    Select all <?= portalCheckoutE($checkoutContext['current_term']) ?> items (pay the term in full)
                </label>
            </div>
            <?php endif; ?>
            <div class="portal-table-wrap">
                <table class="portal-table">
                    <thead><tr><th>Select</th><th>Fee Type</th><th>Term</th><th>Balance Due</th></tr></thead>
                    <tbody>
                    <?php foreach ($fees as $fee): ?>
                        <tr>
                            <td><input class="form-check-input fee-checkbox" type="checkbox" checked
                                    value="<?= (int) $fee['fee_structure_id'] ?>"
                                    data-amount="<?= number_format((float) $fee['remaining'], 2, '.', '') ?>"
                                    data-is-feeding="<?= $fee['is_feeding'] ? '1' : '0' ?>"
                                    data-current-term="<?= $fee['is_current_term'] ? '1' : '0' ?>"></td>
                            <td><?= portalCheckoutE((string) $fee['fee_type']) ?></td>
                            <td><?= portalCheckoutE((string) ($fee['term'] ?? '')) ?></td>
                            <td>GHS <?= number_format((float) $fee['remaining'], 2) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($hasFeedingItem): ?>
            <div class="mb-3 d-none" id="weeksCoveredRow">
                <label class="form-label">
                    Weeks Covered <span class="text-muted small">(how many weeks of feeding does this cover?)</span>
                </label>
                <div class="input-group" style="max-width:260px;">
                    <input type="number" class="form-control" name="weeks_covered" id="weeksCovered" value="1" min="1" max="<?= (int) $checkoutContext['max_weeks_covered'] ?>">
                    <span class="input-group-text">week(s)</span>
                </div>
                <div class="btn-group btn-group-sm mt-2" role="group">
                    <button type="button" class="btn btn-outline-secondary weeks-shortcut-btn" data-weeks="1">1 Week</button>
                    <button type="button" class="btn btn-outline-secondary weeks-shortcut-btn" data-weeks="4">1 Month</button>
                    <button type="button" class="btn btn-outline-secondary weeks-shortcut-btn" data-weeks-full-term="1">Full Term</button>
                </div>
            </div>
            <?php endif; ?>

            <div class="portal-section-title mt-3">Payer Details</div>
            <div class="row g-3 mb-3">
                <div class="col-md-6">
                    <label class="form-label">Full Name</label>
                    <input type="text" class="form-control" name="payer_name" value="<?= portalCheckoutE($defaultPayerName) ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Phone</label>
                    <input type="text" class="form-control" name="payer_phone" value="<?= portalCheckoutE($defaultPayerPhone) ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Email <span class="text-muted small">(optional)</span></label>
                    <input type="email" class="form-control" name="payer_email" value="<?= portalCheckoutE($defaultPayerEmail) ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Mobile Money Number <span class="text-muted small">(required for MoMo via Hubtel)</span></label>
                    <input type="text" class="form-control" id="momo_number" name="momo_number" placeholder="e.g. 0241234567">
                </div>
            </div>

            <!-- Coupon Code -->
            <div class="mb-3">
                <label class="form-label">Coupon / Discount Code <span class="text-muted small">(optional)</span></label>
                <div class="input-group">
                    <input type="text" class="form-control" id="couponCodeInput" placeholder="Enter coupon code">
                    <button type="button" class="btn btn-outline-primary" id="applyCouponBtn">Apply</button>
                    <button type="button" class="btn btn-outline-secondary" id="removeCouponBtn" style="display:none">Remove</button>
                </div>
                <div id="couponFeedback" class="mt-1 small"></div>
                <input type="hidden" name="coupon_id" id="couponIdField" value="0">
                <input type="hidden" name="discount_amount" id="discountAmountField" value="0">
            </div>

            <div class="portal-section-title">Payment Method</div>
            <div class="row g-2 mb-3">
                <div class="col-6 col-md-3">
                    <label class="checkout-method-card d-block">
                        <input type="radio" name="payment_method" value="card" checked <?= !$availableGateways['paystack'] ? 'disabled' : '' ?>>
                        <span><i class="fas fa-credit-card me-1"></i>Card</span>
                    </label>
                </div>
                <div class="col-6 col-md-3">
                    <label class="checkout-method-card d-block">
                        <input type="radio" name="payment_method" value="momo_mtn">
                        <span><i class="fas fa-mobile-alt me-1"></i>MTN MoMo</span>
                    </label>
                </div>
                <div class="col-6 col-md-3">
                    <label class="checkout-method-card d-block">
                        <input type="radio" name="payment_method" value="momo_vodafone">
                        <span><i class="fas fa-mobile-alt me-1"></i>Vodafone Cash</span>
                    </label>
                </div>
                <div class="col-6 col-md-3">
                    <label class="checkout-method-card d-block">
                        <input type="radio" name="payment_method" value="momo_airteltigo">
                        <span><i class="fas fa-mobile-alt me-1"></i>AirtelTigo</span>
                    </label>
                </div>
            </div>

            <div id="gatewaySection" class="mb-3">
                <div class="portal-section-title">Payment Gateway</div>
                <div class="row g-2">
                    <div class="col-6">
                        <label class="checkout-method-card d-block">
                            <input type="radio" name="payment_gateway" value="paystack" checked <?= !$availableGateways['paystack'] ? 'disabled' : '' ?>>
                            <span><i class="fas fa-university me-1"></i>Paystack</span>
                        </label>
                    </div>
                    <div class="col-6">
                        <label class="checkout-method-card d-block">
                            <input type="radio" name="payment_gateway" value="hubtel" <?= !$availableGateways['hubtel'] ? 'disabled' : '' ?>>
                            <span><i class="fas fa-mobile-screen-button me-1"></i>Hubtel</span>
                        </label>
                    </div>
                </div>
                <div class="form-text mt-1" id="gatewayHelpText"></div>
            </div>

            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 pt-2 border-top">
                <div>
                    <div class="small text-muted">Total</div>
                    <div class="fs-4 fw-bold">GHS <span id="runningTotal"><?= number_format($totalAmount, 2) ?></span></div>
                    <div id="discountRow" style="display:none" class="text-success small">
                        Discount: -GHS <span id="discountDisplay">0.00</span>
                        &nbsp;&bull;&nbsp; <strong>Final: GHS <span id="finalDisplay">0.00</span></strong>
                    </div>
                </div>
                <button type="submit" class="btn btn-success btn-lg" id="payNowButton">
                    <i class="fas fa-lock me-2"></i>Pay GHS <span id="buttonTotal"><?= number_format($totalAmount, 2) ?></span>
                </button>
            </div>
        </form>
    <?php endif; ?>
</div>

<script>
(() => {
    const feeCheckboxes = document.querySelectorAll('.fee-checkbox');
    const selectedFeeIdsInput = document.getElementById('selected_fee_ids');
    const runningTotal   = document.getElementById('runningTotal');
    const buttonTotal    = document.getElementById('buttonTotal');
    const payNowButton   = document.getElementById('payNowButton');
    const methodInputs   = document.querySelectorAll('input[name="payment_method"]');
    const gatewayInputs  = document.querySelectorAll('input[name="payment_gateway"]');
    const gatewaySection = document.getElementById('gatewaySection');
    const gatewayHelp    = document.getElementById('gatewayHelpText');
    const momoNumber     = document.getElementById('momo_number');
    const paystackEnabled = <?= json_encode($availableGateways['paystack']) ?>;
    const hubtelEnabled   = <?= json_encode($availableGateways['hubtel']) ?>;
    const weeksCoveredInput = document.getElementById('weeksCovered');
    const weeksCoveredRow   = document.getElementById('weeksCoveredRow');
    const maxWeeksCovered   = <?= (int) $checkoutContext['max_weeks_covered'] ?>;
    const selectAllTermCheckbox = document.getElementById('selectAllTermCheckbox');

    function updateTotals() {
        let total = 0;
        const ids = [];
        let anyFeeding = false;
        feeCheckboxes.forEach(cb => {
            if (cb.checked) {
                total += parseFloat(cb.dataset.amount || '0');
                ids.push(cb.value);
                if (cb.dataset.isFeeding === '1') anyFeeding = true;
            }
        });
        if (selectedFeeIdsInput) selectedFeeIdsInput.value = ids.join(',');
        if (runningTotal) runningTotal.textContent = total.toFixed(2);
        if (buttonTotal)  buttonTotal.textContent  = total.toFixed(2);
        if (payNowButton) payNowButton.disabled = ids.length === 0 || total <= 0;
        if (weeksCoveredRow) weeksCoveredRow.classList.toggle('d-none', !anyFeeding);

        if (selectAllTermCheckbox) {
            const termBoxes = Array.from(feeCheckboxes).filter(cb => cb.dataset.currentTerm === '1');
            selectAllTermCheckbox.checked = termBoxes.length > 0 && termBoxes.every(cb => cb.checked);
        }
    }

    if (selectAllTermCheckbox) {
        selectAllTermCheckbox.addEventListener('change', () => {
            feeCheckboxes.forEach(cb => {
                if (cb.dataset.currentTerm === '1') cb.checked = selectAllTermCheckbox.checked;
            });
            updateTotals();
            reapplyDiscount();
        });
    }

    document.querySelectorAll('.weeks-shortcut-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            let weeks = btn.dataset.weeksFullTerm ? maxWeeksCovered : parseInt(btn.dataset.weeks, 10);
            weeks = Math.max(1, Math.min(weeks || 1, maxWeeksCovered || weeks || 1));
            if (weeksCoveredInput) weeksCoveredInput.value = weeks;
        });
    });

    function syncGateway() {
        const method = document.querySelector('input[name="payment_method"]:checked')?.value || 'card';
        const isCard = method === 'card';
        if (gatewaySection) gatewaySection.style.display = isCard ? 'none' : '';

        gatewayInputs.forEach(input => {
            if (isCard) {
                input.disabled = input.value !== 'paystack' || !paystackEnabled;
                input.checked  = input.value === 'paystack' && paystackEnabled;
            } else {
                input.disabled = (input.value === 'paystack' && !paystackEnabled) || (input.value === 'hubtel' && !hubtelEnabled);
            }
        });

        if (!isCard && !document.querySelector('input[name="payment_gateway"]:checked')) {
            const fallback = document.querySelector('input[name="payment_gateway"]:not(:disabled)');
            if (fallback) fallback.checked = true;
        }

        const activeGateway = document.querySelector('input[name="payment_gateway"]:checked')?.value || 'paystack';
        if (gatewayHelp) {
            if (isCard) {
                gatewayHelp.textContent = paystackEnabled ? 'Card payments are processed through Paystack.' : 'Paystack is not configured.';
            } else if (activeGateway === 'hubtel') {
                gatewayHelp.textContent = 'Hubtel sends a Mobile Money push to the number entered above.';
            } else {
                gatewayHelp.textContent = 'Paystack will open its hosted checkout for Mobile Money authorization.';
            }
        }
        if (momoNumber) momoNumber.required = !isCard && activeGateway === 'hubtel';
    }

    feeCheckboxes.forEach(cb => cb.addEventListener('change', () => { updateTotals(); reapplyDiscount(); }));
    methodInputs.forEach(i  => i.addEventListener('change', syncGateway));
    gatewayInputs.forEach(i => i.addEventListener('change', syncGateway));
    updateTotals();
    syncGateway();
})();

// Coupon logic
let activeDiscount = 0;

function getSubtotal() {
    let t = 0;
    document.querySelectorAll('.fee-checkbox').forEach(cb => { if (cb.checked) t += parseFloat(cb.dataset.amount || '0'); });
    return t;
}

function reapplyDiscount() {
    if (activeDiscount > 0) {
        const sub = getSubtotal();
        const disc = Math.min(activeDiscount, sub);
        const final = Math.max(0.01, sub - disc);
        document.getElementById('discountAmountField').value = disc.toFixed(2);
        document.getElementById('discountDisplay').textContent = disc.toFixed(2);
        document.getElementById('finalDisplay').textContent = final.toFixed(2);
        document.getElementById('buttonTotal').textContent = final.toFixed(2);
        document.getElementById('discountRow').style.display = '';
    }
}

document.getElementById('applyCouponBtn').addEventListener('click', function () {
    const code = document.getElementById('couponCodeInput').value.trim();
    if (!code) return;
    const studentId = document.querySelector('input[name="student_id"]')?.value || '';
    fetch('../ajax/coupons.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ action: 'validate', coupon_code: code, student_id: studentId, amount: getSubtotal() })
    })
    .then(r => r.json())
    .then(d => {
        const fb = document.getElementById('couponFeedback');
        if (d.valid) {
            activeDiscount = parseFloat(d.discount_amount) || 0;
            document.getElementById('couponIdField').value = d.coupon_id;
            fb.innerHTML = '<span class="text-success"><i class="fas fa-check-circle me-1"></i>' + d.message + '</span>';
            document.getElementById('applyCouponBtn').style.display = 'none';
            document.getElementById('removeCouponBtn').style.display = '';
            reapplyDiscount();
        } else {
            fb.innerHTML = '<span class="text-danger"><i class="fas fa-times-circle me-1"></i>' + (d.message || 'Invalid coupon') + '</span>';
        }
    })
    .catch(() => { document.getElementById('couponFeedback').innerHTML = '<span class="text-danger">Coupon check failed</span>'; });
});

document.getElementById('removeCouponBtn').addEventListener('click', function () {
    activeDiscount = 0;
    document.getElementById('couponIdField').value = '0';
    document.getElementById('discountAmountField').value = '0';
    document.getElementById('couponCodeInput').value = '';
    document.getElementById('couponFeedback').innerHTML = '';
    document.getElementById('discountRow').style.display = 'none';
    document.getElementById('applyCouponBtn').style.display = '';
    document.getElementById('removeCouponBtn').style.display = 'none';
    document.getElementById('buttonTotal').textContent = getSubtotal().toFixed(2);
});
</script>
<?= portalPageEnd('fees') ?>
