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

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

$type = 'tr';

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

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

$personen_ids_json = $_POST['personen_ids'] ?? '';

$personen_ids = json_decode($personen_ids_json) ?? [];

$personen_ids = !is_array($personen_ids) ? array(intval($personen_ids)) : array_map('intval', $personen_ids);

if (count($personen_ids) < 1) {
    echo json_encode(['success' => false, 'message' => "Keine Personen angegeben"]);
    http_response_code(422);
    exit;
}

$userid = intval($_SESSION['user_id_trainer'] ?? 0);
$arrayfreigaben = [];

if ($userid > 0) {
    $freigabe_json = db_get_var($mysqli, "SELECT freigabe FROM $db_tabelle_intern_benutzende WHERE id = ?", [$userid]);

    if (is_string($freigabe_json) && $freigabe_json !== '') {
        $arrayfreigaben = json_decode($freigabe_json, true) ?: [];

        $arrayfreigaben = $arrayfreigaben['freigabenTrainer'] ?? [];
    }
}

if (!empty($arrayfreigaben)) {
    $selectedverein = $_SESSION['selectedFreigabeTrainer'] ?? '';

    if (!in_array($selectedverein, $arrayfreigaben)) {
        $selectedverein = $arrayfreigaben[0];
        $_SESSION['selectedFreigabeTrainer'] = $selectedverein;
    }
}

$isAdmin = $selectedverein === "admin";

$mysqli->begin_transaction();

try {
    if (!$isAdmin) {
        $stmt = $mysqli->prepare("DELETE FROM $db_tabelle_teilnehmende WHERE `id` = ? AND `verein` = ?");
        foreach ($personen_ids as $s_id) {
            $stmt->bind_param("is", $s_id, $selectedverein);
            $stmt->execute();
        }
    } else {
        $stmt = $mysqli->prepare("DELETE FROM $db_tabelle_teilnehmende WHERE `id` = ?");
        foreach ($personen_ids as $s_id) {
            $stmt->bind_param("i", $s_id);
            $stmt->execute();
        }
    }
    $stmt->close();
    $mysqli->commit();
} catch (Exception $e) {
    $mysqli->rollback();
    echo json_encode(['success' => false, 'message' => "Datenbankfehler beim Löschen"]);
    http_response_code(500);
    exit;
}

echo json_encode(['success' => true, 'message' => count($personen_ids) . " Datensätze gelöscht"]);
http_response_code(200);
exit;
