<?php
require_once __DIR__ . '/db.php';

$RATE_PER_HOUR   = 0.02;
$RATE_PER_MINUTE = $RATE_PER_HOUR / 60;

$conn->query("
    UPDATE vms
    SET status = 'Offline'
    WHERE last_heartbeat IS NULL OR last_heartbeat < (NOW() - INTERVAL 10 MINUTE)
");

$q = $conn->query("
    SELECT vm_id, COUNT(*) AS minutes_online
    FROM vm_heartbeats
    WHERE DATE(created_at) = CURDATE()
      AND earnapp_running = 1
    GROUP BY vm_id
");

if ($q) {
    while ($row = $q->fetch_assoc()) {
        $vmId    = (int)$row['vm_id'];
        $minutes = (int)$row['minutes_online'];
        $earning = round($minutes * $RATE_PER_MINUTE, 4);

        $stmt = $conn->prepare("
            INSERT INTO vm_earnings (vm_id, date, minutes_online, earning)
            VALUES (?, CURDATE(), ?, ?)
            ON DUPLICATE KEY UPDATE
                minutes_online = VALUES(minutes_online),
                earning = VALUES(earning)
        ");
        $stmt->bind_param("iid", $vmId, $minutes, $earning);
        $stmt->execute();
        $stmt->close();
    }
}

$conn->query("
    DELETE FROM vm_heartbeats
    WHERE created_at < (NOW() - INTERVAL 7 DAY)
");

$conn->close();
echo "CRON OK\n";