<?php
// Raw conf read/write — respects per-host file visibility from vv_get_conf_files().
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/config.php';

$allowed = vv_get_conf_files();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $file = trim($_GET['file'] ?? 'master.conf');
    if (!in_array($file, $allowed, true) || str_contains($file, '..')) {
        echo json_encode(['ok' => false, 'error' => 'Not allowed']);
        exit;
    }
    echo json_encode(['ok' => true, 'content' => vv_read_conf_raw($file), 'file' => $file, 'allowed' => $allowed]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file    = trim($_POST['file'] ?? '');
    $content = $_POST['content'] ?? '';
    if (!in_array($file, $allowed, true) || str_contains($file, '..')) {
        echo json_encode(['ok' => false, 'error' => 'Not allowed']);
        exit;
    }
    $written = vv_write_conf_raw($file, $content);
    $push    = [];
    if ($written && $file === 'master.conf') {
        $push = vv_push_master_conf();
        vv_push_setup_state();
    }
    echo json_encode(['ok' => $written, 'push' => $push]);
    exit;
}

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