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

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

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

ini_wkvs_session();

check_user_permission('kampfrichter');

verify_csrf();

// ---------- Get and sanitize input ----------
$id = intval($_POST['personId'] ?? 0);
$initNoteRun = intval($_POST['run'] ?? 0);
$geraetId = intval($_POST['geraetId'] ?? 0);
$dataType = intval($_POST['dataType'] ?? 0);
$jahr = isset($_POST['jahr']) ? preg_replace('/[^0-9]/', '', $_POST['jahr']) : '';
$anfrageType = $_POST['type'] ?? '';

$allowedTypes = ["neu", "start", "result"];

if (!in_array($anfrageType, $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => "Operation nicht gestattet."]);
    exit; 
}

if ($anfrageType !== "start" && ($id < 1 || intval($jahr) < 1)) {
    echo json_encode(['success' => false, 'message' => 'Personen ID ist nicht valide.']);
    exit;
}

if ($geraetId < 1) {
    echo json_encode(['success' => false, 'message' => 'Invalid discipline']);
    exit;
}

$type = 'kr';

$data = require $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-functions.php';
require $baseDir . '/../scripts/db/db-tables.php';

$stmt = $mysqli->prepare("SELECT `name` FROM $db_tabelle_disziplinen WHERE `id` = ? LIMIT 1");
$stmt->bind_param("s", $geraetId);

if (!$stmt->execute()) {
    http_response_code(500);
    exit;
}

$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid discipline']);
    exit;
}

$geraetData = $result->fetch_assoc();
$geraetName  = $geraetData['name'];

$stmt->close();

$folder = realpath($baseDir . '/externe-geraete/json');

if ($folder === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Could not find displays folder.'
    ]);
    exit;
}

$filename = 'display-id-' . $geraetId . '.json';
$filepath = $folder . '/' . $filename;

if (!is_writable($folder)) {
    echo json_encode(['success' => false, 'message' => 'Folder not writable']);
    exit;
}

$jsonString = file_get_contents($filepath);

// decode JSON, fallback to empty array if invalid
$oldjson = json_decode($jsonString, true) ?? [];

switch ($anfrageType) {
    case "neu":
        $stmt = $mysqli->prepare("SELECT `id`, `name`, `vorname`, `programm`, `verein` FROM `$db_tabelle_teilnehmende` WHERE id = ? LIMIT 1");
        $stmt->bind_param("i", $id);
        $stmt->execute();

        $result = $stmt->get_result();
        $rows = $result->fetch_all(MYSQLI_ASSOC);

        if (!$rows || !is_array($rows) || count($rows) !== 1) {
            echo json_encode(['success' => false, 'message' => 'Row fetch failed']);
            exit;
        }

        $row = $rows[0];


        $data = ["noteLinks" => '',
                "noteRechts" => '',
                "id" => $id,
                "name" => $row['name'],
                "vorname" => $row['vorname'],
                "programm" => $row['programm'],
                "verein" => $row['verein'],
                "start" => false
                ];
        
        $arrayData = $data;
        break;
    case "start":
        if (!array_key_exists("id", $oldjson) || intval($oldjson["id"]) !== $id || !array_key_exists("start", $oldjson)) {
            echo json_encode(['success' => false, 'message' => 'Person nicht auf Display!']);
            exit;
        }
        
        $oldjson["start"] = (bool) $dataType;

        $arrayData = $oldjson;
        break;
    case "result":
        // 1. Get IDs and filter out empty values
        $noteLinksId  = db_get_variable($mysqli, $db_tabelle_var, ['displayIdNoteL']);
        $noteRechtsId = db_get_variable($mysqli, $db_tabelle_var, ['displayIdNoteR']);

        $programm_id = db_get_var($mysqli, "SELECT p.`id` FROM $db_tabelle_teilnehmende t INNER JOIN $db_tabelle_kategorien p ON p.`programm` = t.`programm` WHERE t.`id` = ?", [$id]) ?? null;

        $display_cache = require $baseDir . '/../scripts/cache/display-dependencies.php';

        $this_display_cache = $display_cache[$programm_id][$geraetId][$initNoteRun];

        $sql_where_values = $this_display_cache['values'];

        $sql_where_string = $this_display_cache['SQL'];

        $intersect_noten = $this_display_cache['intersect_noten'];

        $rankLiveArray = [];

        $current_wk_id = (int) db_get_variable($mysqli, $db_tabelle_var, ['current_wk_id']) ?: 0;

        if (!empty($sql_where_values) && $sql_where_string !== '') {

            $notenDB = db_select($mysqli, $db_tabelle_wertungen, '`value`, `note_bezeichnung_id`, `geraet_id`, `run_number`', "`person_id` = ? AND `wk_id` = ? AND ($sql_where_string)", array_merge([$id, $current_wk_id], $sql_where_values));

            $indexedNotenDB = [];

            foreach ($notenDB as $sn) {
                $indexedNotenDB[$sn['geraet_id']][$sn['note_bezeichnung_id']][$sn['run_number']] = $sn;
            }
        }

        $mysqli->begin_transaction();

        
        try {
            $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_wertungen (`person_id`, `note_bezeichnung_id`, `wk_id`, `geraet_id`, `run_number`, `is_public`, `public_value`) VALUES (?, ?, ?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE `public_value` = VALUES(`public_value`), `is_public` = 1");

            foreach ($intersect_noten as $s_note) {
                $n_id = $s_note['n_id'];
                $g_id = $s_note['g_id'];
                $run = $s_note['r'];

                $value = $indexedNotenDB[$g_id][$n_id][$run]['value'] ?? $notenConfig['default_values'][$n_id] ?? 0;
                $rankLiveArray[$g_id][$run][$n_id] = number_format($value, $notenConfig['nullstellen'][$n_id] ?? 2);

                $stmt->bind_param("iiiiid", $id, $n_id, $current_wk_id, $g_id, $run, $value);

                $stmt->execute();
            }

            $mysqli->commit();
            $stmt->close();
        } catch (Exception $e) {
            $mysqli->rollback();
            echo json_encode(['success' => false, 'message' => 'DB Transaction failed Error: ' . $e->getMessage()]);
            exit;
        }

        

       
        // Create an array of IDs that actually exist
        $validIds = array_filter([$noteLinksId, $noteRechtsId]);

        $noten = [];
        $notenConfig = [];

        if (!empty($validIds)) {
            // 2. Fetch Noten (Only if we have IDs to look for)
            $placeholders = implode(',', array_fill(0, count($validIds), '?'));
            
            $sqlNoten = "SELECT `value`, `note_bezeichnung_id` FROM $db_tabelle_wertungen 
                        WHERE person_id = ? AND `wk_id` = ? AND `geraet_id` = ? AND run_number = ?
                        AND `note_bezeichnung_id` IN ($placeholders)";
            
            $stmt = $mysqli->prepare($sqlNoten);
            // Combine standard params with our dynamic ID list
            $params = array_merge([$id, $current_wk_id, $geraetId, $initNoteRun], $validIds);
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $notenDB = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $noten = array_column($notenDB, 'value', 'note_bezeichnung_id');
            $stmt->close();

            // 3. Fetch Config
            $sqlConfig = "SELECT `id`, `default_value`, `nullstellen`, `display_string` 
                        FROM $db_tabelle_wertungstypen WHERE `id` IN ($placeholders)";
            
            $stmt = $mysqli->prepare($sqlConfig);
            $typesConfig = str_repeat('s', count($validIds));
            $stmt->bind_param($typesConfig, ...$validIds);
            $stmt->execute();
            $notenConfigDB = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $notenConfig = array_column($notenConfigDB, null, 'id');
            $stmt->close();
        }

        // 4. Helper function to safely format the output without crashing
        $formatNote = function($id) use ($noten, $notenConfig) {
            if (!$id || !isset($notenConfig[$id])) {
                return ""; // Return empty string if ID is not set or not found in DB
            }
            
            $conf = $notenConfig[$id];
            $val  = $noten[$id] ?? $conf['default_value'] ?? 0;
            $prec = $conf['nullstellen'] ?? 2;

            $display_schema = $conf['display_string'] ?? '${note}';

            $formatted_note = number_format((float)$val, (int)$prec, '.', '');

            $result = str_ireplace('${note}', $formatted_note, $display_schema);

            if ($result === $display_schema) {
                return $formatted_note;
            }

            return $result;
        };

        // 5. Assign to JSON
        $oldjson["noteLinks"]  = $formatNote($noteLinksId);
        $oldjson["noteRechts"] = $formatNote($noteRechtsId);

        $arrayData = $oldjson;
        
        break;
    default: 
        http_response_code(400);
        exit;
}

$jsonData = json_encode($arrayData);

// Write file
if (file_put_contents($filepath, $jsonData) === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to write JSON file'
    ]);
    exit;
}

if ($anfrageType === "result") {
    echo json_encode([
        'success' => true,
        'message' => 'JSON updated successfully for ' . $geraetName,
        'data' => $arrayData,
        'rankLive' => $rankLiveArray,
        'nameGeraet' => strtolower($geraetName)
    ]);
} else {
    // ---------- Return JSON ----------
    echo json_encode([
        'success' => true,
        'message' => 'JSON updated successfully for ' . $geraetName,
        'data' => $arrayData,
        'nameGeraet' => strtolower($geraetName)
    ]);
}
exit;