<?php
header('Content-Type: application/json');

$action = trim($_POST['action'] ?? '');
$name   = trim($_POST['name']   ?? '');

if (!$name || !in_array($action, ['start', 'stop'], true)) {
    echo json_encode(['ok' => false, 'error' => 'Invalid request']);
    exit;
}

// Confirm container exists
$check = trim(shell_exec('docker ps -a --filter ' . escapeshellarg('name=^' . $name . '$') . " --format '{{.Names}}' 2>/dev/null") ?? '');
if ($check !== $name) {
    echo json_encode(['ok' => false, 'error' => 'Container not found']);
    exit;
}

exec(($action === 'start' ? 'docker start' : 'docker stop') . ' ' . escapeshellarg($name) . ' 2>&1', $out, $rc);

echo json_encode(['ok' => $rc === 0, 'output' => implode("\n", $out)]);
