<?php

ini_set("display_errors", 1);
ini_set("display_startup_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();

$type = 'wkl';

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

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

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

$turnerin_ids = $_POST['turnerin_ids'] ?? [];
$neu_abteilung_id = intval($_POST['neuAbteilungId'] ?? 0);
$neu_geraet_id = intval($_POST['neuGeraetId'] ?? 0);
$alt_abteilung_id = intval($_POST['altAbteilungId'] ?? 0);
$alt_geraet_id = intval($_POST['altGeraetId'] ?? 0);
$neu_first_index = intval($_POST['neuFirstIndex'] ?? 0);

// Resolve Abteilung ID
if ($neu_abteilung_id < 1) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Keine Abteilungs ID angegeben.']);
    exit;
} else {
    $stmt = $mysqli->prepare("SELECT 1 FROM $db_tabelle_gruppen WHERE id = ?");
    $stmt->bind_param("i", $neu_abteilung_id);
    $stmt->execute();
    if (!$stmt->get_result()->fetch_assoc()) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalide Abteilungs ID angegeben.']);
        exit;
    }
    $stmt->close();
}

// Resolve Gerät ID
if ($neu_geraet_id < 1) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Keine neue Geräte ID angegeben.']);
    exit;
} else {
    $stmt = $mysqli->prepare("SELECT 1 FROM $db_tabelle_disziplinen WHERE id = ?");
    $stmt->bind_param("i", $neu_geraet_id);
    $stmt->execute();
    if (!$stmt->get_result()->fetch_assoc()) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalide Geräte ID angegeben.']);
        exit;
    }
    $stmt->close();
}

function arrayshift($v) {
    return intval($v) + 1;
}

$array_ids = array_map('intval', $turnerin_ids);

$mysqli->begin_transaction();

try {
    // 1. Move/Upsert the specific gymnasts into the new group
    $stmt = $mysqli->prepare("
        INSERT INTO $db_tabelle_teilnehmende_gruppen (turnerin_id, abteilung_id, geraet_id)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE abteilung_id = VALUES(abteilung_id), geraet_id = VALUES(geraet_id)
    ");

    foreach ($array_ids as $id) {
        $stmt->bind_param("iii", $id, $neu_abteilung_id, $neu_geraet_id);
        $stmt->execute();
    }
    $stmt->close();

    // 2. Reorder the old group to fill any gaps left by the moved gymnasts

    if ($alt_abteilung_id !== 0 && $alt_geraet_id !== 0 && ($alt_abteilung_id !== $neu_abteilung_id || $alt_geraet_id !== $neu_geraet_id)) {
        $old_group_rows_zero_based = db_select($mysqli, $db_tabelle_teilnehmende_gruppen, "turnerin_id", 
            "abteilung_id = ? AND geraet_id = ?", [$alt_abteilung_id, $alt_geraet_id], "turnerin_index ASC");
        
        $updOld = $mysqli->prepare("UPDATE $db_tabelle_teilnehmende_gruppen SET `turnerin_index` = ? WHERE `turnerin_id` = ?");

        $old_group_rows = [];

        foreach ($old_group_rows_zero_based as $i => $row) {
            $new_idx = $i + 1; // Start indexing at 1
            $updOld->bind_param("ii", $new_idx, $row['turnerin_id']);
            $updOld->execute();
            $old_group_rows[$row['turnerin_id']] = $new_idx;
        }
        $updOld->close();
    }

    // 3. Fetch all gymnasts now in this group to determine final order
    // Order by start_index so we preserve the existing relative order of gymnasts already there
    $rows = db_select(
        $mysqli,
        $db_tabelle_teilnehmende_gruppen,
        "turnerin_id",
        "abteilung_id = ? AND geraet_id = ?",
        [$neu_abteilung_id, $neu_geraet_id],
        "turnerin_index ASC"
    );

    $current_ids = array_column($rows, 'turnerin_id');

    // 4. Reconstruct the order: [Remaining ones before index] -> [Prioritized] -> [Remaining ones after index]
    $remaining_ids = array_values(array_diff($current_ids, $array_ids));

    $final_order_zero_based = [];
    // Adjust index to 0-based for array manipulation
    $target_pos = max(0, $neu_first_index - 1);

    // Splice the prioritized IDs into the remaining list at the target position
    array_splice($remaining_ids, $target_pos, 0, $array_ids);
    $final_order_zero_based = $remaining_ids;

    $final_order = [];

    // 5. Update the database with the new continuous indices
    $updStmt = $mysqli->prepare("UPDATE $db_tabelle_teilnehmende_gruppen SET `turnerin_index` = ? WHERE `turnerin_id` = ?");

    foreach ($final_order_zero_based as $array_index => $t_id) {
        $actual_index = $array_index + 1;
        $updStmt->bind_param("ii", $actual_index, $t_id);
        $updStmt->execute();
        $final_order[$t_id] = $actual_index;
    }
    $updStmt->close();

    $mysqli->commit();
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'old_new_start_indexes' => $old_group_rows ?? null,
        'new_new_start_indexes' => $final_order
    ]);

} catch (Throwable $e) {
    $mysqli->rollback();
    http_response_code(500);
    echo json_encode(['success' => false]);
}