<?php
require_once __DIR__ . '/../db.php';
date_default_timezone_set('Asia/Kolkata');

$res = $conn->query("
    SELECT vm_id, MAX(balance) bal
    FROM earnapp_history
    WHERE earning_date = CURDATE()
    GROUP BY vm_id
");
$today = [];
while ($r = $res->fetch_assoc()) {
    $today[$r['vm_id']] = (float)$r['bal'];
}

$res = $conn->query("
    SELECT vm_id, MAX(balance) bal
    FROM earnapp_history
    WHERE earning_date = CURDATE() - INTERVAL 1 DAY
    GROUP BY vm_id
");
$yest = [];
while ($r = $res->fetch_assoc()) {
    $yest[$r['vm_id']] = (float)$r['bal'];
}

$vms = $conn->query("SELECT id, balance FROM vms");
while ($v = $vms->fetch_assoc()) {

    $vmId = $v['id'];
    $todayMax = (float)$v['balance'];
    $yestMax  = $yest[$vmId] ?? 0;

    $daily = $todayMax - $yestMax;
    $cashout = 0;

    if ($daily < 0 && $todayMax > 0) {
        $daily = $todayMax;
        $cashout = 1;
    }

    $conn->query("
        INSERT INTO earnapp_history
        (vm_id, balance, daily_earning, cashout_detected, earning_date)
        VALUES
        ('$vmId', '$todayMax', '$daily', '$cashout', CURDATE())
        ON DUPLICATE KEY UPDATE
        balance=VALUES(balance),
        daily_earning=VALUES(daily_earning),
        cashout_detected=VALUES(cashout_detected)
    ");
}