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

date_default_timezone_set('UTC');

$timeoutMinutes = 5;

/* 1. FORCE OFFLINE FOR OLD HEARTBEAT */
$sqlOffline = "
UPDATE vms
SET status = 'Offline'
WHERE last_heartbeat IS NULL
   OR last_heartbeat < NOW() - INTERVAL {$timeoutMinutes} MINUTE
";
$conn->query($sqlOffline);

/* 2. INSERT HISTORY FOR STATUS CHANGE OR BALANCE CHANGE */
$sqlHistory = "
INSERT INTO earnapp_history
(vm_id, group_name, rdp_nickname, balance, traffic, ip_address, earnapp_token, status, recorded_at)
SELECT
    v.id,
    v.group_name,
    v.rdp_nickname,
    v.balance,
    v.traffic,
    v.current_ip,
    v.earnapp_token,
    v.status,
    NOW()
FROM vms v
WHERE NOT EXISTS (
    SELECT 1
    FROM earnapp_history h
    WHERE h.vm_id = v.id
      AND h.status = v.status
      AND h.balance = v.balance
      AND h.recorded_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
)
";
$conn->query($sqlHistory);

$conn->close();
