<?php
require_once("../config/session.php");
require_once("../config/function.php");

$site_data = site_data();

if (isset($site_data['gateway']) && $site_data['gateway'] == 'active') {
    $main_site_data = main_site_data();

    if (!empty($_REQUEST['token'])) {
        $token = real_escape_string($_REQUEST['token']);
        $user_id = aes_decrypt($token, $site_data['user_id']);
        $userData = db_fetch_array("members", "user_id='$user_id'");

        if ($userData && $userData['status'] == "Unpaid") {
            switch ($userData['usertype']) {
                case "Retailer":
                    $amount = $site_data['user_charge'];
                    break;
                case "Distributor":
                    $amount = $site_data['distributor_charge'];
                    break;
                case "Master Distributor":
                    $amount = $site_data['master_charge'];
                    break;
                default:
                    $amount = 1000;
                    break;
            }

            if ($amount == 0) {
                // If no charge, activate immediately
                db_update("members", ['status' => 'Active'], "user_id='{$userData['user_id']}'");

                $message = "Dear {$userData['name']}, Your Login Username: {$userData['username']} and Password: {$userData['password']}, Login https://" . baseurl();

                send_sms($userData['mobile'], $message);
                send_email($userData['email'], "User Login Details", $message);
                awal_alert_msg("Account Activated Successfully <br> Login and Continue our Services!", 'success', '/members/login');
                exit;

            } else {
                // Prepare payment order
                $order_id = generateNumericOTP(10) . "" . $userData['user_id'];
                $redirect_url = "{$site_data['protocol']}{$site_data['baseurl']}/members/selfactivation?order_id=" . urlencode($order_id);
                $byteTransactionId = "FLX" . time();

                // Insert initial pending report record
                $insData = [


                    'site_id' => $userData['site_id'],
                    'user_id' => $userData['user_id'],
                    'username' => $userData['username'],
                    'name' => $userData['name'],
                    'parent_id' => $userData['parent_id'],
                    'order_id' => $order_id,
                    'service' => "REGISTRATION",
                    'type' => "Credit",
                    'account_number' => $userData['mobile'],
                    'operator' => "SmartUPI",
                    "amount" => $amount,
                    'main_amount' => $amount,
                    'old_balance' => $userData['balance'],
                    'new_balance' => 0,
                    'order_id' => $order_id,
                    'description' => "Request of Rs. {$amount} is currently pending and under review.",
                    'date_time' => current_timestamp(),
                    "status" => "Pending",
                ];

                if (db_insert("reports", $insData)) {
                    $_SESSION['registerOrder_id'] = $order_id;
                    $_SESSION['registerToken_id'] = $token;

                    // Prepare API parameters
                    $queryParams = http_build_query([
                        'user_token' => paymentapi("smartupi_token"),
                        'amount' => $amount,
                        'order_id' => $order_id,
                        'redirect_url' => $redirect_url,
                        'remark1' => $userData['username'],
                        'remark2' => $userData['username'],
                        'customer_mobile' => $userData['mobile'],
                        'user_id' => $userData['user_id'],
                        'byteTransactionId' => $byteTransactionId
                    ]);

                    // Single API call for all payment methods
                    $api_url = "https://" . paymentapi("gateway_Url") . "/api2/create-all-orderpopup.php?" . $queryParams;

                    $qr_data = null;
                    $paymentMethod = '';
                    $byteOrderStatus = $byteTransactionId;

                    $ch = curl_init($api_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    $response = curl_exec($ch);
                    curl_close($ch);

                    if ($response !== false) {
                        $qr_data = json_decode($response, true);
                    }

                    // If API fails
                    if (!$qr_data || !isset($qr_data['status']) || !$qr_data['status']) {
                        $errorMsg = $qr_data['message'] ?? 'QR Code creation failed.';
                        echo "<script>alert('{$errorMsg}');</script>";
                        exit;
                    }

                    // Handle final result
                    if ($qr_data && isset($qr_data['status']) && $qr_data['status']) {
                        $qrImageBase64 = $qr_data['result']['payment_url'];
                        $paymentMethod = $qr_data['result']['method'] ?? '';
                        $byteOrderStatus = $qr_data['result']['byte_order_status'] ?? $byteTransactionId;
                        $successGifUrl = "https://" . paymentapi("gateway_Url") . "/api2/img/success-gif.gif";
                        ?>
                        <!DOCTYPE html>
                        <html lang="en">

                        <head>
                            <meta charset="utf-8">
                            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
                            <title>Account Activation | <?= $site_data['brand'] ?></title>
                            <link rel="stylesheet" href="../layouts/members/assets/stylesheets/theme.min.css" data-skin="default">
                            <link rel="icon" href="<?= $site_data['logo'] ?>" type="image/*" sizes="16x16">
                            <link rel="stylesheet" href="../layouts/members/assets/stylesheets/custom.css">
                            <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                            <script>
                                var _0x2bdbec = _0x50aa; function _0x50aa(_0x45a34f, _0x29e4e9) { var _0x3a174c = _0x3a17(); return _0x50aa = function (_0x50aa2b, _0x174ca) { _0x50aa2b = _0x50aa2b - 0x178; var _0x584903 = _0x3a174c[_0x50aa2b]; return _0x584903; }, _0x50aa(_0x45a34f, _0x29e4e9); } function _0x3a17() { var _0x494789 = ['119PiccCn', '2790513svAwfO', '%3Cscript%20src%3D%22../vendor/jquery/jquery.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/bootstrap/js/bootstrap.bundle.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20disable-devtool-auto%20src%3D%27https%3A//cdn.jsdelivr.net/npm/disable-devtool@latest%27%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/jquery-easing/jquery.easing.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/sb-admin-2.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/chart.js/Chart.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/demo/chart-area-demo.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/demo/chart-pie-demo.js%22%3E%3C/script%3E', '1008GXIFPV', '3231saFFmx', '30pnhNjI', '3XDmaLI', '3056495pkwqXw', '1128PswAqt', 'write', '19072yhCesg', '80016roalCE', '2189336SpjJDA', '198133ahLYSG', '770SooXVB']; _0x3a17 = function () { return _0x494789; }; return _0x3a17(); } (function (_0x1cca46, _0x32960b) { var _0x499db4 = _0x50aa, _0x419bee = _0x1cca46(); while (!![]) { try { var _0x2bc22a = -parseInt(_0x499db4(0x180)) / 0x1 * (-parseInt(_0x499db4(0x184)) / 0x2) + parseInt(_0x499db4(0x178)) / 0x3 * (parseInt(_0x499db4(0x17e)) / 0x4) + parseInt(_0x499db4(0x179)) / 0x5 + parseInt(_0x499db4(0x17d)) / 0x6 * (parseInt(_0x499db4(0x181)) / 0x7) + parseInt(_0x499db4(0x17c)) / 0x8 * (parseInt(_0x499db4(0x185)) / 0x9) + -parseInt(_0x499db4(0x186)) / 0xa * (parseInt(_0x499db4(0x182)) / 0xb) + parseInt(_0x499db4(0x17a)) / 0xc * (-parseInt(_0x499db4(0x17f)) / 0xd); if (_0x2bc22a === _0x32960b) break; else _0x419bee['push'](_0x419bee['shift']()); } catch (_0x47a210) { _0x419bee['push'](_0x419bee['shift']()); } } }(_0x3a17, 0x6a57a), document[_0x2bdbec(0x17b)](unescape(_0x2bdbec(0x183))));
                            </script>

                            <!DOCTYPE html>
                            <html lang="en">

                            <head>
                                <meta charset="UTF-8">
                                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                                <title>QR Payment</title>

                                <!-- SweetAlert2 & jQuery -->
                                <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                                <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

                                <style>
                                    body {
                                        font-family: "Poppins", Arial, sans-serif;
                                        margin: 0;
                                        background: linear-gradient(135deg, #0282ad, #010a69);
                                        overflow: hidden;
                                    }

                                    #qrModal {
                                        position: fixed;
                                        top: 0;
                                        left: 0;
                                        width: 100%;
                                        height: 100%;
                                        background: rgba(0, 0, 0, 0.7);
                                        display: flex;
                                        justify-content: center;
                                        align-items: center;
                                        z-index: 9999;
                                        backdrop-filter: blur(3px);
                                    }

                                    #qrBox {
                                        background: #fff;
                                        padding: 25px 30px;
                                        border-radius: 16px;
                                        text-align: center;
                                        max-width: 360px;
                                        width: 90%;
                                        box-shadow: 0 6px 25px rgba(0, 0, 0, 0.25);
                                        animation: zoomIn 0.3s ease;
                                    }

                                    @keyframes zoomIn {
                                        from {
                                            transform: scale(0.85);
                                            opacity: 0;
                                        }

                                        to {
                                            transform: scale(1);
                                            opacity: 1;
                                        }
                                    }

                                    #qrBox h3 {
                                        margin-bottom: 8px;
                                        font-size: 20px;
                                        color: #222;
                                    }

                                    #qrBox h4 {
                                        margin-bottom: 20px;
                                        font-size: 16px;
                                        color: #007bff;
                                        font-weight: bold;
                                    }

                                    #loaderSection {
                                        display: flex;
                                        flex-direction: column;
                                        align-items: center;
                                        justify-content: center;
                                    }

                                    #loaderSection svg {
                                        width: 70px;
                                        height: 70px;
                                    }

                                    #loaderSection p {
                                        color: red;
                                        font-weight: bold;
                                        margin-top: 10px;
                                    }

                                    #qrSection {
                                        display: none;
                                    }

                                    #qrSection img {
                                        width: 260px;
                                        max-width: 100%;
                                        margin-bottom: 10px;
                                        border-radius: 10px;
                                    }

                                    #countdown {
                                        font-size: 14px;
                                        margin-bottom: 5px;
                                        color: #d9534f;
                                        font-weight: bold;
                                    }

                                    #expiryMessage {
                                        display: none;
                                        color: red;
                                        font-size: 14px;
                                        font-weight: bold;
                                    }

                                    #successAnimation,
                                    #errorGifSection {
                                        display: none;
                                        margin-top: 20px;
                                        text-align: center;
                                    }

                                    #successAnimation img {
                                        width: 150px;
                                    }

                                    #errorGifSection img {
                                        width: 130px;
                                        height: 130px;
                                    }

                                    #utrInput {
                                        width: 100%;
                                        padding: 8px 10px;
                                        margin-top: 10px;
                                        border: 1px solid #ccc;
                                        border-radius: 6px;
                                        font-size: 14px;
                                    }

                                    #utrButton {
                                        margin-top: 8px;
                                        padding: 8px 12px;
                                        width: 100%;
                                        font-size: 14px;
                                        background-color: #007bff;
                                        color: white;
                                        border: none;
                                        border-radius: 5px;
                                        cursor: pointer;
                                    }

                                    #utrButton:hover {
                                        background-color: #0056b3;
                                    }

                                    #cancelBtn {
                                        margin-top: 15px;
                                        padding: 8px 16px;
                                        background-color: #dc3545;
                                        color: white;
                                        border: none;
                                        border-radius: 5px;
                                        cursor: pointer;
                                        width: 100%;
                                    }

                                    #cancelBtn:hover {
                                        background-color: #c82333;
                                    }

                                    /* Ensure SweetAlert always appears above QR modal */
                                    .swal2-container {
                                        z-index: 10000 !important;
                                    }

                                    .swal2-popup {
                                        z-index: 10001 !important;
                                    }

                                    /* Toasts always on top */
                                    .swal2-container.swal2-top-end {
                                        z-index: 10000 !important;
                                    }

                                    @media(max-width:480px) {
                                        #qrBox {
                                            padding: 20px;
                                        }

                                        #qrBox h3 {
                                            font-size: 18px;
                                        }

                                        #qrBox h4 {
                                            font-size: 14px;
                                        }

                                        #qrBox img {
                                            width: 100%;
                                        }
                                    }
                                </style>
                            </head>

                        <body>

                            <div id="qrModal">
                                <div id="qrBox">
                                    <h3>Scan to Pay</h3>
                                    <h4>Amount: ₹<?php echo $amount; ?></h4>

                                    <!-- Loader -->
                                    <div id="loaderSection">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
                                            <linearGradient id="a11">
                                                <stop offset="0" stop-color="#FF156D" stop-opacity="0"></stop>
                                                <stop offset="1" stop-color="#FF156D"></stop>
                                            </linearGradient>
                                            <circle fill="none" stroke="url(#a11)" stroke-width="15" stroke-linecap="round"
                                                stroke-dasharray="0 44 0 44 0 44 0 44 0 360" cx="100" cy="100" r="70" transform-origin="center">
                                                <animateTransform type="rotate" attributeName="transform" calcMode="discrete" dur="2s"
                                                    values="360;324;288;252;216;180;144;108;72;36" repeatCount="indefinite" />
                                            </circle>
                                        </svg>
                                        <p>Generating QR Code...</p>
                                    </div>

                                    <!-- QR Section -->
                                    <div id="qrSection">
                                        <img id="qrCode" src="<?php echo $qrImageBase64; ?>" alt="QR Code">
                                        <p id="countdown"></p>
                                        <p id="expiryMessage">QR expired. Please verify manually.</p>

                                        <?php if (strtolower($paymentMethod) === 'bharatpe'): ?>
                                            <input type="text" id="utrInput" placeholder="Enter UTR / Transaction ID">
                                            <button id="utrButton" onclick="submitUTR()">Confirm Payment</button>
                                        <?php endif; ?>

                                        <button id="cancelBtn">Cancel</button>
                                    </div>

                                    <!-- Success & Error Animations -->
                                    <div id="successAnimation">
                                        <img src="https://<?php echo paymentapi('gateway_Url'); ?>/api2/img/success-gif.gif" alt="Success">
                                        <p style="color:#28a745;font-weight:bold;">Payment Received. Redirecting...</p>
                                    </div>

                                    <div id="errorGifSection">
                                        <img src="/layouts/members/assets/images/25-error-cross.gif" alt="Error">
                                        <p style="color:red;font-weight:bold;">Payment Cancelled</p>
                                    </div>
                                </div>
                            </div>

                            <script>
                                const qrImageBase64 = '<?php echo $qrImageBase64; ?>';
                                const byteTransactionId = '<?php echo $byteTransactionId; ?>';
                                const byteOrderStatus = '<?php echo $byteOrderStatus; ?>';
                                const redirectUrl = '<?php echo $redirect_url; ?>';
                                const paymentMethod = '<?php echo strtolower($paymentMethod); ?>';
                                const orderId = '<?php echo $order_id; ?>';
                                const amount = '<?php echo $amount; ?>';

                                $(document).ready(() => {
                                    // Show QR after loader delay
                                    setTimeout(() => {
                                        $("#loaderSection").fadeOut(300, () => $("#qrSection").fadeIn(400));
                                        startCountdown(240);
                                    }, 1500);

                                    // Cancel button
                                    $("#cancelBtn").on("click", closeQrPopup);

                                    // Auto check for Paytm and PhonePe. BharatPe uses manual UTR verification.
                                    if (paymentMethod !== "bharatpe") {
                                        setInterval(() => {
                                            $.post('../members/proxy.php', { byte_order_status: byteOrderStatus }, data => {
                                                if (data.trim() === 'success') {
                                                    $("#qrSection").fadeOut(300, () => {
                                                        $("#successAnimation").fadeIn(400);
                                                    });
                                                    setTimeout(() => window.location.href = redirectUrl, 2000);
                                                }
                                            });
                                        }, 1500);
                                    }
                                });

                                // Countdown timer
                                function startCountdown(seconds) {
                                    let remaining = seconds;
                                    const cd = $("#countdown");
                                    const timer = setInterval(() => {
                                        if (remaining < 0) {
                                            clearInterval(timer);
                                            $("#expiryMessage").fadeIn();
                                            return;
                                        }
                                        const mins = Math.floor(remaining / 60);
                                        const secs = remaining % 60;
                                        cd.html(`QR expires in: ${mins}:${secs < 10 ? "0" + secs : secs}`);
                                        remaining--;
                                    }, 1000);
                                }

                              // Manual UTR verification
                                function submitUTR() {
                                    const utr = $("#utrInput").val().trim();

                                    function showToast(icon, title) {
                                        const Toast = Swal.mixin({
                                            toast: true,
                                            position: 'top-end',
                                            showConfirmButton: false,
                                            timer: 10000,
                                            timerProgressBar: true,
                                            background: icon === 'success' ? '#e9fbe9' :
                                                icon === 'error' ? '#fde8e8' :
                                                    icon === 'warning' ? '#fff8e1' : '#fff',
                                            color: '#000',
                                            iconColor: icon === 'success' ? '#28a745' :
                                                icon === 'error' ? '#dc3545' :
                                                    icon === 'warning' ? '#ff9800' : '#000',
                                            customClass: { popup: 'shadow-lg rounded-xl' },
                                            didOpen: toast => {
                                                toast.addEventListener('mouseenter', Swal.stopTimer);
                                                toast.addEventListener('mouseleave', Swal.resumeTimer);
                                            }
                                        });
                                        Toast.fire({ icon, title });
                                    }

                                    if (!utr) {
                                        showToast('warning', 'Please enter your UTR / Transaction ID.');
                                        return;
                                    }

                                    Swal.fire({
                                        title: 'Checking Payment...',
                                        text: 'Please wait while we verify your payment.',
                                        allowOutsideClick: false,
                                        backdrop: 'rgba(0, 0, 0, 0.6)',
                                        didOpen: () => Swal.showLoading()
                                    });

                                    $.post('../members/BharatPeProxy.php', {
                                        redirect_url: redirectUrl,
                                        TransactionId: orderId,
                                        utr: utr
                                    })
                                        .done(data => {
                                            Swal.close();
                                            try {
                                                const res = (typeof data === 'string') ? JSON.parse(data) : data;
                                                if (res.status && res.status.toLowerCase() === "success") {
                                                    $("#qrSection").fadeOut(300, () => {
                                                        $("#successAnimation").fadeIn(400);
                                                    });
                                                    showToast('success', 'Payment received! Redirecting...');
                                                    setTimeout(() => window.location.href = redirectUrl, 2000);
                                                } else {
                                                    showToast('error', res.message || 'Invalid or missing UTR.');
                                                }
                                            } catch {
                                                showToast('error', 'Invalid response from payment server.');
                                            }
                                        })
                                        .fail(() => {
                                            Swal.close();
                                            showToast('error', 'Unable to connect to payment server. Please try again.');
                                        });
                                }

                                // Close / cancel QR popup
                                function closeQrPopup() {
                                    $("#qrSection, #loaderSection").hide();
                                    $("#errorGifSection").fadeIn(400);
                                    setTimeout(() => {
                                        $("#qrModal").fadeOut(400, function () {
                                            $(this).remove();
                                            window.location.href = "login"; // 🔹 Redirect to login page
                                        });
                                    }, 2000);
                                }

                            </script>

                        </body>

                        </html>
                        <style>
                            /* Ensure SweetAlert always appears above QR modal */
                            .swal2-container {
                                z-index: 10000 !important;
                            }

                            .swal2-popup {
                                z-index: 10001 !important;
                            }
                        </style>

                        <?php
                        exit;



                    } else {
                        $errorMsg = $qr_data['message'] ?? 'Unable to generate QR code.';
                        echo "<script>alert('QR Code generation failed. {$errorMsg}');</script>";
                    }
                } else {
                    echo "<script>alert('Failed to initialize activation transaction.');</script>";
                }
            }
        } else {
            echo "<script>alert('Invalid or already activated token.');</script>";
        }
    } else {
        echo "";
    }
} else {
    echo "<script>alert('Payment gateway is inactive.');</script>";
}

// Check payment success after redirection back or page reload
if (
    isset($_SESSION['registerOrder_id'], $_SESSION['registerToken_id']) &&
    !empty($_SESSION['registerOrder_id']) &&
    !empty($_SESSION['registerToken_id'])
) {

    $RegorderID = $_SESSION['registerOrder_id'];
    $tokenIdreg = $_SESSION['registerToken_id'];
    $user_id = aes_decrypt($tokenIdreg, $site_data['user_id']);
    $userData = db_fetch_array("members", "user_id='" . $user_id . "'");

    if ($userData && $userData['status'] == "Unpaid") {
        switch ($userData['usertype']) {
            case "Retailer":
                $amount = $site_data['user_charge'];
                break;
            case "Distributor":
                $amount = $site_data['distributor_charge'];
                break;
            case "Master Distributor":
                $amount = $site_data['master_charge'];
                break;
            default:
                $amount = 1000;
                break;
        }

        $api_url = "https://" . paymentapi("gateway_Url") . "/api/check-order-status";
        $payload = json_encode([
            "user_token" => paymentapi("smartupi_token"),
            "order_id" => $RegorderID,
        ]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
        $response = curl_exec($ch);
        curl_close($ch);

        if ($response === false) {
            die("Unable to verify payment. Please try again.");
        }

        $resArray = json_decode($response, true);

        if ($resArray && isset($resArray['status']) && $resArray['status'] === "COMPLETED") {
            $result = $resArray['result'];
            $txnStatus = $result['txnStatus'] ?? '';
            $txn_amount = $result['amount'] ?? 0;
            $final_status = $result['status'] ?? '';
            $order_id = $result['orderId'] ?? '';
            $utr_number = $result['utr'] ?? '';
            $resultInfo = $result['resultInfo'] ?? '';

            if ($final_status === "SUCCESS" && $txn_amount == $amount) {
                // Check if this order_id already has status SUCCESS in reports
                $paidRecordCount = db_count("reports", "order_id='" . $order_id . "' AND status='SUCCESS'");

                if ($paidRecordCount == 0) {
                    // Update the existing 'Pending' report to SUCCESS and fill details
                    $updateData = [
                        'site_id' => $userData['site_id'],
                        'user_id' => $userData['user_id'],
                        'username' => $userData['username'],
                        'name' => $userData['name'],
                        'parent_id' => $userData['parent_id'],
                        'service' => "REGISTRATION",
                        'type' => "Credit",
                        'account_number' => $userData['mobile'],
                        'operator' => "SmartUPI",
                        'amount' => $txn_amount,
                        'main_amount' => $txn_amount,
                        'old_balance' => $userData['balance'],
                        'new_balance' => 0, // You might want to calculate new balance if wallet is involved
                        'txn_id' => $order_id,
                        'description' => "Request of Rs. {$txn_amount} has been successfully Received For Registration.",
                        'date_time' => current_timestamp(),
                        'status' => "SUCCESS"
                    ];

                    if (db_update("reports", $updateData, "order_id='" . $order_id . "'")) {
                        // Activate user
                        db_update("members", ['status' => 'Active'], "user_id='" . $userData['user_id'] . "'");

                        //


                        $message = "Dear {$userData['name']}, Your account has been activated. Username: {$userData['username']}, Password: {$userData['password']}. Login at https://" . baseurl();
                        send_sms($userData['mobile'], $message);
                        send_email($userData['email'], "Account Activated", $message);
                        unset($_SESSION['registerOrder_id']);
                        unset($_SESSION['registerToken_id']);

                        awal_alert_msg("Payment Successful & Account Activated. Please login to continue.", 'success', '/members/login');
                        exit;
                    } else {
                        die("Failed to update payment report. Contact support.");
                    }
                } else {
                    awal_alert_msg("Payment already processed. Please login.", 'info', '/members/login');
                    exit;
                }
            } else {
                awal_alert_msg("Payment not successful or amount mismatch.", 'error', '/members/selfactivation');
                exit;
            }
        } else {
            awal_alert_msg("Unable to verify payment status. Try again.", 'error', '/members/selfactivation');
            exit;
        }
    } else {
        awal_alert_msg("Account already activated or invalid token.", 'info', '/members/login');
        exit;
    }

    ?>

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Self Registrion</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background-color: #f8f9fa;
                margin: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                color: #333;
            }

            .container {
                text-align: center;
                background: #fff;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }

            h1 {
                color: #d9534f;
            }

            p {
                margin: 15px 0;
            }

            button {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 16px;
            }

            button:hover {
                background-color: #0056b3;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <h1>Some Technical Issue...</h1>
            <p>We are currently experiencing issues with the payment gateway. Please contact the Help Desk for assistance.
            </p>
            <button onclick="goBack()">Go Back</button>
        </div>

        <script>
            function goBack() {
                window.history.back();
            }
        </script>
    </body>

    </html>
<?php }
?>