<?php
header('Content-Type: application/json');

ini_set('display_errors', 1);

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

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

ini_wkvs_session();

check_user_permission('wk_leitung');

verify_csrf();

$type = 'wkl';

$data = include $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($data['success'] === false){
	echo json_encode(['success' => false, 'message' => $data['message']]);
    exit; 
}

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

$json = $_POST['json'] ?? '';

$slug = $_POST['slug'] ?? '';

$allowed_slugs = ['rankLive-overview' => 'all', 'rankLive-geraet' => 'geraet', 'kampfrichter-admin' => 'all', 'kampfrichter-geraet' => 'geraet', 'rangliste' => 'all'];

if (!array_key_exists($slug, $allowed_slugs)){
    echo json_encode(['success' => false, 'message' => 'Invalid Type']);
    exit;
}

if (!$json || $json === ''){
    echo json_encode(['success' => false, 'message' => 'No input']);
    exit;
}

$array = json_decode($json, true) ?? [];

$body = $array['body'];

$all_noten = [];

function extractNotenData(array $array): array {
    $result = [];

    // Check if the current array is a 'notenData' object itself
    if (isset($array['type']) && $array['type'] === 'notenData') {
        return [$array];
    }

    // Otherwise, loop through the elements to go deeper
    foreach ($array as $value) {
        if (is_array($value)) {
            // Recursively extract from the sub-array and merge into our result list
            $result = array_merge($result, extractNotenData($value));
        }
    }

    return $result;
}

function extractNotenGeraetData(array $array): array {
    $result = [];

    // Check if the current array is a 'notenData' object itself
    if (isset($array['type']) && $array['type'] === 'notenGeraetData') {
        return [$array];
    }

    // Otherwise, loop through the elements to go deeper
    foreach ($array as $value) {
        if (is_array($value)) {
            // Recursively extract from the sub-array and merge into our result list
            $result = array_merge($result, extractNotenGeraetData($value));
        }
    }

    return $result;
}

$all_noten = ($allowed_slugs[$slug] === 'all') ? extractNotenData($body) : extractNotenGeraetData($body);

$all_noten_export = [];

foreach ($all_noten as $single_note) {
    $all_noten_export[] = [
        'g_id' => $single_note['geraet-id'] ?? 'A',
        'n_id' => $single_note['field-type-id'],
        'r' => $single_note['run']
    ];
}

function unique_matrix($matrix) {
    $matrixAux = $matrix;

    foreach($matrix as $key => $subMatrix) {
        unset($matrixAux[$key]);

        foreach($matrixAux as $subMatrixAux) {
            if($subMatrix === $subMatrixAux) {
                unset($matrix[$key]);
            }
        }
    }

    return $matrix;
}

$all_noten_json = json_encode(unique_matrix($all_noten_export) ?? []) ?? '';

$user_id = (int) $_SESSION['user_id_wk_leitung'] ?? 0;

$stmt = $mysqli->prepare("INSERT INTO `$db_tabelle_tabellen_konfiguration` (`json`, `all_noten_json`, `type_slug`, `created_by`, `updated_by`) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE `json` = VALUES(`json`), `all_noten_json` = VAlUES(`all_noten_json`), `updated_by` = VALUES(`updated_by`)");

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Critical DB ERROR']);
    exit;
}

$stmt->bind_param("sssii", $json, $all_noten_json, $slug, $user_id, $user_id);
$success = $stmt->execute();
$stmt->close();

if (!$success) {
    echo json_encode(['success' => false, 'message' => 'Insert failed']);
    exit;
}

if (str_contains($slug, 'rankLive')) {
    require_once $baseDir . '/../scripts/cache/cache-creators/regenerate-display-dependencies-cache.php';
    generateIntersectCache($mysqli, $baseDir);
}

// Return JSON
echo json_encode([
    'success' => true,
    'message' => 'gespeichert'
]);
exit;