<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/config.php';

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

$body  = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $body['action'] ?? '';

$allowed = ['stop', 'shutdown', 'restart'];
if (!in_array($action, $allowed, true)) {
    echo json_encode(['ok' => false, 'error' => 'invalid action']);
    exit;
}

$cmd = match($action) {
    'stop'     => '/usr/local/sbin/mdcmd stop',
    'shutdown' => '/sbin/shutdown -h now',
    'restart'  => '/sbin/shutdown -r now',
};

$logLine = date('Y-m-d H:i:s') . " action={$action} ip=" . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n";
@file_put_contents(SCRIPTS_DIR . '/actions.log', $logLine, FILE_APPEND | LOCK_EX);

exec($cmd . ' > /dev/null 2>&1 &');
echo json_encode(['ok' => true]);
