<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/balance.php');

// ✅ TheMonkeyPay Configuration
$themonkey_token = "e8d2a2f1ac98d41d3b7422fd11ab98fa";
$themonkey_api_url = "themonkeypay.in";

// ✅ Helper function for API calls
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);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        curl_close($ch);
        return null;
    }
    curl_close($ch);
    return json_decode($response, true);
}

// ✅ Process Payment
if(isset($_POST['amount']) && $_POST['amount'] != NULL){
    
    // ================= QR CODE PAYMENT (TheMonkeyPay) =================
    if($_POST['mode'] == "qr"){
        date_default_timezone_set("Asia/Kolkata");
        $date = date("d-m-Y");
        $ORDER_ID = 'BAL' . $udata['phone'] . rand(1000,99999);
        $amount = mysqli_real_escape_string($ahk_conn,$_POST['amount']);
        $email = $udata['email'];
        
        $ins = mysqli_query($ahk_conn,"INSERT INTO `wallet`(`phone`,`amount`,`txn_id`,`email`,`status`,`date`,`PAYMENTMODE`) 
            VALUES ('".$udata['phone']."','$amount','$ORDER_ID','$email','pending','$date','QR')");

        if($ins){
            $_SESSION['wuphone'] = $udata['phone'];
            $_SESSION['order_id'] = $ORDER_ID;
            $_SESSION['gateway_used'] = 'themonkeypay';
            
            $redirect_url = "https://" . $_SERVER['SERVER_NAME'] . "/Flex4uPoint4in1/balanceresponse.php?order_id={$ORDER_ID}&customer_mobile={$udata['phone']}";
            
            $post_fields = [
                'user_token'        => $GLOBALS['themonkey_token'],
                'amount'            => $amount,
                'order_id'          => $ORDER_ID,
                'customer_mobile'   => $udata['phone'],
                'redirect_url'      => $redirect_url,
                'remark1'           => 'Balance Recharge',
                'remark2'           => $email,
                'merchant_name'     => 'paytm'
            ];
            
            // ✅ Call TheMonkeyPay API
            $resData = call_qr_api("https://{$GLOBALS['themonkey_api_url']}/api/create-order", $post_fields);
            
            if (!empty($resData) && isset($resData['status']) && $resData['status'] === true) {
                $qrImageBase64 = $resData['result']['payment_url'];
                ?>
                <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 showQrModal() {
                    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:9999;display:flex;justify-content:center;align-items:center;">
                        <div style="background:white;padding:30px;border-radius:12px;width:360px;text-align:center;">
                            <h4>Scan to Pay</h4>
                            <h3 style="color:green;font-weight:bold;">Amount: ₹<?php echo $amount; ?></h3>
                            
                            <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="<?php echo $qrImageBase64; ?>" 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>
                                
                                <button id="cancelBtn" style="margin-top:10px;background:red;color:white;
                                    border:none;padding:7px 16px;border-radius:5px;cursor:pointer;">Cancel</button>
                            </div>
                            
                            <div id="successAnimation" style="display:none;margin-top:20px;">
                                <img src="https://i.imgur.com/xwDvaNq.gif" alt="Success" style="width:150px;">
                                <p style="color:#28a745;font-weight:bold;">Payment Received. Redirecting...</p>
                            </div>
                        </div>
                    </div>`;
                    
                    $("body").append(modalHtml);
                    
                    setTimeout(() => {
                        $("#loaderSection").hide();
                        $("#qrSection").show();
                        
                        let remaining = 1800; // 30 minutes
                        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 payment status
                    qrInterval = setInterval(() => {
                        $.post('../Flex4uPoint4in1/checkstatus.php', { order_id: '<?php echo $ORDER_ID; ?>' }, data => {
                            try {
                                const response = typeof data === 'string' ? JSON.parse(data) : data;
                                if (response.status === 'success') {
                                    clearInterval(qrInterval);
                                    $("#qrSection").hide();
                                    $("#successAnimation").show();
                                    setTimeout(() => window.location.href = '<?php echo $redirect_url; ?>', 2000);
                                }
                            } catch(e) {
                                console.log('Status check error:', e);
                            }
                        });
                    }, 3000);
                    
                    $("#cancelBtn").on("click", function () {
                        clearInterval(qrInterval);
                        $("#qrModal").remove();
                        window.location.href = "balance";
                    });
                }
                
                $(document).ready(() => {
                    showQrModal();
                });
                </script>
                <?php
            } else {
                $errorMsg = $resData['message'] ?? 'Payment gateway unavailable';
                ?>
                <script>
                    alert('QR API failed: <?php echo addslashes($errorMsg); ?>');
                    window.location.href = 'balance';
                </script>
                <?php
            }
        }
    }
    
    // ================= OTHER PAYMENT MODES (Keep existing code) =================
    else if($_POST['mode'] == "paytm"){
        $ORDER_ID = $udata['phone'] . rand(1000,99999);
        $amount = mysqli_real_escape_string($ahk_conn,$_POST['amount']);
        $email = mysqli_real_escape_string($ahk_conn,$_POST['email']);
        $ins = mysqli_query($ahk_conn,"INSERT INTO `wallet`(`phone`,`amount`,`txn_id`,`email`,`status`) 
            VALUES ('".$udata['phone']."','$amount','$ORDER_ID','$email','pending')");
    }
    else if($_POST['mode'] == "payu"){
        // Payu Code
        $ORDER_ID = $udata['phone'] . rand(1000,99999);
        $amount = mysqli_real_escape_string($ahk_conn,$_POST['amount']);
        $email = mysqli_real_escape_string($ahk_conn,$_POST['email']);
        $ins = mysqli_query($ahk_conn,"INSERT INTO `wallet`(`phone`,`amount`,`txn_id`,`email`,`status`) 
            VALUES ('".$udata['phone']."','$amount','$ORDER_ID','$email','pending')");
    }
    else if($_POST['mode'] == "sam"){
        // Sam Code
        $ORDER_ID = $udata['phone'] . rand(1000,99999);
        $amount = mysqli_real_escape_string($ahk_conn,$_POST['amount']);
        $email = mysqli_real_escape_string($ahk_conn,$_POST['email']);
        $ins = mysqli_query($ahk_conn,"INSERT INTO `wallet`(`phone`,`amount`,`txn_id`,`email`,`status`) 
            VALUES ('".$udata['phone']."','$amount','$ORDER_ID','$email','pending')");
        
        if($ins){
            ?>
            <form class="mt-2" method="post" name="f2" action="../payment/index.php">
                <input type="hidden" name="emailid" value="<?php echo $udata['email'];?>">
                <input type="hidden" name="phone" value="<?php echo $udata['phone'];?>">
                <input type="hidden" name="name" value="<?php echo $udata['name'];?>">
                <input type="hidden" name="order_id" value="<?php echo $ORDER_ID; ?>">
                <input type="hidden" name="amount" value="<?php echo $amount; ?>">
            </form>
            <script type="text/javascript">
                document.f2.submit();
            </script>
            <?php 
        }
    }
    else if($_POST['mode'] == "upi"){
        // UPI Code
        date_default_timezone_set("Asia/Kolkata");
        $date = date("d-m-Y");
        $ORDER_ID = $udata['phone'] . rand(1000,99999);
        $amount = mysqli_real_escape_string($ahk_conn,$_POST['amount']);
        $email = mysqli_real_escape_string($ahk_conn,$_POST['email']);
        $ins = mysqli_query($ahk_conn,"INSERT INTO `wallet`(`phone`,`amount`,`txn_id`,`email`,`status`,`date`) 
            VALUES ('".$udata['phone']."','$amount','$ORDER_ID','$email','pending','$date')");
    }
}

// ================= SUCCESS/FAILURE MESSAGES =================
if(isset($_POST['successmsg']) && $_POST['successmsg'] == "true"){
    ?>
    <script>
        $(function(){
            Swal.fire('Payment Added Successfully', 'Your Payment Added!', 'success')
        })
    </script>
    <?php
}

if(isset($_POST['failedmsg']) && $_POST['failedmsg'] == "true"){
    ?>
    <script>
        $(function(){
            Swal.fire('Payment Added Failed', 'if Payment Deduct Then Contact us!', 'error')
        })
    </script>
    <?php
}

if(isset($_POST['success']) && $_POST['success'] == "true"){
    ?>
    <script>
        $(function(){
            Swal.fire('Payment Added Successfully', 'Your Payment Added!', 'success')
        })
    </script>
    <?php
}

if(isset($_POST['failed']) && $_POST['failed'] == "true"){
    ?>
    <script>
        $(function(){
            Swal.fire('Payment Added Failed', 'if Payment Deduct Then Contact us!', 'error')
        })
    </script>
    <?php
}

if(isset($_POST['success1']) && $_POST['success1'] == "true"){
    ?>
    <script>
        $(function(){
            Swal.fire('Payment Already updated', 'if Payment Not Update Then Contact us!', 'success')
        })
    </script>
    <?php
}
?>