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

ini_set('display_errors', 1);

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 = include $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';
require $baseDir . '/../scripts/db/db-functions.php';

// ---------- Get and sanitize input ----------
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$value = isset($_POST['value']) ? floatval($_POST['value']) : 0;
$type = isset($_POST['type']) ? $_POST['type'] : '';

$allowedTypes = ['preis', 'order_index', 'aktiv'];
if (!in_array($type, $allowedTypes, true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid type']);
    http_response_code(400);
    exit;
}

if ($id < 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid ID']);
    exit;
}

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


$query = "UPDATE `$db_tabelle_kategorien` SET $type = '$value' WHERE id = $id";
$result = $mysqli->query($query);

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

if ($type === 'aktiv') {
    require_once $baseDir . '/../scripts/cache/cache-creators/regenerate-display-dependencies-cache.php';

    generateIntersectCache($mysqli, $baseDir);
}

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