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

$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' => 'RankLive Overview',
    'rankLive-geraet' => 'RankLive einzelnes Gerät', 
    'kampfrichter-admin' => 'Kampfrichter Admin (alle Geräte)', 
    'kampfrichter-geraet' => 'Kampfrichter einzelnes Gerät' //, 'rangliste' => 'all'
];

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

$json = db_get_var($mysqli, "SELECT `json` FROM $db_tabelle_tabellen_konfiguration WHERE `type_slug` = ?", [$slug]) ?: '';

try {
    $json_array = json_decode($json, true) ?? [];
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error parsing JSON']);
    exit;
}

$wk_name = db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['wkName']);

$exportData = [
    'metadata' => [
        'erstellt_am' => date("d.m.Y H:i"),
        'ersteller' => $_SERVER['HTTP_HOST'],
        'erstellt_mit' => 'WKVS Auto-Export',
        'wkvs_json_table_version' => '1.0.0',
        'titel' => 'WKVS Table für ' . $allowed_slugs[$slug] . ' ' . $wk_name . ' (V 1.0.0)'
    ],
    'data' => $json_array,
    'type' => $slug
];

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

// 6. Force Browser File Download
$fileName = 'WKVS-table-config-' . date('Y-m-d_H-i') . '-' . $slug . '.conf.wkvs';

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;