<?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') {

            $main_site_data = main_site_data();
            $order_id = $_GET['order_id'] ?? null;

            if (!$order_id) {
                alert_js("Order ID is missing.");
                exit;
            }

            // Prepare API request
            $api_url = "https://" . paymentapi("gateway_Url") . "/api/check-order-status";
            $post_data = [
                "user_token" => paymentapi("smartupi_token"),
                "order_id"   => $order_id,
            ];

            $ch = curl_init($api_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            $response = curl_exec($ch);

            if (curl_errno($ch)) {
                echo "cURL Error: " . curl_error($ch);
                exit;
            }
            curl_close($ch);

            $resArray = json_decode($response, true);
            if (!$resArray) {
                alert_js("Error decoding the API response.");
                exit;
            }

            if (isset($resArray["message"]) && $resArray["message"] === "Transaction Successfully") {
                $result = $resArray["result"] ?? null;

                if ($result) {
                    $txnStatus = $result["txnStatus"] ?? '';
                    $txnAmount = floatval($result["amount"] ?? 0);
                    $orderId   = $result["orderId"] ?? '';
                    $utr       = $result["utr"] ?? '';
                    $status    = $result["status"] ?? '';

                    $txn_data = db_fetch_array("reports", "order_id='" . $orderId . "'");
                    if (!$txn_data) {
                        alert_js("Transaction not found.");
                        redirect("walletledger", 0);
                        exit;
                    }

                    if ($txn_data['status'] === "Success") {
                        alert_js("Transaction already processed.");
                        redirect("walletledger", 0);
                        exit;
                    }

                    $user = db_fetch_array("members", "user_id='" . $txn_data['user_id'] . "'");
                    if (!$user) {
                        alert_js("User not found.");
                        redirect("walletledger", 0);
                        exit;
                    }

                    $old_balance = floatval($user['balance']);
                    $new_balance = $old_balance + $txnAmount;

                    // ✅ Updated "Denied" to "Failed"
                    if ($txnAmount < 100) {
                        db_update("reports", [
                            "status"      => "Failed", // changed from "Denied"
                            "amount"      => $txnAmount,
                            "ref_id"      => $utr,
                            "old_balance" => $old_balance,
                            "new_balance" => $old_balance
                        ], "id='" . $txn_data['id'] . "'");

                        $whamessage = "Dear {$user['name']},\n" .
                            "Transaction Failed. Minimum recharge is Rs. 100!\n\n" .
                            "Please avoid making unnecessary payments on {$site_data['brand']}.";

                        send_sms($user['mobile'], $whamessage);

                        alert_js("Transaction Failed. Minimum amount is Rs. 100.");
                        redirect("walletledger", 0);
                        exit;
                    }

                    if ($status === "SUCCESS") {
                        if (db_update("reports", [
                            "txn_id"      => $orderId,
                            "ref_id"      => $utr,
                            "old_balance" => $old_balance,
                            "new_balance" => $new_balance,
                            "amount"      => $txnAmount,
                            "status"      => "Success",
                            "description" => "An amount of Rs. " . $txnAmount . " has been successfully credited to your wallet."
                        ], "id='" . $txn_data['id'] . "'")) {

                            db_update("members", ["balance" => $new_balance], "user_id='" . $user['user_id'] . "'");

                            // Notify user
                            $emailmessage = "Dear {$user['name']}, Added Amount : <strong>{$txnAmount}.00</strong> has been successfully credited to your wallet.<br>" .
                                "Old Balance : <strong>Rs.{$old_balance}</strong><br>" .
                                "Total Balance : <strong>Rs.{$new_balance}</strong>";

                            $whamessage = "Dear {$user['name']},\n" .
                                "Added Amount: *Rs.{$txnAmount}.00* has been successfully credited to your wallet.\n" .
                                "OrderID: *{$order_id}*\n" .
                                "Old Balance: *Rs.{$old_balance}*\n" .
                                "Total Balance: *Rs.{$new_balance}*\n\n" .
                                "Best Regards,\n" .
                                "_*{$site_data['brand']}*_";

                            send_sms($user['mobile'], $whamessage);
                            send_email($user['email'], "Wallet Recharge", $emailmessage);
                            unset($_SESSION['order_id']);

                            alert_js("Transaction Successful. Rs.$txnAmount. Redirecting to wallet ledger...");
                            redirect("walletledger", 0);
                            exit;
                        } else {
                            alert_js("Failed to update transaction report.");
                        }

                    } elseif ($status === "FAILED") {
                        db_update("reports", [
                            "old_balance" => $old_balance,
                            "new_balance" => $old_balance,
                            "status"      => "Failed"
                        ], "id='" . $txn_data['id'] . "'");
                        alert_js("Transaction Failed.");
                        redirect("walletledger", 0);
                        exit;

                    } else { // PENDING or unknown status
                        db_update("reports", [
                            "old_balance" => $old_balance,
                            "new_balance" => $old_balance,
                            "status"      => "Pending"
                        ], "id='" . $txn_data['id'] . "'");
                        alert_js("Transaction Pending.");
                        redirect("walletledger", 0);
                        exit;
                    }

                } else {
                    alert_js("Transaction not successful or missing result.");
                    redirect("walletledger", 0);
                    exit;
                }
            } else {
                alert_js("Transaction not successful: " . ($resArray["message"] ?? "Unknown error"));
                redirect("walletledger", 0);
            }

        } else {
            require_once("404.php");
        }

    } else {
        awal_alert_msg('You Do Not Have Permission for 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>