<?php

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

try {
    $mysqli->set_charset("utf8mb4");

    // 4. Fetch all rows ordered by ID so the layout hierarchy is preserved
    $sql = "SELECT * FROM `$db_tabelle_wertungstypen` ORDER BY `id` ASC";
    $result = $mysqli->query($sql);

    $exportData = [];

    while ($row = $result->fetch_assoc()) {
        $presetItem = [];

        foreach ($row as $columnName => $value) {
            if ($columnName === 'berechnung_json') {
                continue;
            }

            if ($value === null) {
                $presetItem[$columnName] = null;
            } elseif (is_numeric($value)) {
                $presetItem[$columnName] = (strpos($value, '.') !== false) ? (float)$value : (int)$value;
            } else {
                $presetItem[$columnName] = $value;
            }
        }

        $exportDataDisc[] = $presetItem;
    }

    $result->free();

    $geraete = db_select($mysqli, $db_tabelle_disziplinen, '*', '', [], 'start_index ASC');
    $programme = db_select($mysqli, $db_tabelle_kategorien, '*', '', [], 'id ASC');
    $zeitplanTypen = db_select($mysqli, $db_tabelle_zeitplan_types, '*', '', [], 'id ASC');
    $rangNote = db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['rangNote']);
    $wkName = db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['wkName']);
    $orderBestRang = db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['orderBestRang']);

    $personEinzahl = db_get_variable($mysqli, $db_tabelle_var, ['personEinzahl']);
    if ($personEinzahl === null) $personEinzahl = 'Person';
    
    $personMehrzahl = db_get_variable($mysqli, $db_tabelle_var, ['personMehrzahl']);
    if ($personMehrzahl === null) $personMehrzahl = 'Personen';

    $mysqli->close();

    $exportData = [
        'metadata' => [
            'erstellt_am' => date("d.m.Y H:i"),
            'ersteller' => $_SERVER['HTTP_HOST'],
            'erstellt_mit' => 'WKVS Auto-Export',
            'wkvs_json_version' => '1.0.0',
            'titel' => 'WKVS Preset ' . $wkName . ' (V 1.0.0)'
        ],
        'noten' => $exportDataDisc,
        'disziplinen' => $geraete,
        'zeitplan_typen' => $zeitplanTypen,
        'rang_konfiguration' => [
            'rang_note_id' => $rangNote,
            'order_best_rang' => $orderBestRang
        ],
        "leistungsklassen" => $programme,
        "bezeichnungen" =>[
            "singular" => $personEinzahl,
            "plural"=> $personMehrzahl
        ]
    ];

    $jsonOutput = json_encode($exportData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

    // 6. Force Browser File Download
    $fileName = 'WKVS-preset-config-' . date('Y-m-d_H-i') . '.json';

    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . strlen($jsonOutput));

    echo $jsonOutput;
    exit;

} catch (mysqli_sql_exception $e) {
    http_response_code(500);
    echo "Database export failed";
}