<?php
declare(strict_types=1);
define('DASHBOARD_ROOT', dirname(__DIR__, 2));
require_once DASHBOARD_ROOT . '/core/bootstrap.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit(json_encode(['ok'=>false,'error'=>'POST required']));
}

RBAC::enforce('fleet.command');
CSRF::enforce();

$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
$action = $input['action'] ?? '';
$nodeId = (int)($input['node_id'] ?? 0);

require_once DASHBOARD_ROOT . '/core/fleet_orchestrator.php';

switch ($action) {
    case 'lockdown':
        RBAC::enforce('fleet.lockdown');
        $adminId = (int)($_SESSION['admin_id'] ?? 0);
        FleetOrchestrator::lockdown($adminId, $input['reason'] ?? 'Manual lockdown');
        echo json_encode(['ok'=>true,'message'=>'Lockdown initiated']);
        break;

    case 'heartbeat_check':
        $nodes = FleetOrchestrator::getNodes();
        $results = [];
        foreach ($nodes as $n) {
            $age = $n['heartbeat_age_sec'] ?? null;
            $results[] = [
                'node_id' => $n['node_id'],
                'role' => $n['node_role'],
                'status' => $n['status'],
                'heartbeat_age' => $age,
                'healthy' => ($age !== null && $age < 300),
            ];
        }
        echo json_encode(['ok'=>true,'nodes'=>$results]);
        break;

    case 'refresh_status':
        $nodes = FleetOrchestrator::getNodes();
        $out = [];
        foreach ($nodes as $n) {
            $out[] = [
                'node_id' => $n['node_id'],
                'role' => $n['node_role'],
                'status' => $n['status'],
                'cpu' => (float)($n['cpu_usage_pct'] ?? 0),
                'mem' => (float)($n['mem_usage_pct'] ?? 0),
                'disk' => (float)($n['disk_usage_pct'] ?? 0),
                'version' => $n['engine_version'] ?? '',
                'last_heartbeat' => $n['last_heartbeat'] ?? null,
            ];
        }
        echo json_encode(['ok'=>true,'nodes'=>$out]);
        break;

    default:
        echo json_encode(['ok'=>false,'error'=>'Unknown action: '.$action]);
}