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

if (!isset($baseDir)) {
	$baseDir = $_SERVER['DOCUMENT_ROOT'];
}

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session();

check_user_permission('wk_leitung');

verify_csrf();

// ---------- Get and sanitize input ----------
$type = isset($_POST['type']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_POST['type']) : '';

$allowed_types = ['logo','scoring','ctext'];
if (!in_array($type, $allowed_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid type']);
    exit;
}

if ($type === 'ctext'){
	$ctext = isset($_POST['ctext']) ? $_POST['ctext'] : '';
}

$folder = realpath($baseDir.'/externe-geraete/json');
if ($folder === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Could not find displays folder.'
    ]);
    exit;
}

$filename = 'config.json';
$filepath = $folder . '/' . $filename;

if (!is_writable($folder)) {
    echo json_encode(['success' => false, 'message' => 'Folder not writable: ' . $folder]);
    exit;
}


$jsonString = file_get_contents($filepath);

// decode JSON, fallback to empty array if invalid
$oldjson = json_decode($jsonString, true) ?? [];

$oldjson["type"] = $type;

if ($type === 'ctext'){
	$oldjson["ctext"] = $ctext;
}

$jsonData = json_encode($oldjson);



// Write file
if (file_put_contents($filepath, $jsonData) === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to write JSON file: ' . $filepath
    ]);
    exit;
}

// ---------- Return JSON ----------
echo json_encode([
    'success' => true,
    'message' => 'JSON type updated',
	'disable_start_button' => true
]);
exit;