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


$id = (int) $_POST['id'] ?? 0;

if ($id < 1) {
    echo json_encode(['success' => false, 'message' => 'Nicht valide ID']);
    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("INSERT INTO $db_tabelle_var (`name`, `value`) VALUES ('current_wk_id', ?) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)");

$stmt->bind_param("i", $id);

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

    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;