<?php
require_once "../config/db.php";

$wallet = "TJAbqzvjE1bbs8GLUtxfe7P4troEgMT7UZ";

$url = "https://api.trongrid.io/v1/accounts/$wallet/transactions/trc20";

$response = file_get_contents($url);
$data = json_decode($response,true);

if(!isset($data["data"])) exit;

foreach($data["data"] as $tx){

    $hash = $tx["transaction_id"];
    $amount = $tx["value"] / 1000000;

    $symbol = $tx["token_info"]["symbol"];

    if($symbol != "USDT") continue;

    $stmt = $conn->prepare("
    SELECT id,user_id FROM crypto_deposits
    WHERE status='pending'
    LIMIT 1
    ");

    $stmt->execute();
    $res = $stmt->get_result();

    if($row = $res->fetch_assoc()){

        $depositId = $row["id"];
        $userId = $row["user_id"];

        $conn->query("
        UPDATE crypto_deposits
        SET status='confirmed', tx_hash='$hash'
        WHERE id=$depositId
        ");

        $conn->query("
        UPDATE users
        SET balance = balance + $amount
        WHERE id=$userId
        ");
    }
}

/** ---cronjob---     php /var/www/trading-backend/cron/tron_watcher.php     */