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

if (isset($_SESSION["is_login"]) && $_SESSION["is_login"] === true && !empty($_SESSION["login_token"])) {
$user_data = user_data($_SESSION["login_token"]);
$site_data = site_data();
if (isset($user_data['recharge_active']) && $user_data['recharge_active'] == "YES") {
if(isset($site_data['gateway']) && $site_data['gateway'] == 'active'){ 
?>
<?php
$main_site_data = main_site_data();

if(isset($_POST['order_id']) && !empty($_POST['order_id'])) {
$order_id = $_POST['order_id'];

$url = "https://".paymentapi("gateway_Url")."/api/check-order-status";
$data = array(
    "user_token" => paymentapi("smartupi_token"),
    "order_id" => $order_id,
);

$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// Execute request
 $response = curl_exec($ch);

if ($response === false) {
    // Handle network or HTTP request errors
    die("Failed to fetch order information from the API.");
}

$resArray = json_decode($response, true);

if ($resArray === null || !isset($resArray['status'])) {
    die("Invalid response from the API.");
}

$status = $resArray['status'];

if ($status === "COMPLETED") {
    $txnStatus = $resArray["result"]["txnStatus"];
    $order_id = $resArray["result"]["orderId"];
    $fainal_status = $resArray["result"]["status"];
    $txn_amount = $resArray["result"]["amount"] ?? ''; 
    $utr_number = $resArray["result"]["utr"] ?? '';
    $resultInfo = $resArray["result"]["resultInfo"] ?? '';
    
   $txn_count = db_count("reports", "order_id='" . $order_id . "' AND status IN ('Process','Pending')");
   if ($txn_count == 1) {
    $txn_data = db_fetch_array("reports", "order_id='" . $order_id . "' AND status IN ('Process','Pending')");
    if ($txn_data) {
        $user_data = db_fetch_array("members", "user_id='" . $txn_data['user_id'] . "'");
        if ($user_data) { 
            $miniMumAmount = isset($user_data['min_balance']) ? $user_data['min_balance'] - 1 : 49;
            if ($txn_amount > $miniMumAmount) {
            $old_balance = $user_data['balance'];
            $new_balance = $old_balance + $txn_amount;

            // Update transaction status and user balance based on the transaction status
            if ($resArray["result"]["status"] === "SUCCESS") {
                if (db_update("reports", ["txn_id" => $order_id, "ref_id" => $utr_number, "amount" => $txn_amount, "main_amount" => $txn_amount, "old_balance" => $old_balance, "new_balance" => $new_balance, "status" => "SUCCESS", "description" => "An amount of Rs. " . $txn_amount . " has been successfully credited to your wallet."], "id='" . $txn_data['id'] . "'")) {
                    db_update("members", ["balance" => $new_balance], "user_id='" . $user_data['user_id'] . "'");
                    
                    $emailmessage = "Dear {$user_data['name']}, Added Amount : <strong>{$txn_amount}.00</strong> has been successfully credited to your wallet. 
                    Old Balance : <strong>$old_balance</strong>
                    Total Balance : <strong>$new_balance</strong>.";  
                    
                    $whamessage = "Dear {$user_data['name']},\n" .
                    "Added Amount: *{$txn_amount}.00* has been successfully credited to your wallet.\n" .
                    "OrderID: *{$order_id}*\n" .
                    "Old Balance: *{$old_balance}*\n" .
                    "Total Balance: *{$new_balance}*\n\n" .
                    "Best Regards,\n" .
                    "_*{$site_data['brand']}.*_";
                    
                    send_sms_credentials($user_data['mobile'],$whamessage);
                    send_email($user_data['email'],"Wallet Recharge",$emailmessage);

                    alert_js("Transaction Successfully");
                }
            } elseif ($resArray["result"]["status"] === "FAILED") {
                if (db_update("reports", ["old_balance" => $old_balance, "new_balance" => $old_balance, "status" => "Failed"], "id='" . $txn_data['id'] . "'")) {
                    alert_js("Transaction Failed");
                }
            } else {
                alert_js("Transaction Pending Check Again Later.");
            }
        } else {
          if (db_update("reports", ["status" => "Failed", "description" => "Transaction Denied Rs {$txn_amount} You must Add an amount of Rs. {$miniMumAmount} or more"], "id='" . $txn_data['id'] . "'")) {
            $whamessage = "Dear {$txn_data['name']},\n" .
            "Transaction Denied You must Add an amount of Rs. {$miniMumAmount} or more !\n\n".
            "Please avoid making unnecessary payments on {$site_data['brand']}";
            send_sms_credentials($user_data['mobile'],$whamessage);
            alert_js("Transaction Denied You must Add an amount of Rs. {$miniMumAmount} or more.");
          }
        }
        } else {
            alert_js("User Not Found");
        }
    } else {
        alert_js("This transaction is already processed or not found.");
    }
    } else {
    alert_js("Dublicate Payment.");
}
} else {
    if ($resArray['message'] == 'Order not found') {
        db_update("reports", ["status" => "Failed"], "order_id='" .$order_id . "'");
    }
    alert_js($resArray['message']);
}

redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger",0);
die();	
}else{
    echo "Access Denied.";
redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger",0);
die();	
}

?>
<?php 
} else { 
require_once("404.php");
} 
} else {
      awal_alert_msg('You Do Not Have Permission Self Recharge!', 'info', 'dashboard');
}
}else{
 session_destroy();  
redirect("logout",0);
die;
}
?>
<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>