<?php

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

if (!isset($_FILES['configFile']) || $_FILES['configFile']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode([
        'success' => false,
        'message' => 'Keine Config-Datei ausgewählt'
    ]);
    exit;
}

$tableJSONVersion = '1.0.0';

$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';
require $baseDir . '/../scripts/string-calculator/string-calculator-functions.php';

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

$allowed_slugs = ['rankLive-overview' => 'all', 'rankLive-geraet' => 'geraet', 'kampfrichter-admin' => 'Kampfrichter Admin (alle Geräte)', 'kampfrichter-geraet' => 'geraet', 'rangliste' => 'all'];

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


$tmpPath = $_FILES['configFile']['tmp_name'];
$originalName = $_FILES['configFile']['name'];
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

$allowedExt = ['json', 'wkvs'];
if (!in_array($extension, $allowedExt, true)) {
    echo json_encode(['success' => false, 'message' => 'Falsches Format (Endung)']);
    http_response_code(422);
    exit;
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($tmpPath);
$allowedMime = ['application/json'];

if (!in_array($mimeType, $allowedMime, true)) {
    echo json_encode(['success' => false, 'message' => 'Dateiinhalt ist kein gültiges JSON']);
    http_response_code(422);
    exit;
}

$JSONcontent = file_get_contents($tmpPath);

$content = json_decode($JSONcontent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die("Invalid JSON layout.");
}

if (!isset($content['metadata']['wkvs_json_table_version']) || $content['metadata']['wkvs_json_table_version'] !== $tableJSONVersion) {
    echo json_encode(['success' => false, 'message' => 'Inkompatible Datei-Version. (V ' . $tableJSONVersion . ' benötigt'. (isset($content['metadata']['wkvs_json_version']) ?  ", benutzte Datei-Version: V " . $content['metadata']['wkvs_json_version'] : '') . ')' ]);
    unlink($destination);
    http_response_code(422);
    exit;
}

if (!isset($content['data']) || !is_array($content['data'])) {
    echo json_encode(['success' => false, 'message' => 'Ungültige JSON-Struktur']);
    unlink($destination);
    http_response_code(422);
    exit;
}

$body = $content['data']['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;
}

$json = json_encode($content['data']);

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