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

$anz_abt = (int) $_POST['anz_abt'];

$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
$abts = db_select($mysqli, $db_tabelle_gruppen, '*');

// Delete excess Abteilungen
foreach ($abts as $dbabt) {
    if ((int) $dbabt['order_index'] > $anz_abt) {
        db_delete($mysqli, $db_tabelle_gruppen, ['id' => $dbabt['id']]);
    }
}

// Build lookup of existing names
$existing = array_map('intval', array_column($abts, 'order_index'));

// Insert missing Abteilungen
$stmt = $mysqli->prepare("INSERT INTO $db_tabelle_gruppen (`name`, `order_index`) VALUES (?, ?)");

for ($i = 1; $i <= $anz_abt; $i++) {
    if (!in_array($i, $existing, true)) {
        $var_name = "Abteilung $i";
        $stmt->bind_param('si', $var_name, $i);
        $stmt->execute();
    }
}

$stmt->close();

http_response_code(201);
