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

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

if ($dbconnection['success'] !== true){
    echo json_encode(['success' => false, 'message' => 'Critical DB Error.']);
    exit;
}

$id = intval($_POST['field_id']) ?? '';
$verein = htmlspecialchars(trim($_POST['verein'] ?? ''));

if (!isset($id) || !is_int($id) || !isset($verein)){
    echo json_encode(['success' => false, 'message' => 'Invalid Input.']);
    exit;
}

if ($id > 0) {
    $updated = db_update($mysqli, $db_tabelle_vereine, [
        'verein' => $verein,
    ], ['id' => $id]);
} else {
    $stmt = $mysqli->prepare(
        "INSERT INTO {$db_tabelle_vereine}
        (verein)
        VALUES (?)"
    );

    $stmt->bind_param(
        "s",
        $verein
    );

    $updated = $stmt->execute();
}

if ($updated !== false) {
    if ($id == 0) { // new user
        $new_id = $mysqli->insert_id;

        echo json_encode(['success' => true, 'message' =>  $verein.' wurde erfolgreich erstellt.', 'id' => $new_id]);
    } else {
        echo json_encode(['success' => true, 'message' =>  $verein.' wurde erfolgreich aktualisiert.']);
    }
} else {
    echo json_encode(['success' => false, 'message' =>  'DB Error']);
}
