<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');

require_once 'vendor/autoload.php'; // For dotenv and other dependencies

// Check if the session is valid
if (!isset($_SESSION['student_id']) || strlen($_SESSION['student_id']) == 0) {
    header('location:logoutstd.php');
    exit;
}
$eid2 = $_SESSION['student_id'];

// 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 (!$result) {
    die("Query failed: " . mysqli_error($con));
}

if ($row = $result->fetch_assoc()) {
    $adno = $row['studentno'];
    $stdname = $row['studentName'];
    $stdid = $row['id'];

    // Store details in session
    $_SESSION['studentno'] = $adno;
    $_SESSION['studentName'] = $stdname;
    $_SESSION['id'] = $stdid;
} else {
    echo "Invalid student ID.";
    exit;
}

// Load environment variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Retrieve Paystack public key
$paystackPublicKey = $_ENV['PAYSTACK_PUBLIC_KEY'];

// Fetch all fees dynamically
$feesQuery = "SELECT * FROM fees";
$feesResult = mysqli_query($con, $feesQuery);

if (!$feesResult) {
    die("Fees query failed: " . mysqli_error($con));
}

// Initialize variables for fee and discount
$discountAvailable = false;
$discountCode = "";
$discount = 0;
$amount = 0;
$feeType = "";
$class = "";

// If the fee type is eligible, fetch discount codes
if (isset($_GET['fee_id'])) {
    $feeId = intval($_GET['fee_id']);
    $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 if a discount code is still active
$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>
    <?php @include("includes/head.php"); ?>
    <script src="https://js.paystack.co/v1/inline.js"></script>
<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
    <?php @include("includes/headerstd.php"); ?>
    <?php @include("includes/sidebaroldstdboard.php"); ?>

    <div class="content-wrapper">
            <section class="content-header">
                <h1>Fees Payment</h1>
            </section>
            <section class="content">
                <div class="container-fluid">
                    <!-- Payment Confirmation Section -->
                    <?php if (isset($_GET['fee_id'])): ?>
                    <div class="card mt-4">
                        <div class="card-body">
                            <h4>Confirm Payment Details</h4>
                            <p><strong>Student's Fullname:</strong> <?php echo $_SESSION['studentName']; ?></p>
                            <p><strong>Admission No.:</strong> <?php echo $_SESSION['studentno']; ?></p>
                            <p><strong>Class:</strong> <?php echo $class; ?></p>
                            <p><strong>Fee Type:</strong> <?php echo $feeType; ?></p>
                            <p><strong>Amount:</strong> ₦<span id="amount"><?php echo number_format($amount, 2); ?></span></p>

                            <?php if ($discountAvailable && in_array($feeType, [
                                'JSS1 FULL (ONE TERM) SCHOOL FEES', 'JSS1 FULL (2 TERMS) SCHOOL FEES ', 'JSS1 FULL SESSION SCHOOL FEES ',
                                'JSS2 FULL (ONE TERM) SCHOOL FEES ', 'JSS2 FULL (2 TERMS) SCHOOL FEES ', 'JSS2 FULL SESSION SCHOOL FEES ',
                                'SSS1 FULL (ONE TERM) SCHOOL FEES ', 'SSS1 FULL (2 TERMS) SCHOOL FEES ', 'SSS1 FULL SESSION SCHOOL FEES ',
                                'SSS2 FULL (ONE TERM) SCHOOL FEES ', 'SSS2 FULL (2 TERMS) SCHOOL FEES ', 'SSS2 FULL SESSION SCHOOL FEES ',
                                'JSS3 FULL SESSION SCHOOL FEES ','SS3 FULL SESSION SCHOOL FEES '])): ?>
                                <div class="form-group">
                                    <label for="discountCode">Enter Discount Code</label>
                                    <input type="text" id="discountCode" class="form-control" name="discount_code" placeholder="Enter discount code" value="">
                                    <div id="discountAmount" style="margin-top: 10px;"></div>
                                </div>
                            <?php endif; ?>

                            <form method="POST" id="paymentForm">
                                <div class="form-group">
                                    <label for="email">Enter Your Email</label>
                                    <input type="email" id="email" class="form-control" placeholder="Enter your email" required>
                                    <input type="hidden" id="studentno" value="<?php echo $_SESSION['studentno']; ?>" required>
                                    <input type="hidden" id="studentName" value="<?php echo $_SESSION['studentName']; ?>" required>
                                    <input type="hidden" id="feeType" value="<?php echo $feeType; ?>">
                                    <input type="hidden" id="stdid" value="<?php echo $_SESSION['id']; ?>" required>
                                </div>
                                <center><button type="button" class="btn btn-primary" onclick="payWithPaystack()"> Pay  <i class="fa fa-credit-card"></i></button></center>
                            </form>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </section>
        </div>
        <?php @include("includes/footer.php"); ?>
    </div>

    <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("amount").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_paymentb1.php?reference=${reference}&studentno=${studentno}&email=${email}&studentName=${studentName}&stdid=${stdid}`;
                },
                onClose: function() {
                    alert('Transaction was not completed, window closed.');
                }
            });
            handler.openIframe();
        }
    </script>
    <?php @include("includes/foot.php"); ?>
</body>
</html>
