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


$id = (int) $_POST['id'] ?? 0;
$field_name = trim($_POST['inputType'] ?? '');
$value = trim($_POST['value'] ?? '');

$allowed_field_names = ['name', 'slug'];

if (!in_array($field_name, $allowed_field_names)) {
    echo json_encode(['success' => false, 'message' => 'Nicht valides Feld']);
    http_response_code(400);
    exit;
}

if ($id < 1) {
    echo json_encode(['success' => false, 'message' => 'Nicht valide ID']);
    http_response_code(400);
    exit;
}

if ($value === '') {
    echo json_encode(['success' => false, 'message' => 'Inhalt ist leer']);
    http_response_code(400);
    exit;
}

if ($field_name === 'slug'){
    if (preg_match('/\s/', $slug)) {
        echo json_encode(['success' => false, 'message' => 'Der Slug darf keine Leerzeichen enthalten']);
        http_response_code(400);
        exit;
    }

    // Optional: Ensure the slug only contains lowercase letters, numbers, and hyphens
    if (!preg_match('/^[a-z0-9-]+$/', $slug)) {
        echo json_encode(['success' => false, 'message' => 'Der Slug darf nur Kleinbuchstaben, Zahlen und Bindestriche enthaltenn']);
        http_response_code(400);
        exit;
    }
}

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

$type = 'wkl';

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

$id_row = db_select($mysqli, $db_tabelle_wettkaempfe, "1", "`id` = ?", [$id]);

if (count($id_row) !== 1) {
    echo json_encode(['success' => false, 'message' => 'Diese ID existiert nicht']);
    http_response_code(400);
    exit;
}

$stmt = $mysqli->prepare("UPDATE $db_tabelle_wettkaempfe SET `$field_name` = ? WHERE `id` = ?");

$stmt->bind_param("si", $value, $id);

try {
    $stmt->execute();
} catch (mysqli_sql_exception $e) {

    // Error 1062: Duplicate entry
    if ($e->getCode() === 1062) {
        echo json_encode(['success' => false, 'message' => 'Dieser Slug existiert bereits']);
        http_response_code(400);
        exit;
    }

    // Error 1054: Unknown column (e.g., $field_name doesn't exist)
    if ($e->getCode() === 1054) {
        echo json_encode(['success' => false, 'message' => "Das Feld '$field_name' existiert nicht"]);
        http_response_code(400);
        exit;
    }

    // Fallback for other database errors
    echo json_encode(['success' => false, 'message' => 'Ein Datenbankfehler ist aufgetreten']);
    http_response_code(500);
    exit;
}
    
$stmt->close();

// Return JSON
echo json_encode([
    'success' => true,
    'message' => 'Wert geändert'
]);
exit;