<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// Show all errors except deprecation notices (these come from vendor libraries
// that aren't yet typed for newer PHP versions). Long-term fix: update
// dependencies to versions compatible with your PHP runtime.
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);


if (!isset($baseDir)) {
	$baseDir = $_SERVER['DOCUMENT_ROOT'];
}

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session();

check_user_permission('wk_leitung');

verify_csrf();

// Validate input
if (!isset($_POST['abtId']) || !ctype_digit($_POST['abtId'])) {
    http_response_code(406);
    exit;
}

$abtInputId = (int) $_POST['abtId'];

$type = 'wkl';

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

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

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

// Fetch existing Abteilungen ordered by order_index
$abts = db_select($mysqli, $db_tabelle_gruppen, '*', '', [], 'order_index ASC');

$indexed_abts = array_column($abts, null, 'id');

$deleteIndex = $indexed_abts[$abtInputId]['order_index'] ?? null;

if ($deleteIndex === null) {
    http_response_code(406);
    exit;
}

// Delete selected row
db_delete($mysqli, $db_tabelle_gruppen, ['id' => $abtInputId]);

// Reindex subsequent rows
for ($i = $deleteIndex + 1; $i < count($abts); $i++) {
    db_update(
        $mysqli,
        $db_tabelle_gruppen,
        ['order_index' => (int)$abts[$i]['order_index'] - 1],
        ['id'   => (int)$abts[$i]['id']]
    );
}

http_response_code(201);
