<?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 = 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';

$value = isset($_POST['value']) ? preg_replace('/[^a-zA-Z0-9\s\-"]/u', '', $_POST['value']) : '';

if (!$value || $value === ''){
    echo json_encode(['success' => false, 'message' => 'No input']);
    exit;
}


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


$stmt = $mysqli->prepare("INSERT INTO `$db_tabelle_kategorien` (programm) VALUES (?)");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Critical DB ERROR']);
    exit;
}

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

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

// Fetch all rows
$query2 = "SELECT * FROM `$db_tabelle_kategorien` ORDER BY programm ASC";
$programme = $mysqli->query($query2);

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

$output = [];
while ($entry = $programme->fetch_assoc()) {
    $output[] = [
        'id' => $entry['id'],
        'programm' => $entry['programm'],
        'aktiv' => intval($entry['aktiv']),
        'preis' => floatval($entry['preis']),
        'orderIndex' => intval($entry['order_index'])
    ];
}

require_once $baseDir . '/../scripts/cache/cache-creators/regenerate-display-dependencies-cache.php';

generateIntersectCache($mysqli, $baseDir);

// Return JSON
echo json_encode([
    'success' => true,
    'output' => $output,
    'message' => $value.' hinzugefügt'
]);
exit;