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

verify_csrf();

// Validate editId from POST
if (isset($_POST['editId'])) {
    $editId = intval($_POST['editId']);
    if ($editId === false || $editId < 1) {
        echo json_encode(['success' => false, 'message' => 'Falsche Personen ID']);
        exit;
    }
}

$editId = filter_var($editId, FILTER_VALIDATE_INT);

if ($editId === false) {
    echo json_encode(['success' => true]);
    exit;
}

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

$type = 'kr';

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

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

$is_payed = db_get_var($mysqli, "SELECT 1 FROM $db_tabelle_teilnehmende WHERE id = ? AND ((bezahltoverride = ?) OR (bezahlt = ? AND bezahltoverride = ?))", [$editId, 4, 4, 0]);

if ($is_payed != '1') {
    echo json_encode(['success'=> false, 'message'=> 'Startgebühr nicht bezahlt']);
    http_response_code(400);
    exit;
}

$isAdmin = (($_SESSION['selectedFreigabeIdKampfrichter'] ?? '') === 'A') ? true : false;

$disciplines = db_select($mysqli, $db_tabelle_disziplinen, 'id', '', [], 'start_index ASC');

$disciplines = array_column($disciplines, "id");

$requested_discipline = trim($_POST['geraet'] ?? '');

$all_disciplines = false;

if ($isAdmin && $requested_discipline === 'A') {
    $all_disciplines = true;
} else {
    $requested_discipline = (int) $requested_discipline;

    if (!in_array($requested_discipline, $disciplines)) {
        echo json_encode(['success' => false, 'message' => 'Falsche Geräte ID']);
        exit;
    }

    $discipline = $requested_discipline;
}

if ($all_disciplines) { 
    $stmt = $mysqli->prepare("SELECT t.`name`, t.`vorname`, t.`programm`, p.id as programm_id FROM $db_tabelle_teilnehmende t LEFT JOIN $db_tabelle_kategorien p ON p.programm = t.programm WHERE t.id = ?");
} else {

    $disciplines = [$discipline];


    $stmt = $mysqli->prepare("
        SELECT
            t.name,
            t.vorname,
            t.programm,
            p.id as programm_id,
            agg.abteilung,
            agg.geraeteIndex,
            agg.startIndex
        FROM $db_tabelle_teilnehmende t
        LEFT JOIN $db_tabelle_kategorien p ON p.programm = t.programm
        LEFT JOIN (
            SELECT
                ta.turnerin_id,
                GROUP_CONCAT(DISTINCT a.name SEPARATOR ', ') AS abteilung,
                GROUP_CONCAT(DISTINCT g.start_index SEPARATOR ', ') AS geraeteIndex,
                ta.turnerin_index AS startIndex
            FROM $db_tabelle_teilnehmende_gruppen ta
            INNER JOIN $db_tabelle_gruppen a
                ON a.id = ta.abteilung_id
            LEFT JOIN $db_tabelle_disziplinen g
                ON g.id = ta.geraet_id
            GROUP BY ta.turnerin_id
        ) agg ON agg.turnerin_id = t.id
        WHERE t.id = ?
    ");

}
$stmt->bind_param('i', $editId);

$stmt->execute();

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

$stmt->close();

if (!$dbresult || !is_array($dbresult) || count($dbresult) < 1) {
    echo json_encode(['success' => false, 'message' => 'Falsche Personen ID']);
    exit;
}

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

if ($all_disciplines) {
    $stmt = $mysqli->prepare("SELECT `note_bezeichnung_id`, `value`, `geraet_id`, `run_number` FROM $db_tabelle_wertungen WHERE `person_id` = ? AND `wk_id` = ?");

    $stmt->bind_param('si', $editId, $current_wk_id);
} else {
    $stmt = $mysqli->prepare("SELECT `note_bezeichnung_id`, `value`, `geraet_id`, `run_number` FROM $db_tabelle_wertungen WHERE `person_id` = ? AND `geraet_id` = ? AND `wk_id` = ?");

    $stmt->bind_param('ssi', $editId, $discipline, $current_wk_id);  
}

$stmt->execute();

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


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


$stmt->close();

$stmt = $mysqli->prepare("SELECT `id`, `default_value`, `nullstellen`, `pro_geraet`, `geraete_json`, `anzahl_laeufe_json` FROM $db_tabelle_wertungstypen");

$stmt->execute();

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

$stmt->close();

$displayIdNoteL = intval(db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['displayIdNoteL'])) ?? 0;
$displayIdNoteR = intval(db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['displayIdNoteR'])) ?? 0;

if ($displayIdNoteL !== 0 && $displayIdNoteR !== 0) {
    $displayNoten = [$displayIdNoteR => 0, $displayIdNoteL => 0];
}


$noten = [];

$row = $dbresult[0];

$programm_id = $row['programm_id'];

foreach ($disciplines as $d) {
    foreach ($notenConfig as $snC) {
        $allowedGeraete = !empty($snC['geraete_json']) ? json_decode($snC['geraete_json'], true) : [];
        $isProGeraet = ($snC['pro_geraet'] === 1);
        
        if (!$isProGeraet && !in_array($d, $allowedGeraete)) {
            continue;
        }

        // Determine number of runs for this program
        $anzRunsConfig = !empty($snC['anzahl_laeufe_json']) ? json_decode($snC['anzahl_laeufe_json'], true) : [];

        $runs = $anzRunsConfig[$d][$programm_id] ?? $anzRunsConfig[$d]["all"] ?? $anzRunsConfig['default'] ?? 1;

        if (isset($displayNoten) && array_key_exists($snC['id'], $displayNoten)) {
            $displayNoten[$snC['id']] = $runs;
        }

        for ($r = 1; $r <= $runs; $r++) {
            $value = $indexedNotenDB[$d][$snC['id']][$r] ?? $snC['default_value'] ?? 0;
            $noten[$d][$r][$snC['id']] = number_format($value, $snC['nullstellen'] ?? 2);
        }
    }
}

$countBtn = 1;

if (isset($displayNoten)) {
    $countBtn = min($displayNoten);
}


$titel = $row['vorname'].' '.$row['name'].', '.$row['programm'];

if (!$all_disciplines) {

    
    $stmt = $mysqli->prepare("
        SELECT
            t.name,
            t.vorname,
            t.programm,
            t.id,
            agg.abteilung,
            agg.geraeteIndex,
            agg.startIndex
        FROM $db_tabelle_teilnehmende t
        LEFT JOIN (
            SELECT
                ta.turnerin_id,
                GROUP_CONCAT(DISTINCT a.name SEPARATOR ', ') AS abteilung,
                GROUP_CONCAT(DISTINCT g.start_index SEPARATOR ', ') AS geraeteIndex,
                ta.turnerin_index AS startIndex
            FROM $db_tabelle_teilnehmende_gruppen ta
            INNER JOIN $db_tabelle_gruppen a
                ON a.id = ta.abteilung_id
            LEFT JOIN $db_tabelle_disziplinen g
                ON g.id = ta.geraet_id
            GROUP BY ta.turnerin_id
        ) agg ON agg.turnerin_id = t.id
        WHERE agg.abteilung = ? AND agg.geraeteIndex = ?
        ORDER BY t.id DESC
    ");


    $bezahlt = 4;
    $bezahltoverride = 4;

    $stmt->bind_param('ss', $row['abteilung'], $row['geraeteIndex']);


    $stmt->execute();


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

    $stmt->close();

    if (!$entries || !is_array($entries) || count($entries) < 1) {
        echo json_encode(['success' => false, 'message' => 'No DB Result for next Turnerin']);
        exit;
    }


    $maxstartindex = count($entries);

    if ($maxstartindex < 1) {
        $maxstartindex = 1;
    }

    $csti = (int)$row['startIndex'];
    $nsti = $csti + 1;

    if ($nsti > $maxstartindex){
        $nsti -= $maxstartindex;
    }

    $rohstartindex = intval($row['startIndex']);
    $varstartgeraet = intval($row['geraeteIndex']);

    $aktsubabt = $_SESSION['currentsubabt'];

    foreach ($disciplines as $index => $sdiscipline) {
        if (isset($sdiscipline) && $sdiscipline === $discipline) {
            $indexuser = $index;
            break;
        }
    }



    $calculedstartindex = $rohstartindex - $indexuser;

    $calculedstartindex = $calculedstartindex >= 1 ? $calculedstartindex : $calculedstartindex + $maxstartindex;


    $nrow = null;

    if ($calculedstartindex !== count($entries)){
        $nrow = null;

        foreach ($entries as $entry) {
            if ($entry['startIndex'] == $nsti) {
                $nrow = $entry;
                break;
            }
        }
    }

    if ($nrow) {
        $nturnerin = [
            'name' => $nrow['vorname'].' '.$nrow['name'].', '.$nrow['programm'],
            'id'   => $nrow['id']
        ];
    } else {
        $nturnerin = [
            'name' => '--- nächste Gruppe ---',
            'id'   => 0
        ];
    }

}

if ($isAdmin) {
    echo json_encode([
        'success' => true,
        'id'      => $editId,
        'programm_id' => $programm_id,
        'titel'   => $titel,
        'noten'  => $noten,
        'countBtn' => $countBtn
    ]);
} else {
    echo json_encode([
        'success' => true,
        'id'      => $editId,
        'programm_id' => $programm_id,
        'titel'   => $titel,
        'noten'  => $noten,
        'nturnerin' => $nturnerin,
        'countBtn' => $countBtn
    ]);
}


