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

verify_csrf();


$type = 'tr';

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

// --- Get input ---
$id  = isset($_POST['id']) ? intval($_POST['id']) : 0;
$userId = intval($_SESSION['user_id_trainer']);

// --- Validate inputs ---
if ($id < 1) {
    http_response_code(422);
    echo json_encode(["success" => false, "message" => "Nicht valide id"]);
    exit;
}

$verein = db_get_var($mysqli, "SELECT `verein` FROM $db_tabelle_teilnehmende WHERE `id` = ?", [$id]);

if ($verein === null) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Person hat keinen Verein"]);
    exit;
}

$verein_konto = db_get_var($mysqli, "SELECT `konto` FROM $db_tabelle_vereine WHERE `verein` = ?", [$verein]) ?: 0.00;

// --- Check for existing open order ---
$sql = "DELETE FROM $db_tabelle_warenkorb_startgebueren WHERE user_id = ? AND item_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ii", $userId, $id);

if (!$stmt->execute()) {
    http_response_code(500);
    exit;
}

http_response_code(200);
echo json_encode(["success" => true, "message" => "Startgebühr entfernt", "verein" => $verein, "vereinKonto" => $verein_konto]);
exit;
?>