<?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['mobile_dth_recharge_services']) && $user_data['mobile_dth_recharge_services'] == "YES") {

$main_site_data = main_site_data();


if (!isset($_POST['order_id']) || empty(trim($_POST['order_id']))) {
    echo "Access Denied.";
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

$order_id = trim($_POST['order_id']);
$request  = ['order_id' => $order_id];

$responseApi = Quick_Recharge_status_api_run($request);

if ($responseApi === false) {
    alert_js("Failed to fetch order information from the API.");
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

$StatusResponse = json_decode($responseApi, true);

if ($StatusResponse === null || !is_array($StatusResponse)) {
    alert_js("Invalid response from the API.");
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

// Normalize API response fields (work with variants: orderid/order_id etc.)
$statusMessageRaw = $StatusResponse['statusMessage'] ?? $StatusResponse['status'] ?? '';
$statusMessage    = strtolower(trim($statusMessageRaw));
$api_order_id     = $StatusResponse['orderid'] ?? $StatusResponse['order_id'] ?? $order_id;
$api_amount       = isset($StatusResponse['amount']) ? floatval($StatusResponse['amount']) : 0.00;
$api_number       = $StatusResponse['number'] ?? '';
$api_message      = $StatusResponse['message'] ?? '';
$api_error        = $StatusResponse['error'] ?? '';

// Find matching transaction that is still Process or Pending
// Use db_escape() if available to prevent SQL injection (replace if you have a different escaping helper)
$escaped_order_id = function_exists('db_escape') ? db_escape($order_id) : addslashes($order_id);
$txn_count = db_count("reports", "order_id='" . $escaped_order_id . "' AND status IN ('Process','Pending')");

if ($txn_count <= 0) {
    alert_js("This transaction is already processed or not found.");
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

$txn_data = db_fetch_array("reports", "order_id='" . $escaped_order_id . "' AND status IN ('Process','Pending')");
if (!$txn_data) {
    alert_js("Transaction not found.");
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

$member_data = db_fetch_array("members", "user_id='" . intval($txn_data['user_id']) . "'");
if (!$member_data) {
    alert_js("User Not Found");
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

$old_balance = floatval($member_data['balance']);
$txn_amount  = isset($txn_data['amount']) ? floatval($txn_data['amount']) : 0.00; // use main DB amount
$new_balance = $old_balance;

/**
 * Logic choices:
 * - success: mark report SUCCESS but do NOT change balance (per your last request)
 * - pending: do nothing (inform user)
 * - refund / failed / other: mark Failed/Refund and credit refund_amount (from reports table) to user balance
 */

// SUCCESS: update report to SUCCESS but DO NOT change member balance
if ($statusMessage === "success") {
    $update_report = [
        "txn_id"      => $api_order_id ?: $txn_data['txn_id'],
        "ref_id"      => $api_number ?: ($txn_data['ref_id'] ?? ''),
        "old_balance" => $txn_data['old_balance'] ?? $old_balance,
        "new_balance" => $txn_data['new_balance'] ?? $txn_data['old_balance'] ?? $old_balance,
        "status"      => "SUCCESS",
        "description" => "Recharge of Rs. " . number_format($txn_amount, 2) . " for Number {$api_number} succeeded. API message: {$api_message}"
    ];

    if (db_update("reports", $update_report, "id='" . intval($txn_data['id']) . "'")) {
        $emailmessage = "Dear {$member_data['name']}, Recharge Amount : <strong>" . number_format($txn_amount, 2) . "</strong> has been successfully recharged to Number {$api_number}.<br>
Old Balance : <strong>{$old_balance}</strong><br>
Total Balance : <strong>{$old_balance}</strong>.";

        $whamessage = "Dear {$member_data['name']},\n" .
                      "Recharge Amount: *" . number_format($txn_amount, 2) . "* succeeded for Number {$api_number}.\n" .
                      "OrderID: *{$api_order_id}*\n" .
                      "Balance: *{$old_balance}*\n\n" .
                      "Best Regards,\n" .
                      "_*{$site_data['brand']}.*_";

        // Notify user
        send_sms($member_data['mobile'], $whamessage);
        send_email($member_data['email'], "Recharge Success", $emailmessage);

        alert_js("Transaction marked as SUCCESS");
    } else {
        alert_js("Failed to update transaction to SUCCESS.");
    }

    // Redirect after processing
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

// PENDING: inform, but do not update DB balances or report (as per request)
if ($statusMessage === "pending") {
    alert_js($api_message ?: "Transaction Pending");
    redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
    exit;
}

// REFUND or FAILED or any other non-success/pending: update report and refund txn_amount back to user
// Treat "refund" and "refund" synonyms; also "failed", "error", etc.
if (in_array($statusMessage, ['refund', 'failed', 'error', 'refund_requested', 'refunded'], true) || strpos($statusMessage, 'refund') !== false) {
    $refund_amount = $txn_amount; // IMPORTANT: use original DB amount
    $new_balance   = $old_balance + $refund_amount;

    // Decide status label
    $status_label = (strpos($statusMessage, 'refund') !== false) ? "REFUND" : "Failed";

    $update_report = [
        "txn_id"      => $api_order_id ?: $txn_data['txn_id'],
        "ref_id"      => $api_number ?: ($txn_data['ref_id'] ?? ''),
        "old_balance" => $old_balance,
        "new_balance" => $new_balance,
        "status"      => $status_label,
        "description" => "Recharge {$status_label} for Number {$api_number}. API message: " . ($api_message ?: $api_error)
    ];

    if (!db_update("reports", $update_report, "id='" . intval($txn_data['id']) . "'")) {
        alert_js("Failed to update transaction status to {$status_label}.");
        redirect("https://" . $_SERVER['SERVER_NAME'] . "/members/walletledger", 0);
        exit;
    }

    // If refund amount > 0, credit user balance
    if ($refund_amount > 0) {
        if (db_update("members", ["balance" => $new_balance], "user_id='" . intval($member_data['user_id']) . "'")) {
            $emailmessage = "Dear {$member_data['name']}, Recharge of Rs. " . number_format($refund_amount, 2) . " for Number {$api_number} failed and amount has been refunded to your wallet.<br>
Old Balance : <strong>{$old_balance}</strong><br>
Total Balance : <strong>{$new_balance}</strong>.";

            $whamessage = "Dear {$member_data['name']},\n" .
                          "Recharge Amount: *" . number_format($refund_amount, 2) . "* has been refunded for Number {$api_number}.\n" .
                          "OrderID: *{$api_order_id}*\n" .
                          "Old Balance: *{$old_balance}*\n" .
                          "Total Balance: *{$new_balance}*\n\n" .
                          "Best Regards,\n" .
                          "_*{$site_data['brand']}.*_";

            send_sms($member_data['mobile'], $whamessage);
            send_email($member_data['email'], "Recharge Failed - Amount Refunded", $emailmessage);

            alert_js($api_error ?: "Transaction Failed. Amount refunded to wallet.");
        } else {
            alert_js("Transaction failed and report updated, but failed to credit refund to user balance.");
        }
    } else {
        alert_js($api_error ?: "Transaction Failed.");
    }

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

} else {
    awal_alert_msg('You Do Not Have Any Recharge Service Activated !', '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>