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

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

// Ensure session is valid
if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
    header('location:logoutstd.php');
    exit;
}

$eid2 = $_SESSION['student_id'];

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

// 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'];
} 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'); exit;
        exit;
    }
    $_SESSION['pay_amount'] = $payAmount;
} elseif (isset($_SESSION['pay_amount'])) {
    $payAmount = $_SESSION['pay_amount'];
} else {
    flash_alert('Payment amount is missing.', 'payschoolfeesnewb.php');
        header('Location: payschoolfeesnewb.php'); exit;
    exit;
}

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

$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 = $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;
}
?>
<!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); }
.discount-feedback { font-size:.82rem; margin-top:6px; font-weight:600; }
.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;}}
</style>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/headerstd.php"); ?>
        <?php @include("includes/sidebarstd.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="newstdday.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"></div></div>
            <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['studentno']) ?> &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($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 && in_array($feeType, ['School Fees'])): ?>
                                <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>
                                <?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 confirm the session and term you are paying for.</span>
                                </div>

                                <form method="POST" id="paymentForm">
                                    <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>
                                        <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'] ?>">
                                    </div>

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

                                    <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
                                        <button type="button" class="btn-pay-main" onclick="$('#paystackRedirectModal').modal('show')">
                                            <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>
                                </form>
                            </div>
                        </div>

                    </div>
                </div>
            </section>
                </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('₦', '').replace(',', '');
            let feeType = document.getElementById("feeType").value;
            let studentName = document.getElementById("studentName").value;
            let stdid = document.getElementById("stdid").value;

            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
                    }]
        },
                callback: function(response) {
                    let reference = response.reference;
                    window.location.href = `verify_paymentnd.php?reference=${reference}&studentno=${studentno}&email=${email}&studentName=${studentName}&stdid=${stdid}`;
                },
                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
        }
    </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>



</body>

</html>