<?php
require_once 'db.php';

$vms = $conn->query("SELECT earnapp_token, balance, status, ip_address FROM vms");

while ($row = $vms->fetch_assoc()) {
    $token = $row['earnapp_token'];
    $current_balance = (float)$row['balance'];
    
    $last_record = $conn->query("
    SELECT redeem_balance 
    FROM earnapp_history 
    WHERE earnapp_token = '$token' 
    ORDER BY recorded_at DESC 
    LIMIT 1
")->fetch_assoc();

$previous_balance = $last_record ? (float)$last_record['redeem_balance'] : 0;

if (abs($current_balance - $previous_balance) < 0.0001) {
    continue;
}

    $cashout_detected = 0;
    if ($previous_balance > 0.01 && $current_balance < 0.005 && $current_balance < $previous_balance) {
        $cashout_detected = 1;
    }

    $stmt = $conn->prepare("INSERT INTO earnapp_history (earnapp_token, ip_address, redeem_balance, cashout_detected, status, recorded_at) VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("ssdis", $token, $row['ip_address'], $current_balance, $cashout_detected, $row['status']);
    $stmt->execute();
}