<?php
require_once("../layouts/members/head.php");

if (isset($user_data['recharge_active']) && $user_data['recharge_active'] == "YES") {
if(isset($site_data['gateway']) && $site_data['gateway'] == 'active'){ 
?>
<?php
if (isset($_POST['smartupi']) && !empty($_POST['amount']) && $site_data['gateway'] == "active") {
    $amount = safe_str($_POST['amount']);
    $miniMumAmount = isset($user_data['min_balance']) ? $user_data['min_balance'] : 100;
    if(!empty($amount)){
    if (is_numeric($amount) && $amount >= $miniMumAmount && $amount <= 1000) {
        $order_id = order_txn_id();

        $insData = array(
            'site_id'       => $site_data['site_id'] ?? '',
            'user_id'       => $user_data['user_id'] ?? '',
            'username'      => $user_data['username'] ?? '',
            'parent_id'     => $user_data['parent_id'] ?? '',
            'order_id'      => $order_id,
            'service'       => "WALLET",
            'type'          => "Credit",
            'account_number'=> $user_data['mobile'] ?? '',
            'operator'      => "SmartUPI",
            'amount'        => $amount,
            'main_amount'   => $amount,
            'ref_id'        => 'SmartUPI',
            'old_balance'   => $user_data['balance'] ?? '',
            'new_balance'   => 0,
            'txn_id'        => $order_id,
            'description'   => "Request of Rs. {$amount} has been initiated into your wallet via HKB Gateway.",
            'date_time'     => current_timestamp(),
            'status'        => "Process"
        );

        if (db_insert("reports", $insData)) {
            $post_data = array(
                'customer_mobile'=> $user_data['mobile'],
                'user_token'     => paymentapi("smartupi_token"),
                'amount'         => $amount,
                'order_id'       => $order_id,
                'redirect_url'   => "https://" . $_SERVER['SERVER_NAME'] . "/members/addmoneyresponse.php",
                'remark1'        => $user_data['username'],
                'remark2'        => $user_data['username'],
            );

            $api_url = "https://" . paymentapi("gateway_Url") . "/api2/create-orderpopup";

            $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, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
            $response = curl_exec($ch);
            curl_close($ch);

            if ($response) {
                $resArray = json_decode($response, true);
                $_SESSION['order_id'] = $order_id;
                $_SESSION['customer_mobile'] = $user_data['mobile'];

                if ($resArray['status'] && isset($resArray['result']['payment_url'])) {
                    $payment_url = $resArray['result']['payment_url'];

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $payment_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $qr_response = curl_exec($ch);
                    curl_close($ch);

                    if ($qr_response) {
                        $qrData = json_decode($qr_response, true);
                        $redirectPaymentUrl = $qrData['payment_url'] ?? '';
                        $orderUnicID        = $qrData['orderUnicID'] ?? '';
                        $qrImage            = $qrData['qrimage'] ?? '';

                        if ($qrImage) {

                            if (strpos($payment_url, 'payment3') !== false) {
                                echo '<script>
                                document.addEventListener("DOMContentLoaded", function() {
                                    showQrPopup("' . $qrImage . '", "' . $redirectPaymentUrl . '", "' . $orderUnicID . '", "' . $amount . '", "payment3");
                                });
                                </script>';
                            } elseif (strpos($payment_url, 'payment4') !== false) {
                                echo '<script>
                                document.addEventListener("DOMContentLoaded", function() {
                                    showQrPopup("' . $qrImage . '", "' . $redirectPaymentUrl . '", "' . $orderUnicID . '", "' . $amount . '", "payment4");
                                });
                                </script>';
                            }

                            echo '<script>
                            function showQrPopup(qrImage, paymentUrl, orderUnicID, amount, type) {
                                const modalHtml = `
                                    <div id="qrModal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); z-index: 1000; display: flex; justify-content: center; align-items: center;">
                                        <div style="background: white; padding: 20px; border-radius: 10px; text-align: center;">
                                            <h4>Scan QR Code</h4>
                                            <h6 style="color: green; font-weight: bold;">Amount: ₹${amount}</h6>
                                            <img id="qrImageElement" src="${qrImage}" alt="QR Code" style="width: 250px; height: auto; margin: 2px 0;">
                                            <p id="countdown"></p>
                                            <div id="utrSection"></div>
                                            <p id="expiryMessage" style="display: none; color: red; font-weight: bold;">QR Code expired. Closing in 10 seconds...</p>
                                            <button onclick="closeQrPopup()" style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">Close</button>
                                        </div>
                                    </div>
                                `;
                                document.body.insertAdjacentHTML("beforeend", modalHtml);

                                if (type === "payment3") {
                                    startCountdown(240);
                                    const intervalId = setInterval(() => {
                                        checkPaymentStatus(orderUnicID, paymentUrl, intervalId);
                                    }, 3000);
                                    setTimeout(() => {
                                        clearInterval(intervalId);
                                        expireQr();
                                    }, 240000);
                                } else if (type === "payment4") {
                                    document.getElementById("utrSection").innerHTML = `
                                        <hr>
                                        <div style="margin-top:10px;">
                                            <label><b>Enter UTR / Reference Number</b></label><br>
                                            <input type="text" id="utrNumber" placeholder="Enter UTR Number" class="form-control" style="margin-top:5px;">
                                            <button id="utrSubmit" class="btn btn-success mt-2" style="margin-top:10px;">Check Payment Status</button>
                                            <p id="utrStatusResult" style="margin-top:5px;"></p>
                                        </div>
                                    `;

                                    document.getElementById("utrSubmit").addEventListener("click", function(){
                                        const utr = document.getElementById("utrNumber").value.trim();
                                        if(!utr){
                                            alert("Please enter UTR number!");
                                            return;
                                        }
                                        const res = document.getElementById("utrStatusResult");
                                        res.innerHTML = "Checking payment status...";
                                        const formData = new URLSearchParams();
                                        formData.append("utr_number", utr);
                                        formData.append("byte_order_status", orderUnicID);

                                        fetch("https://' . paymentapi("gateway_Url") . '/api2/payment-statuspopup", {
                                            method: "POST",
                                            headers: { "Content-Type": "application/x-www-form-urlencoded" },
                                            body: formData
                                        })
                                        .then(r => r.text())
                                        .then(respText => {
                                            let json = {};
                                            try { json = JSON.parse(respText); } catch(e) {}

                                            if (json.status && json.status.toLowerCase() === "success") {
                                                res.innerHTML = "<span style=\'color:green;font-weight:bold;\'>Payment Successful!</span>";
                                                const redir = json.redirect_url ? json.redirect_url : paymentUrl;
                                                setTimeout(() => window.location.href = redir, 1000);
                                            } else if (json.error) {
                                                res.innerHTML = `<span style=\'color:red;font-weight:bold;\'>${json.error}</span>`;
                                            } else {
                                                res.innerHTML = "<span style=\'color:orange;font-weight:bold;\'>Pending or Invalid UTR.</span>";
                                            }
                                        })
                                        .catch(err => {
                                            res.innerHTML = "<span style=\'color:red;\'>Error checking payment.</span>";
                                            console.error(err);
                                        });
                                    });
                                }
                            }

                            function checkPaymentStatus(orderUnicID, paymentUrl, intervalId) {
                                const formData = new URLSearchParams();
                                formData.append("byte_order_status", orderUnicID);

                                fetch("https://' . paymentapi("gateway_Url") . '/api2/payment-statuspopup", {
                                    method: "POST",
                                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                                    body: formData
                                })
                                .then(r => r.text())
                                .then(statusResponse => {
                                    if (statusResponse.trim() === "success") {
                                        clearInterval(intervalId);
                                        closeQrPopup();
                                        window.location.href = paymentUrl;
                                    } else if (statusResponse.trim() === "failed") {
                                        clearInterval(intervalId);
                                        alert("Payment Failed. Please try again.");
                                        closeQrPopup();
                                    }
                                })
                                .catch(err => console.error("Error checking payment status:", err));
                            }

                            function startCountdown(duration) {
                                const countdownElement = document.getElementById("countdown");
                                let remaining = duration;
                                const timer = setInterval(() => {
                                    const minutes = Math.floor(remaining / 60);
                                    const seconds = remaining % 60;
                                    countdownElement.innerText = `Time remaining: ${minutes}:${seconds < 10 ? "0" + seconds : seconds}`;
                                    remaining -= 1;
                                    if (remaining < 0) clearInterval(timer);
                                }, 1000);
                            }

                            function expireQr() {
                                const qrImageElement = document.getElementById("qrImageElement");
                                if (qrImageElement) qrImageElement.style.display = "none";
                                const expiryMessage = document.getElementById("expiryMessage");
                                expiryMessage.style.display = "block";
                                let closeCounter = 10;
                                const closeTimer = setInterval(() => {
                                    expiryMessage.innerText = `QR Code expired. Closing in ${closeCounter--} seconds...`;
                                    if (closeCounter <= 0) {
                                        clearInterval(closeTimer);
                                        closeQrPopup();
                                    }
                                }, 1000);
                            }

                            function closeQrPopup() {
                                const modal = document.getElementById("qrModal");
                                if (modal) modal.remove();
                            }
                            </script>';
                        } else {
                            echo '<script>alert("Failed to fetch QR code from the payment URL.");</script>';
                        }
                    } else {
                        echo '<script>alert("Failed to connect to the payment URL.");</script>';
                    }
                } else {
                    echo '<script>alert("' . $resArray['message'] . '");</script>';
                }
            } else {
                echo '<script>alert("Failed to connect to the payment gateway.");</script>';
            }
        } else {
            echo '<script>alert("Failed to insert data into the database.");</script>';
        }
    } else {
        echo '<script>alert("Add Money: Minimum ₹'.$miniMumAmount.' Maximum ₹1000!");</script>';
    }
  } else {
      echo '<script>alert("Please Fill Amount");</script>';
  }
}
?>

<div class="row">
    <?php if ($site_data['gateway'] == "active") { ?>
        <div class="col-md-4 mb-2">
            <div class="card text-dark">
                <div class="card-header bg-primary text-white py-2">
                    <div class="d-flex align-items-center">
                        <span class="mr-auto">UPI GATEWAY - Instant Wallet TopUp</span>
                    </div>
                </div> 
                <form class="row p-4" method="POST" action="">
                    <div class="col-md-12 mb-3">
                        <label>Amount</label>
                        <input type="number" class="form-control border-primary" placeholder="Enter Amount" name="amount" required>
                    </div>
                    <div class="col-md-12 mb-3">
                      <button type="submit" class="btn btn-primary btn-block" name="smartupi">Add Money</button>
                      <a href="walletledger" class="btn btn-warning btn-block">Pending Payment Check Status</a>
                    </div>
                </form>
            </div>
        </div>
    <?php } ?>
</div>
<?php 
}else{
require_once("404.php");
} 
} else {
  awal_alert_msg('You Do Not Have Permission Self Recharge!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>

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