<?php
declare(strict_types=1);

session_start();
require_once 'config.php';
require_once 'ai/fee_balance.php';
requireModule('online_payments');
$conn = getDBConnection();

ini_set('display_errors', '0');
error_reporting(E_ALL);

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

$is_admin = isset($_SESSION['user_id']);
$is_parent = isset($_SESSION['parent_id']);
if (!$is_admin && !$is_parent) {
    header('Location: login.php');
    exit;
}

if (!$conn) {
    http_response_code(500);
    exit('Unable to connect to the database.');
}

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

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

function positiveIntArrayFromCsv(?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 fetchStudent(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 paymentMethodLabel(string $method): string
{
    return [
        'card' => 'Card',
        'momo_mtn' => 'MTN Mobile Money',
        'momo_vodafone' => 'Vodafone Cash',
        'momo_airteltigo' => 'AirtelTigo Money',
    ][$method] ?? $method;
}

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

// Ensure coupon columns exist on online_payments (safe no-op if already present)
$conn->query("ALTER TABLE online_payments ADD COLUMN IF NOT EXISTS coupon_id INT NULL DEFAULT NULL");
$conn->query("ALTER TABLE online_payments ADD COLUMN IF NOT EXISTS discount_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00");
$conn->query("ALTER TABLE online_payments ADD COLUMN IF NOT EXISTS original_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00");

$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);

if ($is_parent) {
    $ownershipStmt = $conn->prepare(
        "SELECT id FROM parent_student_link
         WHERE parent_id = ? AND student_id = ?"
    );
    $ownershipStmt->bind_param('ii', $_SESSION['parent_id'], $studentId);
    $ownershipStmt->execute();
    if ($ownershipStmt->get_result()->num_rows === 0) {
        $ownershipStmt->close();
        header('Location: parent-portal/dashboard.php?error=unauthorized');
        exit;
    }
    $ownershipStmt->close();
}

$student = $studentId > 0 ? fetchStudent($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 student'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'], getAcademicYear(), null, getCurrentTerm());
    } elseif ($scope === 'all') {
        $checkoutContext = rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], getAcademicYear());
    } elseif ($requestedFeeIds !== []) {
        $checkoutContext = rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], getAcademicYear(), $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') {
    $studentId = isset($_POST['student_id']) && ctype_digit((string) $_POST['student_id']) ? (int) $_POST['student_id'] : 0;
    $selectedFeeIds = positiveIntArrayFromCsv($_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'] ?? ''));
    $appliedCouponId     = intval($_POST['coupon_id'] ?? 0) ?: null;
    $appliedDiscountAmt  = max(0.0, (float) ($_POST['discount_amount'] ?? 0));

    $student = $studentId > 0 ? fetchStudent($conn, $studentId) : null;
    $postContext = $student
        ? rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], getAcademicYear(), $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 = gatewayLabel($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); // cannot exceed total
        $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',
            $studentId,
            $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@' . normalizeBaseUrlHost(BASE_URL));
                $paystackPayload = [
                    'email' => $email,
                    'amount' => (int) round($totalAmount * 100),
                    'reference' => $receiptNumber,
                    'callback_url' => rtrim(BASE_URL, '/') . '/payment_callback.php',
                    'metadata' => ['student_id' => $studentId, 'payment_id' => $paymentId]
                ];
                if ($paymentMethod === 'card') {
                    $paystackPayload['channels'] = ['card'];
                } else {
                    $paystackPayload['channels'] = ['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=?");
                $gatewayStatus = (string) ($response['data']['message'] ?? 'failed');
                $gatewayResponse = json_encode($response, JSON_UNESCAPED_UNICODE);
                $update->bind_param('ssi', $gatewayStatus, $gatewayResponse, $paymentId);
                $update->execute();
                $update->close();
                $errorMessage = 'Unable to initialize the ' . strtolower(paymentMethodLabel($paymentMethod)) . ' payment at the moment.';
            } else {
                $hubtelResponse = hubtelRequestPayment($totalAmount, $momoNumber, $receiptNumber, $studentId, $paymentId);
                $gatewayStatus = (string) ($hubtelResponse['ResponseCode'] ?? ($hubtelResponse['status'] ?? 'pending'));
                $gatewayResponse = json_encode($hubtelResponse, JSON_UNESCAPED_UNICODE);
                $update = $conn->prepare("UPDATE online_payments SET gateway_status=?, gateway_response=? WHERE id=?");
                $update->bind_param('ssi', $gatewayStatus, $gatewayResponse, $paymentId);
                $update->execute();
                $update->close();
                $waitingPayment = [
                    'id' => $paymentId,
                    'reference' => $receiptNumber,
                    'amount' => $totalAmount,
                    'method_label' => paymentMethodLabel($paymentMethod) . ' via ' . gatewayLabel($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'] ?? '')) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Payment Checkout - EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <style>
        .method-card { border:1px solid #dee2e6; border-radius:.75rem; padding:1rem; cursor:pointer; }
        .method-card:hover { border-color: var(--secondary); box-shadow: var(--shadow-sm); }
        .method-card input { margin-right: .65rem; }
        .waiting-box { background:#fff9db; border:1px solid #ffe066; }
        .summary-box { background: linear-gradient(135deg, rgba(52,152,219,.08), rgba(39,174,96,.08)); }
    </style>
</head>
<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <div class="main-content">
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <main class="content">
                <div class="content-header d-flex justify-content-between align-items-start flex-wrap gap-3">
                    <div>
                        <h2><i class="fas fa-mobile-alt me-2"></i>Online Payment Checkout</h2>
                        <p>Select fee items and complete payment securely.</p>
                    </div>
                    <a href="fees.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back to Fees</a>
                </div>
            <?php if ($errorMessage !== ''): ?><div class="alert alert-danger"><?= e($errorMessage) ?></div><?php endif; ?>
            <?php if ($waitingPayment !== null): ?>
                <div class="card waiting-box mb-4"><div class="card-body">
                    <h5 class="card-title mb-2"><i class="fas fa-clock me-2 text-warning"></i>Waiting for Payment Confirmation</h5>
                    <p class="mb-2">Your <?= e($waitingPayment['method_label']) ?> request has been initiated for <strong>GHS <?= number_format((float) $waitingPayment['amount'], 2) ?></strong>.</p>
                    <p class="mb-3">Reference: <strong><?= e($waitingPayment['reference']) ?></strong></p>
                    <a href="payment_receipt.php?id=<?= (int) $waitingPayment['id'] ?>" class="btn btn-warning"><i class="fas fa-sync-alt me-1"></i>Check Payment Status</a>
                </div></div>
            <?php endif; ?>
            <div class="row g-4">
                <div class="col-lg-8">
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-file-invoice-dollar me-2"></i>Payment Details</h5>
                        </div>
                        <div class="card-body">
                        <?php if (!$student): ?>
                            <div class="alert alert-warning mb-0">Invalid student or fee selection.</div>
                        <?php elseif (!$hasAnyGateway): ?>
                            <div class="alert alert-warning mb-0">No payment gateway is configured. Add Paystack or Hubtel credentials in Settings first.</div>
                        <?php else: ?>
                            <div class="card summary-box mb-4">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6"><label class="form-label text-muted">Student</label><div class="fw-semibold"><?= e($studentName) ?></div></div>
                                        <div class="col-md-6"><label class="form-label text-muted">Class</label><div class="fw-semibold"><?= e((string) ($student['class'] ?? '')) ?></div></div>
                                    </div>
                                </div>
                            </div>
<?php
$sub_code    = getSettingValue('paystack_subaccount_code');
$sub_enabled = getSettingValue('paystack_split_enabled');
if (!empty($sub_code) && $sub_enabled === '1'): ?>
<div class="alert alert-info py-2 small mb-3">
  <i class="fas fa-shield-alt me-1"></i>
  Payment processed securely by Paystack.
  Funds settle directly to
  <strong><?= htmlspecialchars((string)(getSettingValue('school_name') ?? 'the school')) ?></strong>.
</div>
<?php endif; ?>
                            <form method="post" id="checkoutForm">
                                <input type="hidden" name="student_id" value="<?= (int) $student['id'] ?>">
                                <input type="hidden" name="selected_fee_ids" id="selected_fee_ids" value="<?= e(implode(',', array_column($fees, 'fee_structure_id'))) ?>">
                                <?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 <?= e($checkoutContext['current_term']) ?> items (pay the term in full)
                                    </label>
                                </div>
                                <?php endif; ?>
                                <div class="table-responsive mb-3">
                                    <table class="table align-middle">
                                        <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><?= e((string) $fee['fee_type']) ?></td>
                                                <td><?= e((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-4 d-none" id="weeksCoveredRow">
                                    <label class="form-label">
                                        Weeks Covered
                                        <span class="text-muted small ms-1">(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; ?>
                                <!-- Coupon Code -->
                                <div class="mb-4">
                                    <label class="form-label">Coupon Code (optional)</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-2"></div>
                                    <input type="hidden" name="coupon_id" id="couponIdField" value="0">
                                    <input type="hidden" name="discount_amount" id="discountAmountField" value="0">
                                </div>

                                <div class="row g-3 mb-4">
                                    <div class="col-md-6"><label for="payer_name" class="form-label">Payer Name</label><input type="text" class="form-control" id="payer_name" name="payer_name" value="<?= e($defaultPayerName) ?>" required></div>
                                    <div class="col-md-6"><label for="payer_phone" class="form-label">Payer Phone</label><input type="text" class="form-control" id="payer_phone" name="payer_phone" value="<?= e($defaultPayerPhone) ?>" required></div>
                                    <div class="col-md-6"><label for="payer_email" class="form-label">Payer Email</label><input type="email" class="form-control" id="payer_email" name="payer_email" value="<?= e($defaultPayerEmail) ?>"></div>
                                    <div class="col-md-6"><label for="momo_number" class="form-label">Mobile Money Number</label><input type="text" class="form-control" id="momo_number" name="momo_number" placeholder="Required for MOMO payments"></div>
                                </div>
                                <div class="mb-4">
                                    <label class="form-label">Payment Method</label>
                                    <div class="row g-3">
                                        <div class="col-md-6"><label class="method-card d-block"><input type="radio" name="payment_method" value="card" checked <?= !$availableGateways['paystack'] ? 'disabled' : '' ?>><span><i class="fas fa-credit-card me-2"></i>Card</span></label></div>
                                        <div class="col-md-6"><label class="method-card d-block"><input type="radio" name="payment_method" value="momo_mtn"><span><i class="fas fa-mobile-alt me-2"></i>MTN Mobile Money</span></label></div>
                                        <div class="col-md-6"><label class="method-card d-block"><input type="radio" name="payment_method" value="momo_vodafone"><span><i class="fas fa-mobile-alt me-2"></i>Vodafone Cash</span></label></div>
                                        <div class="col-md-6"><label class="method-card d-block"><input type="radio" name="payment_method" value="momo_airteltigo"><span><i class="fas fa-mobile-alt me-2"></i>AirtelTigo Money</span></label></div>
                                    </div>
                                </div>
                                <div class="mb-4" id="gatewaySection">
                                    <label class="form-label">Payment Gateway</label>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="method-card d-block">
                                                <input type="radio" name="payment_gateway" value="paystack" checked <?= !$availableGateways['paystack'] ? 'disabled' : '' ?>>
                                                <span><i class="fas fa-university me-2"></i>Paystack</span>
                                            </label>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="method-card d-block">
                                                <input type="radio" name="payment_gateway" value="hubtel" <?= !$availableGateways['hubtel'] ? 'disabled' : '' ?>>
                                                <span><i class="fas fa-mobile-screen-button me-2"></i>Hubtel</span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="form-text mt-2" id="gatewayHelpText"></div>
                                </div>
                                <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                                    <div>
                                        <div class="text-muted">Running 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;|&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> Now</button>
                                </div>
                            </form>
                        <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-info-circle me-2"></i>Payment Notes</h5>
                        </div>
                        <div class="card-body">
                            <ul class="mb-0 ps-3">
                                <li>Card payments use Paystack when Paystack is configured.</li>
                                <li>Mobile Money can use either Paystack or Hubtel, depending on the configured gateway.</li>
                                <li>Receipt becomes available immediately after confirmation.</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            </main>

            <footer class="footer">
                <p>&copy; 2024 EduTrack PRO. All rights reserved.</p>
            </footer>
        </div>
    </div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="js/main.js"></script>
<script>
(() => {
    const feeCheckboxes = document.querySelectorAll('.fee-checkbox');
    const selectedFeeIds = document.getElementById('selected_fee_ids');
    const runningTotal = document.getElementById('runningTotal');
    const buttonTotal = document.getElementById('buttonTotal');
    const payNowButton = document.getElementById('payNowButton');
    const paymentMethodInputs = document.querySelectorAll('input[name="payment_method"]');
    const gatewayInputs = document.querySelectorAll('input[name="payment_gateway"]');
    const gatewaySection = document.getElementById('gatewaySection');
    const gatewayHelpText = 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((checkbox) => {
            if (checkbox.checked) {
                total += parseFloat(checkbox.dataset.amount || '0');
                ids.push(checkbox.value);
                if (checkbox.dataset.isFeeding === '1') anyFeeding = true;
            }
        });
        if (selectedFeeIds) selectedFeeIds.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 syncGatewayOptions() {
        const selectedMethod = document.querySelector('input[name="payment_method"]:checked')?.value || 'card';
        const isCard = selectedMethod === '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);
            }
        });

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

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

        if (momoNumber) {
            momoNumber.required = !isCard && activeGateway === 'hubtel';
        }
    }

    feeCheckboxes.forEach((checkbox) => checkbox.addEventListener('change', () => { updateTotals(); reapplyDiscount(); }));
    paymentMethodInputs.forEach((input) => input.addEventListener('change', syncGatewayOptions));
    gatewayInputs.forEach((input) => input.addEventListener('change', syncGatewayOptions));
    updateTotals();
    syncGatewayOptions();
})();

// Coupon logic
let activeDiscount = 0;

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

function reapplyDiscount() {
    if (activeDiscount > 0) {
        const subtotal = getSubtotal();
        const discount = Math.min(activeDiscount, subtotal);
        const final = Math.max(0.01, subtotal - discount);
        document.getElementById('discountAmountField').value = discount.toFixed(2);
        document.getElementById('discountDisplay').textContent = discount.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;
    const feeIds = document.getElementById('selected_fee_ids').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, fee_ids: feeIds, 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';
    // Restore button total to subtotal
    const subtotal = getSubtotal();
    document.getElementById('buttonTotal').textContent = subtotal.toFixed(2);
});
</script>
</body>
</html>
