<?php
session_start();
include('../includes/config.php');

$user_token = $flexsecure_upikey; // Defined in config.php
$qrImageBase64 = '';
$amount = '';
$order_id = '';
$byteTransactionId = '';
$qr_status = false;
$phone = '';
$email = '';
$gatewayUsed = '1'; // Default gateway

// ✅ Helper function to call QR API
function call_qr_api($url, $post_fields) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "<script>alert('cURL error: " . curl_error($ch) . "');</script>";
    }
    curl_close($ch);
    return json_decode($response, true);
}

// ✅ Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = mysqli_real_escape_string($ahk_conn, $_POST['phone'] ?? '');
    $email = mysqli_real_escape_string($ahk_conn, $_POST['email'] ?? '');
    $amount = mysqli_real_escape_string($ahk_conn, $_POST['amount'] ?? '');

    $order_id = 'FLX' . rand(1000000000, 9999999999);
    $byteTransactionId = "BYTE" . rand(10000000000000, 99999999999999);

    $_SESSION['order_id'] = $order_id;
    $_SESSION['customer_mobile'] = $phone;

    if (strlen($user_token) !== 32) {
        echo "<script>alert('Invalid API key.');</script>";
    } elseif (empty($phone) || empty($amount)) {
        echo "<script>alert('Phone and amount are required.');</script>";
    } else {
        $redirect_url = "https://" . $_SERVER['SERVER_NAME'] . "/Flex4uPoint4in1/regresponse.php?order_id={$order_id}&customer_mobile={$phone}";

        $post_fields = [
            'user_token'        => $user_token,
            'amount'            => $amount,
            'order_id'          => $order_id,
            'byteTransactionId' => $order_id,
            'customer_mobile'   => $phone,
            'email'             => $email,
            'redirect_url'      => $redirect_url
        ];

        // ✅ Try Gateway 1
        $resData = call_qr_api("https://themonkeypay.in/api2/create-orderpopup.php", $post_fields);

        // ✅ Try Gateway 2 on failure
        if (empty($resData) || (isset($resData['status']) && $resData['status'] !== true)) {
            $resData = call_qr_api("https://themonkeypay.in/api2/create-orderpopup2.php", $post_fields);
            $gatewayUsed = '2';
        }

        // ✅ Try Gateway 3 on failure again
        if (empty($resData) || (isset($resData['status']) && $resData['status'] !== true)) {
            $resData = call_qr_api("https://themonkeypay.in/api2/create-orderpopup3.php", $post_fields);
            $gatewayUsed = '3';
        }

        // ✅ Success — QR generated
        if (!empty($resData['status']) && $resData['status'] === true && !empty($resData['result']['payment_url'])) {
            $qr_status = true;
            $qrImageBase64 = $resData['result']['payment_url'];

            $ins = mysqli_query($ahk_conn, "INSERT INTO `wallet`(`phone`,`amount`,`txn_id`,`email`,`status`) 
                VALUES ('$phone','$amount','$order_id','$email','pending')");

            if (!$ins) {
                echo "<script>alert('Failed to insert wallet data.');</script>";
            }
        } else {
            $errorMsg = $resData['message'] ?? 'Unknown error occurred while generating QR.';
            echo "<script>alert('QR API failed: {$errorMsg}');</script>";
        }
    }
}
?>

<?php if ($qr_status): ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let qrInterval;

function showQrWithLoader(qrImage, amount, order_id, gatewayUsed, redirect_url) {
    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:10000; display:flex; justify-content:center; align-items:center;">
    <div style="background:white; padding:30px; border-radius:12px; width:320px; text-align:center;">
        <h4>Scan to Pay</h4>
        <h3 style="color:green;font-weight:bold;">Amount: ₹${amount}</h3>

        <!-- Loader Section -->
        <div id="loaderSection">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="60" height="60" style="margin:auto;">
                <linearGradient id="a9">
                    <stop offset="0" stop-color="#FF156D" stop-opacity="0"></stop>
                    <stop offset="1" stop-color="#FF156D"></stop>
                </linearGradient>
                <circle fill="none" stroke="url(#a9)" 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 style="color:red;">Generating QR Code...</p>
        </div>

        <div id="qrSection" style="display:none;">
            <img src="${qrImage}" alt="QR Code" style="width:250px;margin-bottom:10px;">
            <p id="countdown" style="color:red;"></p>
            <p id="expiryMessage" style="display:none;color:red;font-weight:bold;">QR expired.</p>

            <!-- Gateway 3 Manual Verify -->
            <div id="gateway3Manual" style="display:${gatewayUsed === '3' ? 'block' : 'none'};margin-top:10px;">
                <input type="text" id="utrInput" placeholder="Enter UTR / Transaction ID"
                    style="width:100%;padding:8px;border:1px solid #ccc;border-radius:6px;">
                <button id="confirmUtrBtn" style="margin-top:8px;padding:8px 12px;font-size:14px;
                    background:#007bff;color:white;border:none;border-radius:5px;cursor:pointer;">Confirm Payment</button>
            </div>

            <button id="cancelBtn" style="margin-top:10px;background:red;color:white;
                border:none;padding:7px 16px;border-radius:5px;">Cancel</button>
        </div>

        <div id="successAnimation" style="display:none;margin-top:20px;">
            <img src="https://themonkeypay.in/api2/img/success-gif.gif" alt="Success" style="width:150px;">
            <p style="color:#28a745;font-weight:bold;">Payment Received. Redirecting...</p>
        </div>
    </div>
</div>`;

    document.body.insertAdjacentHTML("beforeend", modalHtml);

    // ✅ Simulate QR loading
    setTimeout(() => {
        $("#loaderSection").hide();
        $("#qrSection").show();

        let remaining = 240;
        const countdownEl = $("#countdown");

        const timer = setInterval(() => {
            const minutes = Math.floor(remaining / 60);
            const seconds = remaining % 60;
            countdownEl.text(`This QR code will expire in ${minutes}:${seconds < 10 ? "0" : ""}${seconds}`);
            if (--remaining < 0) {
                clearInterval(timer);
                $("#expiryMessage").show();
            }
        }, 1000);
    }, 1500);

    // ✅ Auto-check status for gateways 1 & 2
    if (gatewayUsed !== "3") {
        qrInterval = setInterval(() => {
            $.post('../Flex4uPoint4in1/proxy.php', { byte_order_status: order_id }, data => {
                if (data === 'success') {
                    clearInterval(qrInterval);
                    $("#qrSection").hide();
                    $("#successAnimation").show();
                    setTimeout(() => window.location.href = redirect_url, 2000);
                }
            });
        }, 2000);
    }

    // ✅ Manual Verify (Gateway 3)
    $("#confirmUtrBtn").on("click", () => submitUTR(order_id, redirect_url));
}

// ================= MANUAL VERIFY (Gateway 3) =================
function submitUTR(order_id, redirect_url) {
    const utr = $("#utrInput").val().trim();
    if (!utr) {
        Swal.fire("Enter UTR", "Please enter your UTR / Transaction ID.", "warning");
        return;
    }

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

    $.get('../Flex4uPoint4in1/BharatPeProxy.php', {
        redirect_url: redirect_url,
        TransactionId: order_id,
        utr: utr
    })
    .done(function (data) {
        Swal.close();

        let res;
        try {
            res = (typeof data === "string") ? JSON.parse(data) : data;
            console.log("Manual Verify Response:", res);

            if (res.status && res.status.toLowerCase() === "success") {
                $("#qrSection").hide();
                $("#successAnimation").show();
                setTimeout(() => window.location.href = redirect_url, 2000);
            } else {
                Swal.fire("Verification Failed", res.message || "Invalid or missing UTR.", "error");
            }
        } catch (e) {
            console.error("Parse error:", e, data);
            Swal.fire("Error", "Invalid response from payment server.", "error");
        }
    })
    .fail(function (xhr, status, error) {
        Swal.close();
        console.error("Verify error:", status, error, xhr.responseText);
        Swal.fire("Connection Error", "Unable to connect to payment server. Please try again.", "error");
    });
}

// ✅ Cancel Payment
$(document).on("click", "#cancelBtn", function () {
    clearInterval(qrInterval);
    $("#qrModal").remove();
    window.location.href = "../auth";
});

// ✅ On Load
document.addEventListener("DOMContentLoaded", function () {
    showQrWithLoader(
        "<?php echo $qrImageBase64; ?>",
        "<?php echo $amount; ?>",
        "<?php echo $order_id; ?>",
        "<?php echo $gatewayUsed; ?>",
        "<?php echo $redirect_url; ?>"
    );
});
</script>
<?php endif; ?>
<style>
.swal2-container { z-index: 10000 !important; }
.swal2-popup { z-index: 10001 !important; }
.swal2-container.swal2-top-end { z-index: 10000 !important; }
</style>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Activation | <?php echo ahkweb('webname'); ?></title>
    <link rel="shortcut icon" type="image/x-icon" href="<?php echo ahkweb('logo'); ?>" />
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
</body>
</html>

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