<?php
header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate');

$agentPath = __DIR__ . '/../../static/agent.ps1';

if (!file_exists($agentPath)) {
    http_response_code(500);
    echo json_encode(['error' => 'agent.ps1 not found on server']);
    exit;
}

$agentContent  = file_get_contents($agentPath);
$serverVersion = '0.0.0';
if (preg_match('/\$AGENT_VERSION\s*=\s*"([^"]+)"/', $agentContent, $m)) {
    $serverVersion = trim($m[1]);
}

$serverHash    = strtoupper(hash_file('sha256', $agentPath));
$clientVersion = trim($_GET['version'] ?? '0.0.0');
$updateAvailable = version_compare($serverVersion, $clientVersion, '>');

echo json_encode([
    'update_available' => $updateAvailable,
    'version'          => $serverVersion,
    'sha256'           => $serverHash,
    'checked_at'       => date('Y-m-d H:i:s'),
]);