<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];
include('includes/flash.php');
// Use the session ID set in session.php

// Load dependencies
require_once 'vendor/autoload.php';



$eid2 = $_SESSION['student_id'];
// Fetch Wallet Balance
$wallet_query = mysqli_query($con, "SELECT balance FROM wallets WHERE student_id = '$eid2'");
$wallet = mysqli_fetch_assoc($wallet_query);
$currentBalance = $wallet['balance'] ?? 0;


// 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['studentno'] = $row['studentno'];
    $_SESSION['studentName'] = $row['studentName'];
    $_SESSION['id'] = $row['id'];
    $scholarship = $row['scholarship'];
    $stream = $row['stream'];
} 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: payschoolfees.php?tab_id=$tabSessionID");
        exit;
    }
    $_SESSION['pay_amount'] = $payAmount;
} elseif (isset($_SESSION['pay_amount'])) {
    $payAmount = $_SESSION['pay_amount'];
} else {
    flash_alert('Payment amount is missing.');
    header("Location: payschoolfees.php?tab_id=$tabSessionID");
    exit;
}

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

//Get amountDue for schoolfees
// Validate fee_id
if (isset($_GET['termdue']) || empty($_GET['termdue'])) {
    $amountDue = intval($_GET['termdue']);
}

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

// 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 = $_SESSION['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;
}

// check if the student is eligible for scholarship discount
// Fetch full school fee for this student

$Fee = 0; // Default

// Default school fees
$feeQuery = mysqli_query($con, "
    SELECT amount 
    FROM fees 
    WHERE class = '$class' 
      AND stream = '$stream' 
      AND student_type = 'Old' 
      AND name = 'School Fees' 
    LIMIT 1
");

if ($feeQuery && mysqli_num_rows($feeQuery) > 0) {
    $row = mysqli_fetch_assoc($feeQuery);
    $Fee = $row['amount'];
}

// Special overrides for First Term
if ($currentTermName === "First Term") {
    if ($class === "SS 1") {
        $overrideQuery = mysqli_query($con, "
            SELECT amount 
            FROM fees 
            WHERE class = '$class' 
              AND stream = '$stream' 
              AND student_type = 'Old' 
              AND name = 'First Term SS 1 School Fees' 
            LIMIT 1
        ");
    } elseif ($class === "JSS 3") {
        $overrideQuery = mysqli_query($con, "
            SELECT amount 
            FROM fees 
            WHERE class = '$class' 
              AND stream = '$stream' 
              AND student_type = 'Old' 
              AND name = 'First Term JSS 3 School Fees' 
            LIMIT 1
        ");
    } elseif ($class === "SS 3") {
        $overrideQuery = mysqli_query($con, "
            SELECT amount 
            FROM fees 
            WHERE class = '$class' 
              AND stream = '$stream' 
              AND student_type = 'Old' 
              AND name = 'First Term SS 3 School Fees' 
            LIMIT 1
        ");
    }

    // Apply override if found
    if (isset($overrideQuery) && $overrideQuery && mysqli_num_rows($overrideQuery) > 0) {
        $row = mysqli_fetch_assoc($overrideQuery);
        $Fee = $row['amount'];
    }
}



?>
<!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: 860px;
        margin: 0 auto;
        padding: 0 0 40px;
    }

    .student-hero {
        background: linear-gradient(135deg, var(--dark), var(--primary)); color:#fff;
        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, var(--primary), var(--primary));
        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;
    }

    .hero-badge {
        background: linear-gradient(135deg, var(--primary), var(--dark));
        border: 1px solid rgba(255, 255, 255, .12);
        border-radius: 10px;
        padding: 10px 18px;
        text-align: right;
        color:#fff;
    }

    .hero-badge-label {
        font-size: .65rem;
        text-transform: uppercase;
        letter-spacing: .1em;
        color: #fff;
        
    }

    .hero-badge-amount {
        font-size: 1.4rem;
        font-weight: 800;
        color: #fff;
        line-height: 1.2;
    }

    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 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;
    }

    .select2-container {
        width: 100% !important;
    }

    .select2-container--default .select2-selection--single {
        height: 44px !important;
        border: 1.5px solid #e2e8f0 !important;
        border-radius: 12px !important;
        background: #f8fafc !important;
        display: flex;
        align-items: center;
        padding: 0 14px;
    }

    .select2-container--default.select2-container--open .select2-selection--single,
    .select2-container--default.select2-container--focus .select2-selection--single {
        border-color: #6366f1 !important;
        box-shadow: 0 0 0 4px rgba(99, 102, 241, .1) !important;
        background: #fff !important;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: #0f172a;
        font-size: .88rem;
        line-height: 44px !important;
        padding: 0;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 44px !important;
        right: 12px;
    }

    .select2-dropdown {
        border: 1.5px solid #e2e8f0 !important;
        border-radius: 12px !important;
        box-shadow: 0 10px 40px rgba(15, 23, 42, .12) !important;
        overflow: hidden;
    }

    .select2-container--default .select2-results__option--highlighted {
        background: #6366f1 !important;
    }

    .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;
    }

    .pay-method-card {
        border: 1.5px solid #e2e8f0;
        border-radius: 16px;
        padding: 20px;
        text-align: center;
        transition: border-color .2s, box-shadow .2s;
    }

    .pay-method-card:hover {
        border-color: #6366f1;
        box-shadow: 0 4px 20px rgba(99, 102, 241, .1);
    }

    .pay-method-card h6 {
        font-weight: 700;
        color: #0f172a;
        margin-bottom: 6px;
    }

    .pay-method-card .balance-text {
        font-size: .82rem;
        color: #64748b;
        margin-bottom: 12px;
    }

    .btn-pay-card {
        color: #fff;
        border: none;
        height: 44px;
        padding: 0 28px;
        border-radius: 12px;
        font-size: .88rem;
        font-weight: 700;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        transition: transform .15s, box-shadow .15s;
    }

    .btn-pay-card:hover:not(:disabled) {
        transform: translateY(-2px);
    }

    .btn-pay-card:disabled {
        opacity: .5;
        cursor: not-allowed;
    }

    .discount-feedback {
        font-size: .82rem;
        margin-top: 6px;
        font-weight: 600;
    }

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

    .hint-text {
        font-size: .72rem;
        color: #ef4444;
        margin-top: 4px;
        display: block;
    }

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

        .hero-badge {
            width: 100%;
            text-align: left;
        }

        .info-grid {
            grid-template-columns: 1fr 1fr;
        }

        .pay-method-card {
            margin-bottom: 12px;
        }
    }
</style>


<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/headerstd.php"); ?>
        <?php @include("includes/sidebaroldstd.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="oldstdday.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">ADM:
                                                                    <?= htmlspecialchars($_SESSION['studentno']) ?>
                                                                    &nbsp;·&nbsp; <?= htmlspecialchars($class) ?></p>
                                                            </div>
                                                        </div>
                                                        <div class="hero-badge">
                                                            <p class="hero-badge-label">Wallet Balance</p>
                                                            <p class="hero-badge-amount">
                                                                ₦<?= number_format($currentBalance, 2) ?></p>
                                                        </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>

                                                        <?php if ($discountAvailable && $feeType === 'School Fees' && $scholarship === 'Yes' && $payAmount == $Fee): ?>
                                                                <div class="section-divider"></div>
                                                                <div style="margin-bottom:16px;">
                                                                    <label class="field-label">Discount Code</label>
                                                                    <input type="text" id="discountCode" class="wpf-input"
                                                                        placeholder="Enter discount code">
                                                                    <div id="discountAmount" class="discount-feedback"></div>
                                                                </div>
                                                                <input type="hidden" id="payAmount" value="<?= $payAmount ?>">
                                                        <?php endif; ?>
                                                    </div>
                                                </div>

                                                <!-- Payment Form -->
                                                <div class="form-card">
                                                    <div class="form-card-header">
                                                        <div class="form-card-header-icon"><i
                                                                class="fas fa-credit-card"></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. Always double-check the session and
                                                                term.</span>
                                                        </div>

                                                        <form method="POST" id="paymentForm">
                                                            <div class="row">
                                                                <div class="col-md-4" style="margin-bottom:18px;">
                                                                    <label class="field-label">Your Email</label>
                                                                    <input type="email" id="email" class="wpf-input"
                                                                        placeholder="Enter your email" required>
                                                                    <input type="hidden" id="studentno"
                                                                        value="<?= htmlspecialchars($_SESSION['studentno']) ?>">
                                                                    <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" name="payAmount"
                                                                        value="<?= $payAmount ?>">
                                                                    <input type="hidden" name="class"
                                                                        value="<?= htmlspecialchars($class) ?>">
                                                                    <input type="hidden" name="sessionName"
                                                                        value="<?= htmlspecialchars($currentSessionName) ?>">
                                                                    <input type="hidden" name="termName"
                                                                        value="<?= htmlspecialchars($currentTermName) ?>">
                                                                    <input type="hidden" name="fee_id"
                                                                        value="<?= $feeId ?>">
                                                                    <input type="hidden" name="amountDue"
                                                                        value="<?= $amountDue ?? 0 ?>">
                                                                </div>
                                                                <div class="col-md-4" style="margin-bottom:18px;">
                                                                    <label class="field-label">Academic Session</label>
                                                                    <select name="session_id" id="session_id"
                                                                        class="select2-field" required>
                                                                        <option value="">-- Select Session --</option>
                                                                        <?php
                                                                        $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");
                                                                        while ($row = $sessionResult->fetch_assoc()) {
                                                                            echo "<option value='{$row['session_name']}'>{$row['session_name']}</option>";
                                                                        }
                                                                        ?>
                                                                    </select>
                                                                    <span class="hint-text">Make sure you select the
                                                                        correct Session</span>
                                                                </div>
                                                                <div class="col-md-4" style="margin-bottom:18px;">
                                                                    <label class="field-label">Term</label>
                                                                    <select name="term_id" id="term_id"
                                                                        class="select2-field" required>
                                                                        <option value="">-- Select Term --</option>
                                                                    </select>
                                                                    <span class="hint-text">Make sure you select the
                                                                        correct term</span>
                                                                </div>
                                                            </div>

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

                                                            <div class="row">
                                                                <div class="col-md-6" style="margin-bottom:12px;">
                                                                    <div class="pay-method-card">
                                                                        <h6><i class="fas fa-credit-card mr-1"
                                                                                style="color:#6366f1;"></i> Pay via Card
                                                                            / Bank</h6>
                                                                        <p class="balance-text"><i class="fas fa-lock"
                                                                                style="color:#6366f1;"></i> Secured by
                                                                            Paystack</p>
                                                                        <?php if ($currentBalance >= $payAmount): ?>
                                                                            <button type="button" class="btn-pay-card"
                                                                                style="background:#94a3b8;" disabled title="Your wallet balance covers this payment. Please use wallet instead.">
                                                                                Proceed to Paystack <i class="fas fa-arrow-right"></i>
                                                                            </button>
                                                                            <div style="font-size:.75rem;color:#64748b;margin-top:6px;">
                                                                                <i class="fas fa-info-circle"></i> Use your wallet for instant approval.
                                                                            </div>
                                                                        <?php else: ?>
                                                                            <button type="button" class="btn-pay-card"
                                                                                style="background:linear-gradient(135deg,#6366f1,#8b5cf6);"
                                                                                onclick="savePaymentDataAndProceed()">
                                                                                Proceed to Paystack <i
                                                                                    class="fas fa-arrow-right"></i>
                                                                            </button>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </div>
                                                                <div class="col-md-6" style="margin-bottom:12px;">
                                                                    <div class="pay-method-card">
                                                                        <h6><i class="fas fa-wallet mr-1"
                                                                                style="color:#10b981;"></i> Pay via
                                                                            School Wallet</h6>
                                                                        <p class="balance-text">Balance: <strong
                                                                                style="color:#10b981;">₦<?= number_format($currentBalance, 2) ?></strong>
                                                                        </p>
                                                                        <?php if ($currentBalance >= $payAmount): ?>
                                                                                <button type="button" class="btn-pay-card"
                                                                                    style="background:linear-gradient(135deg,#10b981,#059669);"
                                                                                    onclick="saveWalletPaymentDataAndProceed()">
                                                                                    Pay from Wallet <i
                                                                                        class="fas fa-check-circle"></i>
                                                                                </button>
                                                                        <?php else: ?>
                                                                                <button type="button" class="btn-pay-card"
                                                                                    style="background:#94a3b8;" disabled>
                                                                                    Insufficient Balance <i
                                                                                        class="fas fa-exclamation-triangle"></i>
                                                                                </button>
                                                                                <div
                                                                                    style="font-size:.75rem;color:#ef4444;margin-top:6px;">
                                                                                    Top up your wallet to use this method.</div>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </form>
                                                    </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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.select2-field').select2({ width: '100%' });
        });
    </script>

    <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('amounttopay').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('amounttopay').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
                            }
                        }
                    };
                    var payAmount = document.getElementById('payAmount')?.value || '0';

                    xhr.send(
                        'discount_code=' + encodeURIComponent(discountCode) +
                        '&feeType=' + encodeURIComponent(feeType) +
                        '&studentno=' + encodeURIComponent(studentno) +
                        '&payAmount=' + encodeURIComponent(payAmount)
                    );
                }, 500); // Delay AJAX request by 500ms
            } else {
                document.getElementById('amounttopay').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 session = document.getElementById("session_id").value;
            let term = document.getElementById("term_id").value;
            let tab_id = "<?php echo $tabSessionID; ?>";
            let discountCode = document.getElementById("discountCode")?.value ?? "";
            let discountText = document.getElementById("discountAmount")?.innerText;

            let usedDiscount = discountText?.toLowerCase().includes("₦") ? "Yes" : "No";
            let discountAmount = 0,
                discountPercent = 0;

            if (usedDiscount === "Yes") {
                let originalAmountToPay = <?php echo json_encode($payAmount); ?>;
                let amountToPay = parseFloat(amount);
                discountAmount = originalAmountToPay - amountToPay;
                discountPercent = (discountAmount / originalAmountToPay) * 100;
            }

            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",
                        value: feeType
                    },
                    {
                        display_name: "Used Discount",
                        value: usedDiscount
                    },
                    {
                        display_name: "Discount Amount",
                        value: discountAmount.toFixed(2)
                    },
                    {
                        display_name: "Discount Percent",
                        value: discountPercent.toFixed(2)
                    }
                    ]
                },
                callback: function (response) {
                    let reference = response.reference;
                    window.location.href = `verify_payment.php?reference=${reference}&studentno=${studentno}&email=${email}&studentName=${studentName}&stdid=${stdid}&tab_id=${tab_id}&session=${session}&term=${term}`;
                },
                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 startWalletPayment() {
            $('#WalletRedirectModal').modal('hide'); // Close the modal first
            setTimeout(() => {
                payWithWallet(); // Then call Paystack
            }, 400); // Wait briefly so modal hides smoothly
        }

        function payWithWallet() {
            // 1. Gather all data up front
            const studentno = document.getElementById("studentno").value;
            const email = document.getElementById("email").value;
            const studentName = document.getElementById("studentName").value;
            const stdid = document.getElementById("stdid").value;
            const session = document.getElementById("session_id").value;
            const term = document.getElementById("term_id").value;
            const feeType = document.getElementById("feeType").value;
            const amount = document.getElementById("amounttopay").textContent.replace(/[₦,]/g, '');
            const tab_id = "<?php echo $tabSessionID; ?>";
            const fee_id = document.querySelector('input[name="fee_id"]').value;

            // Handle Discounts
            const discountText = document.getElementById("discountAmount")?.innerText || "";
            const discount_used = discountText.toLowerCase().includes("₦") ? "Yes" : "No";
            let discount_amount = "0.00";
            let discount_percent = "0.00";

            if (discount_used === "Yes") {
                const originalAmount = parseFloat(<?php echo json_encode($payAmount); ?>);
                const finalAmount = parseFloat(amount);
                discount_amount = (originalAmount - finalAmount).toFixed(2);
                discount_percent = ((discount_amount / originalAmount) * 100).toFixed(2);
            }

            // 2. Validation
            if (!session || !term || !email) {
                alert("Please fill in all details before proceeding.");
                return;
            }

            if (!confirm(`Confirm payment of ₦${amount} from wallet?`)) return;

            // 3. The Request
            $.ajax({
                url: 'process_wallet_payment.php',
                method: 'POST',
                data: {
                    stdid: stdid,
                    amount: amount,
                    fee_id: fee_id,
                    feeType: feeType,
                    email: email,
                    studentno: studentno,
                    session: session
                },
                dataType: 'json',
                success: function (response) {
                    console.log("Response Received:", response);

                    if (response.status === 'success') {
                        // Use the variables we defined at the top
                        const params = new URLSearchParams({
                            reference: response.reference,
                            studentno: studentno,
                            email: email,
                            studentName: studentName,
                            stdid: stdid,
                            tab_id: tab_id,
                            session: session,
                            term: term,
                            discount_used: discount_used,
                            discount_amount: discount_amount,
                            discount_percent: discount_percent,
                            fee_type: feeType,
                            amount: amount
                        });

                        window.location.href = "verify_wallet_payment.php?" + params.toString();
                    } else {
                        alert("Error: " + response.message);
                    }
                },
                error: function (xhr) {
                    console.error("Critical Error:", xhr.responseText);
                    // Try to parse error message from response
                    try {
                        const errData = JSON.parse(xhr.responseText);
                        alert("Payment failed: " + (errData.message || "Unknown error. Please try again."));
                    } catch (e) {
                        alert("Payment failed. Please try again or contact support.");
                    }
                }
            });
        }

        function savePaymentDataAndProceed() {
            const data = {
                email: document.getElementById('email').value,
                studentno: document.getElementById('studentno').value,
                studentName: document.getElementById('studentName').value,
                feeType: document.getElementById('feeType').value,
                stdid: document.getElementById('stdid').value,
                payAmount: document.querySelector('input[name="payAmount"]').value,
                class: document.querySelector('input[name="class"]').value,
                sessionName: document.querySelector('input[name="sessionName"]').value,
                termName: document.querySelector('input[name="termName"]').value,
                fee_id: document.querySelector('input[name="fee_id"]').value,
                amountDue: document.querySelector('input[name="amountDue"]').value,
                session_id: document.getElementById('session_id').value,
                term_id: document.getElementById('term_id').value
            };

            // Discount info
            let discountCode = document.getElementById("discountCode")?.value || "";
            let discountText = document.getElementById("discountAmount")?.innerText || "";
            let amount = document.getElementById("amounttopay")?.textContent.replace(/[₦,]/g, '') || "";

            let usedDiscount = discountText.toLowerCase().includes("₦") ? "Yes" : "No";
            let discountAmount = 0;
            let discountPercent = 0;

            if (usedDiscount === "Yes") {
                let originalAmountToPay = <?php echo json_encode($payAmount); ?>;
                let amountToPay = parseFloat(amount);
                discountAmount = originalAmountToPay - amountToPay;
                discountPercent = (discountAmount / originalAmountToPay) * 100;
            }

            // Add discount info to data
            data.discountCode = discountCode;
            data.discount_used = usedDiscount;
            data.discount_amount = discountAmount.toFixed(2);
            data.discount_percent = discountPercent.toFixed(2);

            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');
                }
            });
        }


        function saveWalletPaymentDataAndProceed() {
            const data = {
                email: document.getElementById('email').value,
                studentno: document.getElementById('studentno').value,
                studentName: document.getElementById('studentName').value,
                feeType: document.getElementById('feeType').value,
                stdid: document.getElementById('stdid').value,
                payAmount: document.querySelector('input[name="payAmount"]').value,
                class: document.querySelector('input[name="class"]').value,
                sessionName: document.querySelector('input[name="sessionName"]').value,
                termName: document.querySelector('input[name="termName"]').value,
                fee_id: document.querySelector('input[name="fee_id"]').value,
                amountDue: document.querySelector('input[name="amountDue"]').value,
                session_id: document.getElementById('session_id').value,
                term_id: document.getElementById('term_id').value
            };

            // Discount info
            let discountCode = document.getElementById("discountCode")?.value || "";
            let discountText = document.getElementById("discountAmount")?.innerText || "";
            let amount = document.getElementById("amounttopay")?.textContent.replace(/[₦,]/g, '') || "";

            let usedDiscount = discountText.toLowerCase().includes("₦") ? "Yes" : "No";
            let discountAmount = 0;
            let discountPercent = 0;

            if (usedDiscount === "Yes") {
                let originalAmountToPay = <?php echo json_encode($payAmount); ?>;
                let amountToPay = parseFloat(amount);
                discountAmount = originalAmountToPay - amountToPay;
                discountPercent = (discountAmount / originalAmountToPay) * 100;
            }

            // Add discount info to data
            data.discountCode = discountCode;
            data.discount_used = usedDiscount;
            data.discount_amount = discountAmount.toFixed(2);
            data.discount_percent = discountPercent.toFixed(2);

            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') {
                        $('#WalletRedirectModal').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"); ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const termSelect = document.getElementById('term_id');
            const studentClass = "<?php echo strtoupper($_SESSION['class']); ?>";

            // PHP provides DB-based term list
            const dbTerms = <?php
            $termOptions = [];
            $termResult = $con->query("SELECT DISTINCT term_name FROM school_terms ORDER BY term_name ASC");
            while ($row = $termResult->fetch_assoc()) {
                $termOptions[] = $row['term_name'];
            }
            echo json_encode($termOptions);
            ?>;

            let options = '<option value="">-- Select Term --</option>';

            if (studentClass === "JSS 3" || studentClass === "SS 3") {
                options += `
                <option value="Full Session">Full Session (First, Second & Third Term)</option>
                <option value="Full Session 2 Instalment">Full Session in 2 Instalments</option>
                <option value="Full Session 3 Instalment">Full Session in 3 Instalments</option>
            `;
            } else {
                options += `
                <option value="Full Session">Full Session (First, Second & Third Term)</option>
                <option value="First Term and Second Term">Two Terms (First & Second Term)</option>
                <option value="Second Term and Third Term">Two Terms (Second & Third Term)</option>
            `;
            }

            dbTerms.forEach(term => {
                options += `<option value="${term}">${term}</option>`;
            });

            options += `
                <option value="Fourth Term">Fourth Term</option>`;

            termSelect.innerHTML = options;
        });
    </script>

    <!-- 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>



    <!-- Wallet Confirm Redirect Modal -->
    <div id="WalletRedirectModal" 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> Your wallet balance will be deducted immediately upon confirmation.
                    </p>
                    <p style="font-size: 1rem;">
                        <i class="fas fa-check-circle text-success mr-2"></i> Wallet payments are <strong>approved instantly</strong> — no admin action required.
                    </p>
                    <p style="font-size: 1rem;">
                        <i class="fas fa-envelope text-primary mr-2"></i> A confirmation email will be sent to you once the payment is processed.
                    </p>
                    <div class="alert alert-info mt-3 mb-0 text-center">
                        <strong>Do not close this window until you are redirected back to the portal.</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="startWalletPayment()">
                        <i class="fas fa-credit-card"></i> Pay Now
                    </button>
                </div>
            </div>
        </div>
    </div>





</body>

</html>