 <?php
header('Content-Type: application/json');
require_once '../config/db.php'; 

$wallet = $_GET['wallet'];
$apiKey = "a6a4fd3b6d27ab07cf90ab39e9867d1a3f0be8c0889f52b1712d7300099aa8ae";
$admin_receiving_wallet = "0xFa998baCC7A72de1B220B1b796D73b76239B89e1"; // <--- Apna main address yahan dalein
$usdt_contract = "0x55d398326f99059fF775485246999027B3197955"; 

// 1. Database se address nikalein using 'wallet' column
$res = mysqli_query($conn, "SELECT deposit_address, private_key FROM deposits WHERE wallet = '$wallet' AND status = 'pending' LIMIT 1");
$row = mysqli_fetch_assoc($res);

if(!$row) {
    echo json_encode(["confirmed" => false, "message" => "No pending deposit found"]);
    exit;
}

$address = $row['deposit_address'];
$privKey = $row['private_key'];

// 2. Tatum API balance check
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tatum.io/v3/blockchain/token/address/BSC/$address/$usdt_contract");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["x-api-key: $apiKey"]);
$response = curl_exec($ch);
$balanceData = json_decode($response, true);
curl_close($ch);

$amount = isset($balanceData[0]['balance']) ? (float)$balanceData[0]['balance'] : 0;

if ($amount > 0) {
    // 3. AUTO-SWEEP: Admin wallet mein transfer
    $transferData = [
        "to" => $admin_receiving_wallet,
        "currency" => "USDT_BSC",
        "amount" => strval($amount),
        "fromPrivateKey" => $privKey
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.tatum.io/v3/blockchain/token/transaction");
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($transferData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json", "x-api-key: $apiKey"]);
    $sweepRes = curl_exec($ch);
    $sweepData = json_decode($sweepRes, true);
    curl_close($ch);

    if (isset($sweepData['txId'])) {
        mysqli_begin_transaction($conn);
        // DB columns update
        mysqli_query($conn, "UPDATE deposits SET amount = '$amount', status = 'completed', tx_hash = '".$sweepData['txId']."' WHERE deposit_address = '$address'");
        mysqli_query($conn, "UPDATE users SET balance = balance + $amount WHERE wallet = '$wallet'");
        mysqli_commit($conn);
        
        echo json_encode(["confirmed" => true, "amount" => $amount]);
    } else {
        echo json_encode(["confirmed" => false, "message" => "Sweep failed. Check BNB Gas fees on deposit address."]);
    }
} else {
    echo json_encode(["confirmed" => false, "message" => "Payment not detected yet"]);
}
?>