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

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

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

$abt_id = intval($_POST['abteilungId'] ?? 1);

// Determine current year
$current_year = date('Y');
$monat = date('n');
if ($monat > 6) $current_year++;

// Prepare SQL statement
$stmt = $mysqli->prepare("
    SELECT 
        t.id AS person_id
    FROM $db_tabelle_teilnehmende_gruppen tab 
    INNER JOIN $db_tabelle_teilnehmende t ON tab.turnerin_id = t.id
    INNER JOIN $db_tabelle_gruppen ab ON ab.id = tab.abteilung_id
    WHERE ab.id = ?
    ORDER BY t.id ASC
");

$stmt->bind_param('i', $abt_id);
$stmt->execute();

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

$indexedPersonen = array_column($personen, null, 'person_id');

// Close statement
$stmt->close();

// 1. Get the IDs from the first query results
$personenIds = array_column($personen, 'person_id');

if (empty($personenIds)) {
    echo json_encode(["success" => false, "message" => "Keine Notenänderungen vorhanden"]);
    http_response_code(400);
    exit;
}

$placeholders = implode(',', array_fill(0, count($personenIds), '?'));

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

$sqlNotenChanges = "DELETE FROM $db_tabelle_wertungen_log WHERE person_id IN ($placeholders) AND `wk_id` = ?";
$stmtNotenChanges = $mysqli->prepare($sqlNotenChanges);

$paramsArray = array_merge($personenIds, [$current_wk_id]);

$types = str_repeat('i', count($personenIds)) . 's';

$stmtNotenChanges->bind_param($types, ...$paramsArray);

$stmtNotenChanges->execute();
$stmtNotenChanges->close();

echo json_encode(["success" => true, "message" => "Notenänderung für Abteilung " . $abt_id . " gelöscht"]);
http_response_code(200);