<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');
// Use the session ID set in session.php

// Load dependencies
require_once 'vendor/autoload.php';
// Ensure session is valid


$eid2 = $_SESSION['student_id'];


// Load environment variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$paystackPublicKey = $_ENV['PAYSTACK_PUBLIC_KEY'];

// Fetch student details
$query = "SELECT * FROM students WHERE id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("i", $eid2);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    $_SESSION['studentRegNo'] = $row['studentRegNo'];
    $_SESSION['studentName'] = $row['studentName'];
    $_SESSION['id'] = $row['id'];
} else {
    echo "Invalid student ID.";
    exit;
}

// Validate pay_amount and store in session
if (isset($_GET['pay_amount'])) {
    $payAmount = intval($_GET['pay_amount']);
    if ($payAmount <= 0) {
        flash_alert('Payment of ₦0 is not possible');
        header("Location: payschoolfeesnewb.php?tab_id=$tabSessionID");
        exit;
        exit;
    }
    $_SESSION['pay_amount'] = $payAmount;
} elseif (isset($_SESSION['pay_amount'])) {
    $payAmount = $_SESSION['pay_amount'];
} else {
    flash_alert('Payment amount is missing.');
    header("Location: payschoolfeesnewb.php?tab_id=$tabSessionID");
    exit;
    exit;
}

// Validate fee_id
if (!isset($_GET['fee_id']) || empty($_GET['fee_id'])) {
    flash_alert('Fee ID Missing.');
    header("Location: payschoolfeesnewb.php?tab_id=$tabSessionID");
    exit;
    exit;
}
//Get amountDue for schoolfees
// Validate fee_id
if (isset($_GET['termdue']) || empty($_GET['termdue'])) {
    $amountDue = intval($_GET['termdue']);
}

$feeId = intval($_GET['fee_id']);

// Read admission session/term passed from payschoolfeesnewb.php
$admSession = trim($_GET['adm_session'] ?? '');
$admTerm    = trim($_GET['adm_term']    ?? '');

// Fetch fee details
$feeQuery = "SELECT * FROM fees WHERE id = ?";
$feeStmt = $con->prepare($feeQuery);
$feeStmt->bind_param("i", $feeId);
$feeStmt->execute();
$feeResult = $feeStmt->get_result();

if ($fee = $feeResult->fetch_assoc()) {
    $amount = $fee['amount'];
    $feeType = $fee['name'];
    $class = $fee['class'];
} else {
    echo "<p class='text-danger'>Invalid fee ID.</p>";
    exit;
}

// Check active discount codes
$discountAvailable = false;
$discountQuery = "SELECT * FROM discount_codes WHERE expiry_date >= NOW() LIMIT 1";
$discountResult = mysqli_query($con, $discountQuery);
if ($discountResult && mysqli_num_rows($discountResult) > 0) {
    $discountAvailable = true;
}

// Fetch school virtual account for bank transfer option (New Boarding Student payment type)
$vaRow = null;
$vaResult = $con->query("SELECT account_number, bank_name, account_name FROM school_virtual_accounts WHERE payment_type = 'new_student_board' AND is_active = 1 LIMIT 1");
if ($vaResult && $vaResult->num_rows > 0) {
    $vaRow = $vaResult->fetch_assoc();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php @include("includes/head.php"); ?>
<script src="https://js.paystack.co/v1/inline.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .cpf-wrapper {
        max-width: 760px;
        margin: 0 auto;
        padding: 0 0 40px;
    }

    .student-hero {
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 60%, #0f2044 100%);
        border-radius: 20px;
        padding: 24px 28px;
        position: relative;
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(15, 23, 42, .35);
        margin-bottom: 24px;
    }

    .student-hero::before {
        content: '';
        position: absolute;
        top: -60px;
        right: -60px;
        width: 220px;
        height: 220px;
        background: radial-gradient(circle, rgba(99, 102, 241, .25) 0%, transparent 70%);
        border-radius: 50%;
    }

    .hero-inner {
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;
        z-index: 1;
        gap: 12px;
        flex-wrap: wrap;
    }

    .hero-info {
        display: flex;
        align-items: center;
        gap: 16px;
        min-width: 0;
    }

    .hero-avatar {
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #6366f1, #8b5cf6);
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.3rem;
        font-weight: 800;
        color: #fff;
        flex-shrink: 0;
    }

    .hero-name {
        font-size: 1.1rem;
        font-weight: 700;
        color: #f8fafc;
        margin: 0;
    }

    .hero-meta {
        font-size: .75rem;
        color: #94a3b8;
        margin: 3px 0 0;
    }

    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        gap: 12px;
        margin-bottom: 20px;
    }

    .info-chip {
        background: #f8fafc;
        border: 1.5px solid #e2e8f0;
        border-radius: 12px;
        padding: 12px 16px;
    }

    .info-chip-label {
        font-size: .68rem;
        text-transform: uppercase;
        letter-spacing: .06em;
        color: #64748b;
        margin-bottom: 4px;
    }

    .info-chip-value {
        font-size: .92rem;
        font-weight: 700;
        color: #0f172a;
    }

    .info-chip-value.highlight {
        color: #6366f1;
    }

    .form-card {
        background: #fff;
        border-radius: 20px;
        box-shadow: 0 4px 30px rgba(15, 23, 42, .07);
        overflow: hidden;
        border: 1px solid #e8ecf4;
        margin-bottom: 20px;
    }

    .form-card-header {
        padding: 18px 24px;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .form-card-header-icon {
        width: 34px;
        height: 34px;
        background: linear-gradient(135deg, #0f172a, #1e293b);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: .82rem;
    }

    .form-card-header h5 {
        margin: 0;
        font-size: .92rem;
        font-weight: 700;
        color: #0f172a;
    }

    .form-card-body {
        padding: 24px;
    }

    .field-label {
        font-size: .72rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: .06em;
        color: #64748b;
        margin-bottom: 6px;
        display: block;
    }

    .wpf-input {
        width: 100%;
        height: 44px;
        border: 1.5px solid #e2e8f0;
        border-radius: 12px;
        padding: 0 14px;
        font-size: .88rem;
        color: #0f172a;
        background: #f8fafc;
        transition: border-color .2s, box-shadow .2s;
        outline: none;
    }

    .wpf-input:focus {
        border-color: #6366f1;
        box-shadow: 0 0 0 4px rgba(99, 102, 241, .1);
        background: #fff;
    }

    .notice-bar {
        background: #fffbeb;
        border: 1.5px solid #fde68a;
        border-radius: 12px;
        padding: 12px 16px;
        font-size: .82rem;
        color: #92400e;
        display: flex;
        align-items: flex-start;
        gap: 8px;
        margin-bottom: 20px;
    }

    .notice-bar i {
        margin-top: 1px;
        color: #f59e0b;
        flex-shrink: 0;
    }

    .btn-pay-main {
        color: #fff;
        border: none;
        height: 46px;
        padding: 0 32px;
        border-radius: 12px;
        font-size: .9rem;
        font-weight: 700;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        background: linear-gradient(135deg, #6366f1, #8b5cf6);
        box-shadow: 0 6px 20px rgba(99, 102, 241, .35);
        transition: transform .15s, box-shadow .15s;
    }

    .btn-pay-main:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 28px rgba(99, 102, 241, .45);
    }

    .section-divider {
        height: 1px;
        background: #f1f5f9;
        margin: 20px 0;
    }

    @media(max-width:576px) {
        .hero-inner {
            flex-direction: column;
            align-items: flex-start;
        }

        .info-grid {
            grid-template-columns: 1fr 1fr;
        }
    }
        .info-grid {
        display: grid;
        gap: 12px;
        margin-bottom: 20px;
    }
    .info-chip {
        background: #f8fafc;
        border: 1.5px solid #e2e8f0;
        border-radius: 12px;
        padding: 12px 16px;
    }
    .info-chip-label {
        font-size: .68rem;
        text-transform: uppercase;
        letter-spacing: .06em;
        color: #64748b;
        margin-bottom: 4px;
    }
    .info-chip-value {
        font-size: .92rem;
        font-weight: 700;
        color: #0f172a;
    }
    .info-chip-value.highlight { color: #1a5c35; }
    @media(max-width:576px) {
        .info-grid { grid-template-columns: 1fr 1fr !important; }
    }
</style>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/headerstd.php"); ?>
        <?php @include("includes/sidebarstdboard.php"); ?>

        <div class="content-wrapper" style="background:#f0f2f8;">
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-credit-card"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Payment Management
                                            <span class="premium-subtitle text-secondary">Make Payment</span>
                                        </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="newstdboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Pay
                                            <?php echo htmlspecialchars($feeType); ?>
                                        </li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            <section class="content-body">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <!-- general form elements -->
                            <div class="card card-primary">
                                <div class="card-header">
                                    <h5 class="card-title font-weight-bold">
                                        <i class="fas fa-wallet"></i> Confirm Payment Details
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <section class="content" style="padding:16px 12px 40px;">
                                        <div class="container-fluid" style="padding-left:0;padding-right:0;">
                                            <div class="cpf-wrapper">

                                                <!-- Student Hero -->
                                                <div class="student-hero">
                                                    <div class="hero-inner">
                                                        <div class="hero-info">
                                                            <div class="hero-avatar">
                                                                <?= strtoupper(substr($_SESSION['studentName'], 0, 1)) ?>
                                                            </div>
                                                            <div>
                                                                <p class="hero-name">
                                                                    <?= htmlspecialchars($_SESSION['studentName']) ?>
                                                                </p>
                                                                <p class="hero-meta">REG:
                                                                    <?= htmlspecialchars($_SESSION['studentRegNo']) ?>
                                                                    &nbsp;·&nbsp; <?= htmlspecialchars($class) ?>
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Payment Summary -->
                                                <div class="form-card">
                                                    <div class="form-card-header">
                                                        <div class="form-card-header-icon"><i
                                                                class="fas fa-receipt"></i></div>
                                                        <h5>Payment Summary</h5>
                                                    </div>
                                                    <div class="form-card-body">
                                                        <div class="info-grid">
                                                            <div class="info-chip">
                                                                <div class="info-chip-label">Payment For</div>
                                                                <div class="info-chip-value">
                                                                    <?= htmlspecialchars($feeType) ?>
                                                                </div>
                                                            </div>
                                                            <div class="info-chip">
                                                                <div class="info-chip-label">Amount Due</div>
                                                                <div class="info-chip-value highlight">₦<span
                                                                        id="amount"><?= number_format(($feeType == "School Fees" || $feeType == "School Fees (New Student)") ? $amountDue : $amount, 2) ?></span>
                                                                </div>
                                                            </div>
                                                            <div class="info-chip">
                                                                <div class="info-chip-label">Amount to Pay</div>
                                                                <div class="info-chip-value highlight">₦<span
                                                                        id="amounttopay"><?= number_format($payAmount, 2) ?></span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Payment Form -->
                                                <!-- Payment Method Toggle -->
                                                <div style="display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap;">
                                                    <button type="button" id="btnPayCard" onclick="switchPayMethod('card')"
                                                        style="flex:1;min-width:140px;height:46px;border-radius:12px;border:2px solid #6366f1;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;font-weight:700;font-size:.88rem;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;">
                                                        <i class="fas fa-credit-card"></i> Pay with Card
                                                    </button>
                                                    <?php if ($vaRow): ?>
                                                    <button type="button" id="btnPayTransfer" onclick="switchPayMethod('transfer')"
                                                        style="flex:1;min-width:140px;height:46px;border-radius:12px;border:2px solid #6366f1;background:#fff;color:#6366f1;font-weight:700;font-size:.88rem;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;">
                                                        <i class="fas fa-university"></i> Pay via Bank Transfer
                                                    </button>
                                                    <?php else: ?>
                                                    <div style="flex:1;min-width:140px;height:46px;border-radius:12px;border:2px solid #e2e8f0;background:#f8fafc;color:#94a3b8;font-weight:600;font-size:.82rem;display:flex;align-items:center;justify-content:center;gap:8px;">
                                                        <i class="fas fa-university"></i> Bank Transfer Unavailable
                                                    </div>
                                                    <?php endif; ?>
                                                </div>

                                                <!-- Bank Transfer Info Panel -->
                                                <?php if ($vaRow): ?>
                                                <div id="bankTransferInfoPanel" style="display:none;margin-bottom:20px;">
                                                    <div class="form-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f0fdf4);">
                                                        <div class="form-card-header" style="background:transparent;border-bottom:1px solid #bfdbfe;">
                                                            <div class="form-card-header-icon" style="background:linear-gradient(135deg,#3b82f6,#06b6d4);"><i class="fas fa-university"></i></div>
                                                            <h5 style="color:#1e40af;">Transfer to This Account</h5>
                                                        </div>
                                                        <div class="form-card-body">
                                                            <div class="info-grid" style="grid-template-columns:1fr 1fr 1fr;margin-bottom:16px;">
                                                                <div class="info-chip" style="border-color:#bfdbfe;background:#fff;">
                                                                    <div class="info-chip-label">Account Number</div>
                                                                    <div class="info-chip-value" style="color:#1e40af;font-size:1.1rem;letter-spacing:.05em;"><?= htmlspecialchars($vaRow['account_number']) ?></div>
                                                                </div>
                                                                <div class="info-chip" style="border-color:#bfdbfe;background:#fff;">
                                                                    <div class="info-chip-label">Bank Name</div>
                                                                    <div class="info-chip-value" style="color:#1e40af;"><?= htmlspecialchars($vaRow['bank_name']) ?></div>
                                                                </div>
                                                                <div class="info-chip" style="border-color:#bfdbfe;background:#fff;">
                                                                    <div class="info-chip-label">Account Name</div>
                                                                    <div class="info-chip-value" style="color:#1e40af;"><?= htmlspecialchars($vaRow['account_name']) ?></div>
                                                                </div>
                                                            </div>
                                                            <div class="notice-bar" style="background:#eff6ff;border-color:#bfdbfe;color:#1e40af;margin-bottom:0;">
                                                                <i class="fas fa-info-circle" style="color:#3b82f6;"></i>
                                                                <span>Fill in your email below, click <strong>Initiate Transfer</strong> to generate your payment reference, then transfer the <strong>exact amount</strong> to this account. After transferring, click "I Have Made the Transfer" to confirm.</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php endif; ?>

                                                <!-- Shared Student Details Form -->
                                                <div class="form-card">
                                                    <div class="form-card-header">
                                                        <div class="form-card-header-icon"><i class="fas fa-user"></i></div>
                                                        <h5>Payment Details</h5>
                                                    </div>
                                                    <div class="form-card-body">
                                                        <div class="notice-bar">
                                                            <i class="fas fa-exclamation-triangle"></i>
                                                            <span>Please ensure all details are correct before
                                                                proceeding with payment.</span>
                                                        </div>

                                                        <div style="margin-bottom:18px;">
                                                            <label class="field-label">Your Email</label>
                                                            <input type="email" id="email" class="wpf-input"
                                                                placeholder="Enter your email" required>
                                                        </div>
                                                        <input type="hidden" id="studentno"
                                                            value="<?= htmlspecialchars($_SESSION['studentRegNo']) ?>">
                                                        <input type="hidden" id="studentName"
                                                            value="<?= htmlspecialchars($_SESSION['studentName']) ?>">
                                                        <input type="hidden" id="feeType"
                                                            value="<?= htmlspecialchars($feeType) ?>">
                                                        <input type="hidden" id="stdid"
                                                            value="<?= $_SESSION['id'] ?>">
                                                        <input type="hidden" id="cls"
                                                            value="<?= htmlspecialchars($class) ?>">

                                                        <div class="section-divider"></div>

                                                        <!-- Card action panel -->
                                                        <div id="cardPaymentPanel" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
                                                            <button type="button" class="btn-pay-main"
                                                                onclick="savePaymentDataAndProceed()">
                                                                <i class="fas fa-credit-card"></i> Proceed to
                                                                Payment
                                                            </button>
                                                            <small style="color:#64748b;"><i class="fas fa-lock"
                                                                    style="color:#6366f1;"></i> Secured by
                                                                Paystack</small>
                                                        </div>

                                                        <!-- Bank transfer action panel -->
                                                        <?php if ($vaRow): ?>
                                                        <div id="bankTransferPanel" style="display:none;">
                                                            <div id="vaStatusArea" style="display:none;margin-bottom:16px;"></div>
                                                            <div id="vaReferenceArea" style="display:none;margin-bottom:16px;">
                                                                <div class="info-chip" style="border-color:#fde68a;background:#fffbeb;margin-bottom:12px;">
                                                                    <div class="info-chip-label" style="color:#92400e;">Your Payment Reference (keep this for your records)</div>
                                                                    <div id="vaReferenceValue" style="font-size:1.1rem;font-weight:800;color:#b45309;letter-spacing:.08em;margin-top:4px;"></div>
                                                                </div>
                                                                <p style="font-size:.78rem;color:#64748b;margin-bottom:12px;">
                                                                    <i class="fas fa-exclamation-triangle" style="color:#f59e0b;"></i>
                                                                    Transfer the <strong>exact amount</strong> shown above to the account. After transferring, click the button below. Reference expires in <span id="vaExpiryDisplay" style="font-weight:700;color:#dc2626;font-family:monospace;"></span>.
                                                                </p>
                                                                <button type="button" id="btnMadeTransfer" onclick="verifyVaTransfer()"
                                                                    style="height:46px;padding:0 28px;border-radius:12px;border:none;background:linear-gradient(135deg,#059669,#10b981);color:#fff;font-weight:700;font-size:.9rem;cursor:pointer;display:inline-flex;align-items:center;gap:8px;">
                                                                    <i class="fas fa-check-circle"></i> I Have Made the Transfer
                                                                </button>
                                                                <span id="vaRetryInfo" style="font-size:.75rem;color:#94a3b8;margin-left:10px;"></span>
                                                            </div>
                                                            <div style="margin-bottom:16px;">
                                                                <label class="field-label">Amount to Transfer (₦) — you may adjust if paying partially</label>
                                                                <input type="number" id="dva-amount" class="wpf-input" value="<?= $payAmount ?>" min="1" step="1">
                                                            </div>
                                                            <div id="vaInitiateArea">
                                                                <button type="button" id="btnInitiateTransfer" onclick="initiateVaTransfer()"
                                                                    style="height:46px;padding:0 28px;border-radius:12px;border:none;background:linear-gradient(135deg,#3b82f6,#06b6d4);color:#fff;font-weight:700;font-size:.9rem;cursor:pointer;display:inline-flex;align-items:center;gap:8px;">
                                                                    <i class="fas fa-paper-plane"></i> Initiate Transfer
                                                                </button>
                                                            </div>
                                                        </div>
                                                        <?php endif; ?>

                                                    </div>
                                                </div>

                                            </div>
                                        </div>
                                    </section>
                                </div>

                            </div><!-- /.wpf-wrapper -->
                        </div>
            </section>
        </div><!-- /.content-wrapper -->

        <?php @include("includes/footer.php"); ?>
        <?php @include("includes/foot.php"); ?>
    </div><!-- /.wrapper -->
    <script>
        const PAYSTACK_PUBLIC_KEY = "<?php echo $paystackPublicKey; ?>";

        // Debounced input listener for discount code
        let timeout;
        document.getElementById('discountCode').addEventListener('input', function () {
            clearTimeout(timeout);
            var discountCode = this.value.trim();
            var feeType = document.getElementById('feeType').value;
            var studentno = document.getElementById('studentno').value;

            if (discountCode) {
                timeout = setTimeout(function () {
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', 'check_discount_code.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            var response = JSON.parse(xhr.responseText);
                            if (response.success) {
                                document.getElementById('amount').innerText = response.newAmount.toFixed(2);
                                document.getElementById('discountAmount').innerText = 'Discount Applied: ₦' + response.discountAmount.toFixed(2);
                                document.getElementById('discountAmount').style.color = 'green'; // Success message in green
                            } else {
                                document.getElementById('amount').innerText = response.originalAmount.toFixed(2);
                                document.getElementById('discountAmount').innerText = 'Invalid Discount Code'; // Show invalid code message
                                document.getElementById('discountAmount').style.color = 'red'; // Error message in red
                            }
                        }
                    };
                    xhr.send('discount_code=' + encodeURIComponent(discountCode) + '&feeType=' + encodeURIComponent(feeType) + '&studentno=' + encodeURIComponent(studentno));
                }, 500); // Delay AJAX request by 500ms
            } else {
                document.getElementById('amount').innerText = <?php echo $amount; ?>;
                document.getElementById('discountAmount').innerText = 'Invalid Discount Code';
                document.getElementById('discountAmount').style.color = 'red';
            }
        });


        function payWithPaystack() {
            let email = document.getElementById("email").value;
            let studentno = document.getElementById("studentno").value;
            let amount = document.getElementById("amounttopay").textContent.replace(/[₦,]/g, '');
            let feeType = document.getElementById("feeType").value;
            let studentName = document.getElementById("studentName").value;
            let stdid = document.getElementById("stdid").value;
            let tab_id = "<?php echo $tabSessionID; ?>";

            if (!email || !studentno || !amount || !feeType || !studentName || !stdid) {
                alert("Email is required");
                return;
            }

            let handler = PaystackPop.setup({
                key: PAYSTACK_PUBLIC_KEY,
                email: email,
                amount: amount * 100, // Convert to kobo
                currency: "NGN",
                metadata: {
                    custom_fields: [{
                        display_name: "Fees Type",
                        variable_name: "feeType",
                        value: feeType
                    }, {
                        display_name: "Adm Session",
                        variable_name: "adm_session",
                        value: "<?php echo addslashes($admSession); ?>"
                    }, {
                        display_name: "Adm Term",
                        variable_name: "adm_term",
                        value: "<?php echo addslashes($admTerm); ?>"
                    }]
                },
                callback: function (response) {
                    let reference = response.reference;
                    window.location.href = `verify_paymentnb.php?reference=${reference}&studentno=${studentno}&email=${email}&studentName=${studentName}&stdid=${stdid}&tab_id=${tab_id}&adm_session=<?php echo urlencode($admSession); ?>&adm_term=<?php echo urlencode($admTerm); ?>`;
                },
                onClose: function () {
                    alert('Transaction was not completed, window closed.');
                }
            });
            handler.openIframe();
        }

        function startPayment() {
            $('#paystackRedirectModal').modal('hide'); // Close the modal first
            setTimeout(() => {
                payWithPaystack(); // Then call Paystack
            }, 400); // Wait briefly so modal hides smoothly
        }

        function savePaymentDataAndProceed() {
            // Gather inputs as variables first
            let email = document.getElementById("email").value;
            let studentno = document.getElementById("studentno").value;
            let amount = document.getElementById("amounttopay").textContent.replace(/[₦,]/g, '');
            let feeType = document.getElementById("feeType").value;
            let studentName = document.getElementById("studentName").value;
            let stdid = document.getElementById("stdid").value;
            let cls = document.getElementById("cls").value;



            // Build the data object to send
            const data = {
                email: email,
                studentno: studentno,
                payAmount: amount,
                feeType: feeType,
                studentName: studentName,
                stdid: stdid,
                class: cls
            };

            console.log('Sending data:', data);

            $.ajax({
                url: 'save_payment_data.php',
                method: 'POST',
                data: data,
                dataType: 'json',
                success: function (response) {
                    console.log('Server response:', response);
                    if (response.status === 'success') {
                        $('#paystackRedirectModal').modal('show');
                    } else {
                        alert('Failed to save payment data: ' + (response.message || 'Unknown error'));
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX error:', status, error);
                    alert('Request failed. Please try again later');
                }
            });
        }
    </script>
    <?php @include("includes/foot.php"); ?>


    <!-- Confirm Redirect Modal -->
    <div id="paystackRedirectModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="redirectModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content shadow-lg border-0 rounded">
                <div class="modal-header bg-gradient-warning text-dark">
                    <h5 class="modal-title font-weight-bold" id="redirectModalLabel">
                        <i class="fas fa-exclamation-circle text-secondary mr-2"></i> Please Read Before Proceeding
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                        style="font-size: 1.5rem;">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <div class="modal-body px-4 py-3">
                    <p style="font-size: 1rem;">
                        <i class="fas fa-info-circle text-warning mr-2"></i> After making payment on Paystack, you must
                        allow the system to <strong>redirect you back</strong> to this site.
                    </p>
                    <p style="font-size: 1rem;">
                        <i class="fas fa-exclamation-triangle text-danger mr-2"></i> Once redirected, wait for few
                        seconds for the system to redirect you to the payment approval request page.
                    </p>
                    <p style="font-size: 1rem;">
                        <i class="fas fa-check-circle text-success mr-2"></i> You <strong>must click the "Continue" BLUE
                            ROUND BUTTON</strong> on the approval request page to complete your payment approval.
                    </p>
                    <div class="alert alert-danger mt-3 mb-0 text-center">
                        <strong>Skipping this step may cause your payment to remain unverified!</strong>
                    </div>
                </div>

                <div class="modal-footer justify-content-between px-4 py-2">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times-circle"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-success font-weight-bold" onclick="startPayment()">
                        <i class="fas fa-credit-card"></i> Pay Now
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentPayMethod = 'card';
        let vaRetryCount = 0;
        let vaTransferRef = '';
        let vaCountdownTimer = null;

        function startCountdown(expiryDate) {
            if (vaCountdownTimer) clearInterval(vaCountdownTimer);
            var display = document.getElementById('vaExpiryDisplay');
            var btn = document.getElementById('btnMadeTransfer');

            function tick() {
                var now = new Date();
                var remaining = Math.floor((expiryDate - now) / 1000);
                if (remaining <= 0) {
                    clearInterval(vaCountdownTimer);
                    display.innerText = '00:00';
                    display.style.color = '#dc2626';
                    if (btn) btn.disabled = true;
                    document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fef2f2;border-color:#fecaca;color:#991b1b;"><i class="fas fa-clock" style="color:#dc2626;"></i><span> Reference expired. Please refresh the page to get a new one.</span></div>';
                    document.getElementById('vaStatusArea').style.display = 'block';
                    return;
                }
                var mins = Math.floor(remaining / 60);
                var secs = remaining % 60;
                var formatted = (mins < 10 ? '0' : '') + mins + ':' + (secs < 10 ? '0' : '') + secs;
                display.innerText = formatted;
                display.style.color = remaining <= 300 ? '#dc2626' : '#92400e';
            }
            tick();
            vaCountdownTimer = setInterval(tick, 1000);
        }

        function switchPayMethod(method) {
            currentPayMethod = method;
            var btnCard     = document.getElementById('btnPayCard');
            var btnTransfer = document.getElementById('btnPayTransfer');
            var cardPanel   = document.getElementById('cardPaymentPanel');
            var bankPanel   = document.getElementById('bankTransferPanel');
            var infoPanel   = document.getElementById('bankTransferInfoPanel');

            if (method === 'card') {
                btnCard.style.background = 'linear-gradient(135deg,#6366f1,#8b5cf6)';
                btnCard.style.color = '#fff';
                if (btnTransfer) { btnTransfer.style.background = '#fff'; btnTransfer.style.color = '#6366f1'; }
                cardPanel.style.display = 'flex';
                if (bankPanel) bankPanel.style.display = 'none';
                if (infoPanel) infoPanel.style.display = 'none';
            } else {
                btnCard.style.background = '#fff';
                btnCard.style.color = '#6366f1';
                if (btnTransfer) { btnTransfer.style.background = 'linear-gradient(135deg,#6366f1,#8b5cf6)'; btnTransfer.style.color = '#fff'; }
                cardPanel.style.display = 'none';
                if (bankPanel) bankPanel.style.display = 'block';
                if (infoPanel) infoPanel.style.display = 'block';
            }
        }

        function initiateVaTransfer() {
            var email       = document.getElementById('email').value.trim();
            var studentno   = document.getElementById('studentno').value;
            var studentName = document.getElementById('studentName').value;
            var stdid       = document.getElementById('stdid').value;
            var cls         = document.getElementById('cls').value;
            var feeType     = document.getElementById('feeType').value;
            var amount      = document.getElementById('dva-amount').value;
            var tab_id      = "<?php echo $tabSessionID ?? ''; ?>";

            if (!email) {
                alert('Please enter your email before initiating the transfer.');
                return;
            }

            var btn = document.getElementById('btnInitiateTransfer');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

            $.ajax({
                url: 'init_va_transfer.php',
                method: 'POST',
                data: { studentno: studentno, studentName: studentName, email: email,
                        fee_type: feeType, amount: amount, source_page: 'confirmpaynb',
                        tab_id: tab_id, student_id: stdid, class: cls },
                dataType: 'json',
                success: function(resp2) {
                    if (resp2.status === 'success') {
                        vaTransferRef = resp2.transfer_reference;
                        document.getElementById('vaReferenceValue').innerText = vaTransferRef;
                        document.getElementById('vaInitiateArea').style.display = 'none';
                        document.getElementById('vaReferenceArea').style.display = 'block';
                        startCountdown(new Date(resp2.expires_at));
                    } else {
                        alert('Failed to initiate transfer: ' + (resp2.message || 'Unknown error'));
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-paper-plane"></i> Initiate Transfer';
                    }
                },
                error: function() {
                    alert('Request failed. Please try again.');
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-paper-plane"></i> Initiate Transfer';
                }
            });
        }

        function verifyVaTransfer() {
            if (vaRetryCount >= 5) {
                alert('Maximum retry attempts reached. Please contact the school.');
                return;
            }
            var tab_id = "<?php echo $tabSessionID ?? ''; ?>";
            var btn = document.getElementById('btnMadeTransfer');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying...';
            document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#eff6ff;border-color:#bfdbfe;color:#1e40af;"><i class="fas fa-spinner fa-spin" style="color:#3b82f6;"></i><span> Checking with Paystack...</span></div>';
            document.getElementById('vaStatusArea').style.display = 'block';

            $.ajax({
                url: 'verify_va_transfer.php',
                method: 'POST',
                data: { transfer_reference: vaTransferRef, tab_id: tab_id },
                dataType: 'json',
                success: function(resp) {
                    if (resp.status === 'success') {
                        document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#f0fdf4;border-color:#bbf7d0;color:#065f46;"><i class="fas fa-check-circle" style="color:#059669;"></i><span> Payment verified! Redirecting...</span></div>';
                        setTimeout(function() { window.location.href = resp.redirect_url; }, 1500);
                    } else if (resp.status === 'not_received') {
                        vaRetryCount++;
                        document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fffbeb;border-color:#fde68a;color:#92400e;"><i class="fas fa-exclamation-triangle" style="color:#f59e0b;"></i><span> ' + resp.message + '</span></div>';
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-check-circle"></i> I Have Made the Transfer';
                        document.getElementById('vaRetryInfo').innerText = 'Attempt ' + vaRetryCount + ' of 5';
                        if (vaRetryCount >= 5) {
                            btn.disabled = true;
                            document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fef2f2;border-color:#fecaca;color:#991b1b;"><i class="fas fa-times-circle" style="color:#dc2626;"></i><span> Maximum retry attempts reached. Please contact the school.</span></div>';
                        }
                    } else if (resp.status === 'amount_mismatch') {
                        document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fef2f2;border-color:#fecaca;color:#991b1b;"><i class="fas fa-times-circle" style="color:#dc2626;"></i><span> ' + resp.message + ' Expected: ₦' + resp.expected + ', Received: ₦' + resp.received + '</span></div>';
                        btn.disabled = true;
                    } else if (resp.status === 'expired') {
                        document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fef2f2;border-color:#fecaca;color:#991b1b;"><i class="fas fa-clock" style="color:#dc2626;"></i><span> ' + resp.message + '</span></div>';
                        btn.disabled = true;
                    } else {
                        document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fef2f2;border-color:#fecaca;color:#991b1b;"><i class="fas fa-times-circle" style="color:#dc2626;"></i><span> ' + (resp.message || 'Verification failed') + '</span></div>';
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-check-circle"></i> I Have Made the Transfer';
                    }
                },
                error: function() {
                    document.getElementById('vaStatusArea').innerHTML = '<div class="notice-bar" style="background:#fef2f2;border-color:#fecaca;color:#991b1b;"><i class="fas fa-times-circle" style="color:#dc2626;"></i><span> Request failed. Please try again.</span></div>';
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-check-circle"></i> I Have Made the Transfer';
                }
            });
        }
    </script>

</body>

</html>