<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instant Balance Add By HKB</title>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- SweetAlert -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>

<?php
session_start();

$hostname = 'localhost';
$username = 'u524285562_webnew';
$password = 'U524285562_webnew';
$database = 'u524285562_webnew';

$conn = new mysqli($hostname, $username, $password, $database);

if ($conn->connect_error) {
    echo "<script>
        Swal.fire('Database Error', 'Database connection failed: " . addslashes($conn->connect_error) . "', 'error');
    </script>";
    exit;
}

// ✅ Session check
if (!isset($_SESSION['order_id'], $_SESSION['customer_mobile'])) {
    echo "<script>
        Swal.fire('Error', 'Order ID or Customer Mobile not set in session', 'error');
    </script>";
    exit;
}

// ✅ Sanitize values
$order_id = preg_replace('/[^a-zA-Z0-9]/', '', $_SESSION['order_id']);
$customer_mobile = filter_var($_SESSION['customer_mobile'], FILTER_SANITIZE_STRING);

// ✅ Prevent double processing
if (!empty($_SESSION['wallet_updated'][$order_id])) {
    echo "<script>
        Swal.fire('Info', 'Wallet already updated for this order ID', 'info').then(() => {
            window.location.href = 'https://allcscseva.shop/admin/index.php';
        });
    </script>";
    exit;
}

// ✅ API call
$url = "https://pay.allwebfast.in/api/check-order-status";
$postData = [
    "user_token" => "4f4f2d5860edb2ee76ba899d3b63bd02",  // API Token
    "order_id"   => $order_id
];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query($postData),
    CURLOPT_TIMEOUT        => 15
]);

$response = curl_exec($ch);

if ($response === false) {
    $curlError = curl_error($ch);
    echo "<script>
        Swal.fire('cURL Error', '" . addslashes($curlError) . "', 'error');
    </script>";
    curl_close($ch);
    exit;
}
curl_close($ch);

// ✅ Decode safely
$responseData = json_decode($response, true);

if (!is_array($responseData)) {
    echo "<script>
        Swal.fire('Error', 'Invalid API response received', 'error');
    </script>";
    exit;
}

// ✅ Check payment status
if (
    isset($responseData["status"], $responseData["result"]["txnStatus"]) &&
    $responseData["status"] === "COMPLETED" &&
    $responseData["result"]["txnStatus"] === "COMPLETED"
) {
    $amount = intval($responseData["result"]["amount"]);

    // ✅ Update wallet securely (using users table and balance column)
    $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE phone = ?");
    $stmt->bind_param("is", $amount, $customer_mobile);

    if ($stmt->execute()) {
        $_SESSION['wallet_updated'][$order_id] = true;

        echo "<script>
            Swal.fire('SUCCESS', 'Wallet updated successfully!', 'success').then(() => {
                window.location.href = 'https://allcscseva.shop/admin/index.php';
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire('Error', 'Wallet update failed: " . addslashes($conn->error) . "', 'error').then(() => {
                window.location.href = 'https://allcscseva.shop/admin/index.php';
            });
        </script>";
    }
    $stmt->close();
} else {
    $status = $responseData["status"] ?? "Unknown";
    echo "<script>
        Swal.fire('Payment Error', 'API call unsuccessful. Status: {$status}', 'error').then(() => {
            window.location.href = 'https://allcscseva.shop/admin/index.php';
        });
    </script>";
}

$conn->close();
?>

</body>
</html>
