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

$allowed_operations = ['overrite', 'add'];

if (!isset($_POST['operation']) || !in_array($_POST['operation'], $allowed_operations, true)) {
    http_response_code(400);
    echo 'Invalid operation.';
    exit;
}

$operation = $_POST['operation'];

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

$allGeraete = db_select($mysqli, $db_tabelle_disziplinen, "id, name, start_index", "", [], "start_index ASC");
$allAbt = db_select($mysqli, $db_tabelle_gruppen, "name, id, order_index", "", [], "order_index ASC");

$indexded_order_index_abt = array_column($allAbt, null, 'order_index');

$maxTurnerinnenGruppe = 8;

$allTurnerinnen = db_select($mysqli, $db_tabelle_teilnehmende, "id, programm, verein, name" , "", [], "programm ASC");

$grouped = [];

foreach ($allTurnerinnen as $t) {
    $grouped[strtolower($t['programm'])][$t['verein']][] = $t;
}

function getMinKey(array $array): string|int {
    return array_search(min($array), $array, true);
}

function arrayRiegeneiteilung($allturnerinnen, $maxTurnerinnenGruppe, $allGeraete) {
    $indabt = 1;
    $arrayAutoRiegeneinteilung = [];
    foreach ($allturnerinnen as $prog => $vereine) {
        // ABTEILUNG BERECHNEN
        $countturterinnenprog = 0;
        foreach ($vereine as $verein => $turnerinnen) {
            foreach ($turnerinnen as $ind => $turnerin) {
                $countturterinnenprog++;
                $abt = intdiv($countturterinnenprog, $maxTurnerinnenGruppe * count($allGeraete)) + $indabt;
                $allturnerinnen[$prog][$verein][$ind]['abt'] = $abt;
                $arrayAbt[$abt][$verein][] = $turnerin;
            }
            
        }

        $indabt += intdiv($countturterinnenprog - 1, $maxTurnerinnenGruppe * count($allGeraete)) + 1;
    }

    foreach ($arrayAbt as $abt => $vereine) {

        // AUSGLEICHEN DER GRUPPEN
        $arrayAbt = [];
        $arrayGruppen = [];
        foreach ($allGeraete as $geraet) {
            $arrayGruppen[$geraet['id']] = 0;
        }

        $turnerinnenCount = 0;

        foreach ($vereine as $verein => $turnerinnen) {
            $turnerinnenCount += count($turnerinnen);
        }

        foreach ($vereine as $verein => $turnerinnen) {

            if (count($turnerinnen) > $maxTurnerinnenGruppe || count($turnerinnen) > $turnerinnenCount / count($allGeraete)) {
                
                if (count($turnerinnen) > $turnerinnenCount / count($allGeraete)) {
                    $maxTurnerinnenGruppeTemp = ceil($turnerinnenCount / count($allGeraete));
                } else {
                    $maxTurnerinnenGruppeTemp = $maxTurnerinnenGruppe;
                }
                // AUFTEILEN IN MEHRERE GRUPPEN
                $chunks = array_chunk($turnerinnen, $maxTurnerinnenGruppeTemp);
                foreach ($chunks as $chunk) {

                    $minKey = getMinKey($arrayGruppen);

                    $arrayGruppen[$minKey] += count($chunk);

                    foreach ($chunk as $ind =>$turnerin) {
                        $arrayAutoRiegeneinteilung[$abt][$minKey][] = $turnerin;
                    }
                }
                continue;
            }

            $minKey = getMinKey($arrayGruppen);

            $arrayGruppen[$minKey] += count($turnerinnen);

            foreach ($turnerinnen as $ind =>$turnerin) {
                $arrayAutoRiegeneinteilung[$abt][$minKey][] = $turnerin;
            }
            
        }
    }

    
    foreach ($arrayAutoRiegeneinteilung as $indAbt => $abt) {
        foreach ($abt as $indGeraet => $geraet) {
            foreach ($geraet as $indTurnerin => $turnerin) {
                $arrayAutoRiegeneinteilung[$indAbt][$indGeraet][$indTurnerin]['turnerin_index'] = $indTurnerin + 1;
            }
        }
    }
    

    return $arrayAutoRiegeneinteilung;
}
    
$arrayAutoRiegeneinteilung = arrayRiegeneiteilung($grouped, $maxTurnerinnenGruppe, $allGeraete);

if ($operation === 'overrite') {
    $stmt = $mysqli->prepare("DELETE FROM $db_tabelle_gruppen");
    $stmt->execute();
    $stmt->close();
}

$stmt = $mysqli->prepare("DELETE FROM $db_tabelle_teilnehmende_gruppen");
$stmt->execute();
$stmt->close();



foreach ($arrayAutoRiegeneinteilung as $indAbt => $abt) {

    if ($operation === 'overrite' || !isset($indexded_order_index_abt[$indAbt])) {
        $var_name = "Abteilung $indAbt";

        $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_gruppen (`name`, `order_index`) VALUES (?, ?)");
        $stmt->bind_param("si", $var_name, $indAbt);
        $stmt->execute();
        $idAbt = $stmt->insert_id;
        $stmt->close();
    } else {
        $idAbt = $indexded_order_index_abt[$indAbt]['id'];
    }

    foreach ($abt as $indGeraet => $geraet) {
        foreach ($geraet as $indTurnerin => $turnerin) {
            $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_teilnehmende_gruppen (turnerin_id, abteilung_id, geraet_id, turnerin_index) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $turnerin['id'], $idAbt, $indGeraet, $turnerin['turnerin_index']);
            $stmt->execute();
            $stmt->close();
        }
    }
}

return http_response_code(200);