<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once 'db.php';

date_default_timezone_set('Asia/Kolkata');

/*
CLI / browser test script
Purpose:
- Calculate per-VM Today / Yesterday earning
- Calculate RDP-wise Today / Yesterday
- Print results (no DB writes)
*/

echo "=== PER VM TEST ===\n\n";

$vmRows = [];

$q = $conn->query("
SELECT
    v.unit_id,
    v.rdp_nickname,
    t.today_max,
    y.yest_max,
    p.prev_max
FROM vms v
LEFT JOIN (
    SELECT vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS today_max
    FROM earnapp_history
    WHERE earning_date = CURDATE()
    GROUP BY vm_id
) t ON t.vm_id = v.unit_id
LEFT JOIN (
    SELECT vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS yest_max
    FROM earnapp_history
    WHERE earning_date = CURDATE() - INTERVAL 1 DAY
    GROUP BY vm_id
) y ON y.vm_id = v.unit_id
LEFT JOIN (
    SELECT vm_id, MAX(CAST(balance AS DECIMAL(10,4))) AS prev_max
    FROM earnapp_history
    WHERE earning_date < CURDATE() - INTERVAL 1 DAY
    GROUP BY vm_id
) p ON p.vm_id = v.unit_id
");

while ($r = $q->fetch_assoc()) {
    $today = max(0, ($r['today_max'] ?? 0) - ($r['yest_max'] ?? 0));
    $yest  = max(0, ($r['yest_max'] ?? 0) - ($r['prev_max'] ?? 0));

    $vmRows[] = [
        'vm' => $r['unit_id'],
        'rdp' => $r['rdp_nickname'],
        'today' => $today,
        'yesterday' => $yest
    ];

    echo "VM: {$r['unit_id']} | RDP: {$r['rdp_nickname']} | Today: {$today} | Yesterday: {$yest}\n";
}

echo "\n=== RDP AGGREGATION TEST ===\n\n";

$rdpAgg = [];

foreach ($vmRows as $v) {
    $r = $v['rdp'] ?: 'UNKNOWN';
    if (!isset($rdpAgg[$r])) {
        $rdpAgg[$r] = ['today' => 0, 'yesterday' => 0];
    }
    $rdpAgg[$r]['today'] += $v['today'];
    $rdpAgg[$r]['yesterday'] += $v['yesterday'];
}

foreach ($rdpAgg as $rdp => $e) {
    echo "RDP: {$rdp} | Today: {$e['today']} | Yesterday: {$e['yesterday']}\n";
}

echo "\n=== TOTAL CHECK ===\n\n";

$totalToday = array_sum(array_column($vmRows, 'today'));
$totalYest  = array_sum(array_column($vmRows, 'yesterday'));

echo "TOTAL TODAY: {$totalToday}\n";
echo "TOTAL YESTERDAY: {$totalYest}\n";