<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Responses BY HBConnect </title>  <!--https://new.hbconnect.live-->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.14/dist/sweetalert2.all.min.js"></script>
</head>
<body>

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

if (isset($_SESSION['order_id'])) {
    $order_id = $_SESSION['order_id'];
    $customer_mobile = $_SESSION['customer_mobile'];

    $ta_check = mysqli_query($ahk_conn, "SELECT * FROM wallet WHERE txn_id='$order_id'");
    if (!$ta_check) {
    echo "Error: " . mysqli_error($ahk_conn);
    exit;
    }
    $hkb_status = mysqli_fetch_array($ta_check);
    if (mysqli_num_rows($ta_check) == 1 && $hkb_status['status'] =="pending") {
         $txn_check = mysqli_fetch_array($ta_check);
         $txn_status = $txn_check['status'];
    // if (!isset($_SESSION['wallet_updated'][$order_id])) {
        $url = "https://pginstant.gdrd.site/api/check-order-status";
        
        $minimum_amount="0";                                         // minimum amount add restriction from users...

        $postData = array(
            "user_token" => "035e3549df7ab69e29d5ffabe605988a",                       // api_key https://new.hbconnect.live
            "order_id" => $order_id
        );

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo "<script>alert('cURL Error: " . curl_error($ch) . "');</script>";
            exit;
        }

        curl_close($ch);

        $responseData = json_decode($response, true);

        if ($responseData["status"] === "COMPLETED") {
            $txnStatus = $responseData["result"]["txnStatus"];
            $status = $responseData["result"]["status"];
            $amount = $responseData["result"]["amount"];
            $utrt = $responseData["result"]["utr"];
            $resultInfo = $responseData["result"]["resultInfo"];
            
            echo "PAYMENT SUCCESSFULLY";
            if ($status === "SUCCESS") {
            if ($amount > $minimum_amount) {    // hkb amount change your oown according
                
                $sql = "UPDATE users SET balance = balance + $amount WHERE phone = '$customer_mobile'";
                $sql2 = "UPDATE wallet SET status = 'success' ,amount='$amount',BANKTXNID='$utrt',RESPMSG='$resultInfo',PAYMENTMODE='UPI QR' WHERE txn_id = '$order_id'";
                $ahk_conn->query($sql2);
                if ($ahk_conn->query($sql) === TRUE && $ahk_conn->query($sql2) === TRUE) {
                    echo "<script>
                    Swal.fire({
                        title: 'SUCCESS',
                        text: 'WALLET UPDATED SUCCESSFULLY',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        window.location.href = 'https://".$_SERVER['SERVER_NAME']."/admin/wallet.php';
                    });
                </script>";

                    $_SESSION['wallet_updated'][$order_id] = true;
                } else {
                    echo "<script>
                    Swal.fire({
                        title: 'WALLET UPDATE FAILED',
                        text: 'Update failed: " . $ahk_conn->error . "',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        window.location.href = 'https://".$_SERVER['SERVER_NAME']."/admin/wallet.php';
                    });
                </script>";
                }
                
            } else {
                $sql3 = "UPDATE wallet SET status = 'success' ,amount='$amount',BANKTXNID='$utrt',RESPMSG='$resultInfo',PAYMENTMODE='UPI <br> Trying To Cheat Amount Not refunded or Added !' WHERE txn_id = '$order_id'";
                $ahk_conn->query($sql3);
            echo "<script>
                    Swal.fire({
                        title: 'You Are Trying To Cheat ! Amount Load Minimun ".($minimum_amount+0)."',
                        text: 'This Amount Not refunded or Added ! Sorry',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        window.location.href = 'https://".$_SERVER['SERVER_NAME']."/admin/wallet.php';
                    });
                </script>";
        }
            }
        
        } else {
            echo "<script>
                    Swal.fire({
                        title: 'PAYMMENT GATEWAY API PROBLEM CONTACT ADMIN',
                        text: 'API call unsuccessful. Status: " . ($responseData["status"] ?? "Unknown") . "',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        window.location.href = 'https://".$_SERVER['SERVER_NAME']."/admin/wallet.php';
                    });
                </script>";
        }
    } else {
        echo "<script>
                    Swal.fire({
                        title: 'Dont try to Repeat Payment Already Added.',
                        text: 'Wallet Already Updated SuccessFully !',
                        icon: 'warning',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        window.location.href = 'https://".$_SERVER['SERVER_NAME']."/admin/wallet.php';
                    });
                </script>";
    }

} else {
    echo "<script>Swal.fire('Error', 'Order ID not set in session', 'error');</script>";
}
?>

</body>
</html>
