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

$type = 'wkl';

$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($data['success'] === false){
	echo json_encode(['success' => false, 'message' => $data['message']]);
    exit; 
}

require $baseDir . '/../scripts/db/db-tables.php';

$allowedTypes = [
    'wkName', 
    'displayCTextLogo', 
    'displayCTextWKName',
    'displayColourLogo', 
    'displayTextColourLogo', 
    'displayColorScoringBg',
    'displayColorScoringBgSoft',
    'displayColorScoringShadowColor',
    'displayColorScoringBorderColor',
    'displayColorScoringPanel',
    'displayColorScoringPanelSoft',
    'displayColorScoringPanelText',
    'displayColorScoringPanelTextSoft',
    'displayColorScoringPanelTextNoteL',
    'displayColorScoringPanelTextNoteR',
    'displayIdNoteL',
    'displayIdNoteR',
    'rechnungenName', 
    'rechnungenVorname', 
    'rechnungenStrasse', 
    'rechnungenHausnummer', 
    'rechnungenPostleitzahl', 
    'rechnungenOrt',
    'rechnungenIBAN',
    'maxLengthMusic',
    'linkWebseite',
    'rangNote',
    'orderBestRang',
    'rechnungenPostversand',
    'rechnungenPostversandKosten',
    'personEinzahl',
    'personMehrzahl',
    'rankLivePublic',
    'riegeneinteilungPublic'
];

$type = $_POST['type'] ? trim($_POST['type']) : '';

if (!in_array($type, $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

$value = $_POST['value'] ? trim($_POST['value']) : null;

// ---------- Step 2: Get values from DB ----------


$stmt = $mysqli->prepare("INSERT INTO $db_tabelle_var (`name`, `value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)");

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Critical db error']);
    exit;
}

$stmt->bind_param("ss", $type, $value);
$success = $stmt->execute();
$stmt->close();

if (!$success) {
    echo json_encode(['success' => false, 'message' => 'Insert failed']);
    exit;
}

// Return JSON
echo json_encode([
    'success' => true
]);
exit;