<?php

$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['abt']) || !ctype_digit($_POST['abt']) || !isset($_POST['newOrderIndex'])) {
    http_response_code(406);
    exit;
}

$abtInput = (int) $_POST['abt'];
$newOrderIndex_input = (int) $_POST['newOrderIndex'];

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

$allAbts = db_select($mysqli, $db_tabelle_gruppen, 'id', 'id != ? ORDER BY order_index ASC', [$abtInput]);
$ids = array_column($allAbts, 'id');

$targetIndex = max(0, $newOrderIndex_input - 1);

array_splice($ids, $targetIndex, 0, $abtInput);

$mysqli->begin_transaction();

$one_based_indexes = [];

try {
    foreach ($ids as $zeroBasedIndex => $abtId) {
        $newIndex = $zeroBasedIndex + 1;
        db_update(
            $mysqli,
            $db_tabelle_gruppen,
            ['order_index' => $newIndex],
            ['id' => $abtId]
        );
        $one_based_indexes[$abtId] = $newIndex;
    }

    $mysqli->commit();
} catch (Exception $e) {
    $mysqli->rollback();
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    exit;
}

http_response_code(200);
echo json_encode(['success' => true, 'newIndexes' => $one_based_indexes]);
exit;