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

$name = trim($_POST['name'] ?? '');
$slug = trim($_POST['slug'] ?? '');

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

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

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

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

$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';

$stmt = $mysqli->prepare("INSERT INTO $db_tabelle_wettkaempfe (`name`, `slug`) VALUES (?, ?)");

$stmt->bind_param("ss", $name, $slug);

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

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

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

$insert_id = $mysqli->insert_id;

// Return JSON
echo json_encode([
    'success' => true,
    'message' => 'Wettkampf hinzugefügt',
    'id' => $insert_id
]);
exit;