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

verify_csrf();

$personen_ids_json = $_POST['personen_ids'] ?? '';

$personen_ids = json_decode($personen_ids_json) ?? [];

$personen_ids = !is_array($personen_ids) ? array(intval($personen_ids)) : array_map('intval', $personen_ids);

if (count($personen_ids) < 1) {
    echo json_encode(['success' => false, 'message' => "Keine Personen angegeben"]);
    http_response_code(400);
    exit;
}

$neu_kat_id = (int) $_POST['kat_id'] ?? 0;

if ($neu_kat_id < 1) {
    echo json_encode(['success' => false, 'message' => "Keine neue Kategorie angegeben"]);
    http_response_code(400);
    exit;
}

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

$type = 'tr';

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

if ($dbconnection['success'] !== true) {
    echo 'Critical DB Error.';
    exit;
}

$all_kats = db_select($mysqli, $db_tabelle_kategorien, "`id`, `programm`, `preis`");

$all_kats_id_indexed = array_column($all_kats, null, 'id');

$preise_kats = array_column($all_kats, 'preis', 'programm');

if (!isset($all_kats_id_indexed[$neu_kat_id])) {
    echo json_encode(['success' => false, 'message' => "Nicht valide Kategorie"]);
    http_response_code(400);
    exit;
}

$new_kat_name = $all_kats_id_indexed[$neu_kat_id]['programm'];
$new_kat_preis = $all_kats_id_indexed[$neu_kat_id]['preis'];
$vereine_plus_array = [];

function get_kat_price_diff(array $old_data, string $new_kat): array {
    global $preise_kats;
    global $vereine_plus_array;

    $return_array = [];

    $old_kat = $old_data['programm'] ?? '';
    $verein = $old_data['verein'] ?? '';
    $bezahlt = (int) ($old_data['bezahlt'] ?? 1);

    var_dump(!isset($preise_kats[$new_kat]), !in_array($bezahlt, [2, 4], true), $old_kat === $new_kat, $old_kat === '', $old_kat, $new_kat);

    if ($old_kat === '' || $old_kat === $new_kat || !in_array($bezahlt, [2, 4], true) || !isset($preise_kats[$new_kat])) {
        return $return_array;
    }

    $betrag_bezahlt = (float) ($old_data['betrag_bezahlt'] ?? 0.00);
    $new_kat_preis  = (float) $preise_kats[$new_kat];

    if ($new_kat_preis > $betrag_bezahlt) {
        $return_array['bezahlt'] = ($betrag_bezahlt === 0.00) ? 1 : 2;
    } elseif ($new_kat_preis < $betrag_bezahlt) {
        $return_array['bezahlt']    = 4;
        $return_array['betrag_bezahlt'] = $betrag_bezahlt - $new_kat_preis;
        $vereine_plus_array[$verein] = ((float) ($vereine_plus_array[$verein] ?? 0.00)) + $betrag_bezahlt - $new_kat_preis;
    } else {
        $return_array['bezahlt'] = 4;
    }

    return $return_array;
}

function update_verein_balances(array $vereine_plus_array_funct) {
    global $mysqli;
    global $db_tabelle_vereine;

    if (empty($vereine_plus_array_funct)) {
        return;
    }

    $stmt = $mysqli->prepare("UPDATE $db_tabelle_vereine SET `konto` = `konto` + ? WHERE `verein` = ?");
    
    if ($stmt) {
        foreach ($vereine_plus_array_funct as $verein => $betrag) {
            if ($betrag <= 0.00) {
                continue;
            }

            $stmt->bind_param("ds", $betrag, $verein);
            $stmt->execute();
        }
        $stmt->close();
    }
}

function remove_from_basket(array $ids_array = []) : bool {
    global $mysqli;
    global $db_tabelle_warenkorb_startgebueren;

    if (empty($ids_array)) return true;

    $tplaceholders = implode(", ", array_fill(0, count($ids_array), "?"));

    $stmt = $mysqli->prepare("DELETE FROM $db_tabelle_warenkorb_startgebueren WHERE `item_id` IN ($tplaceholders)");
    $stmt->bind_param(str_repeat('i', count($ids_array)), ...$ids_array);
    $ret = $stmt->execute();
    $stmt->close();

    return $ret;
}

// 4. Data Processing & Transaction Block
$placeholders = implode(", ", array_fill(0, count($personen_ids), "?"));
$entries = db_select($mysqli, $db_tabelle_teilnehmende, "`id`, `programm`, `bezahlt`, `betrag_bezahlt`, `verein`", "`id` IN ($placeholders)", $personen_ids);

$mysqli->begin_transaction();

try {

    $stmtbez  = $mysqli->prepare("UPDATE $db_tabelle_teilnehmende SET `bezahlt` = ?, `programm` = ? WHERE `id` = ?");
    $stmtbezbet = $mysqli->prepare("UPDATE $db_tabelle_teilnehmende SET `bezahlt` = ?, `programm` = ?, `betrag_bezahlt` = ? WHERE `id` = ?");
    $stmtnorm = $mysqli->prepare("UPDATE $db_tabelle_teilnehmende SET `programm` = ? WHERE `id` = ?");
    
    $status_update_bez = null;
    $current_id_bez    = null;
    $stmtbez->bind_param("isi", $status_update_bez, $new_kat_name, $current_id_bez);

    $status_update_bet_bez = null;
    $current_id_bet_bez    = null;
    $betrag_bezahlt    = null;
    $stmtbezbet->bind_param("isdi", $status_update_bet_bez, $new_kat_name, $betrag_bezahlt, $current_id_bet_bez);

    $current_id_norm   = null;
    $stmtnorm->bind_param("si", $new_kat_name, $current_id_norm);

    foreach ($entries as $s_entry) {
        $res = get_kat_price_diff($s_entry, $new_kat_name);
        
        if (count($res) < 1) {
            $current_id_norm = $s_entry['id'];
            $stmtnorm->execute();
        } elseif (isset($res['betrag_bezahlt'])){
            $status_update_bet_bez = $res['bezahlt'];
            $current_id_bet_bez    = $s_entry['id'];
            $betrag_bezahlt    = $res['betrag_bezahlt'];
            $stmtbezbet->execute();
        } else {
            $status_update_bez = $res['bezahlt'];
            $current_id_bez    = $s_entry['id'];
            $stmtbez->execute();
        }
    }
    
    $stmtnorm->close();
    $stmtbez->close();

    remove_from_basket($personen_ids);

    var_dump($vereine_plus_array);

    update_verein_balances($vereine_plus_array);

    $mysqli->commit();

    // Fix #1: Added explicit echo for output tracking
    http_response_code(200);
    echo json_encode(['success' => true, 'message' => "Kategorie erfolgreich geändert"]);
    exit;

} catch (Exception $e) {
    // Rollback instantly if anything fails
    $mysqli->rollback();

    // Fix #1 & #3: Proper error output formatting
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => "Datenbankfehler"]);
    exit;
}