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

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = trim($_GET['id'] ?? '');
    if (!$id || str_contains($id, '..')) {
        echo json_encode(['ok' => false, 'error' => 'Invalid id']);
        exit;
    }
    $groups = vv_conf_fields_for_script($id);
    echo json_encode(['ok' => true, 'groups' => $groups]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id      = trim($_POST['id']      ?? '');
    $rawJson = $_POST['changes'] ?? '[]';

    if (!$id) { echo json_encode(['ok' => false, 'error' => 'Missing id']); exit; }

    $changes = json_decode($rawJson, true);
    if (!is_array($changes)) { echo json_encode(['ok' => false, 'error' => 'Invalid changes']); exit; }

    $allowed = vv_get_conf_files();
    foreach ($changes as $c) {
        if (empty($c['file']) || !in_array($c['file'], $allowed, true)) {
            echo json_encode(['ok' => false, 'error' => 'Unauthorized file: ' . ($c['file'] ?? '')]);
            exit;
        }
        if (empty($c['key']) || !preg_match('/^[A-Z_][A-Z0-9_]*$/', $c['key'])) {
            echo json_encode(['ok' => false, 'error' => 'Invalid key: ' . ($c['key'] ?? '')]);
            exit;
        }
    }

    $results = vv_conf_write_changes($changes);

    // Propagate master.conf to partner hosts when the owner edits it (mirrors rawconf.php).
    $push = [];
    if (($results['master.conf'] ?? false) === true) {
        $push = vv_push_master_conf();
        vv_push_setup_state();
    }

    echo json_encode(['ok' => !in_array(false, $results, true), 'files' => $results, 'push' => $push]);
    exit;
}

echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
