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

$vmId = $_POST['vm_id'];
$newToken = trim($_POST['earnapp_token']);

$old = $conn->query("
    SELECT earnapp_token, balance
    FROM vms WHERE id='$vmId'
")->fetch_assoc();

$oldToken = $old['earnapp_token'];
$lastBal  = $old['balance'];

if ($oldToken && $oldToken !== $newToken) {
    $conn->query("
        INSERT INTO sdk_token_history
        (vm_id, old_token, last_balance)
        VALUES
        ('$vmId', '$oldToken', '$lastBal')
    ");
}

$conn->query("
    UPDATE vms SET earnapp_token='$newToken'
    WHERE id='$vmId'
");