<?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();

if (!isset($_POST['css_content'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing css_content parameter.']);
    exit;
}

$css_content = $_POST['css_content'] ?? '';

if (strlen($css_content) > 200000) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'File size too large.']);
    exit;
}

if (preg_match('/javascript:/i', $css_content) || preg_match('/<script/i', $css_content)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid characters detected.']);
    exit;
}

file_put_contents($baseDir . '/intern/css/user.css', $css_content);

http_response_code(200);
echo json_encode(['success' => true, 'message' => 'CSS saved successfully.']);
exit;
