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

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

ini_set('display_errors', 1);

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

ini_wkvs_session();

check_user_permission('wk_leitung');
check_user_permission('kampfrichter');

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

parse_input_to_delete();

verify_delete_csrf($_DELETE);

$programm_id = (int) ($_DELETE['programmId'] ?? 0);

if ($programm_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Keine valide Programm-ID']);
    exit;
}

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


$type = 'wkl';

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

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

$programm_name = db_get_var($mysqli, "SELECT `programm` FROM $db_tabelle_kategorien WHERE id = ? LIMIT 1", [$programm_id]) ?: null;

if ($programm_name === null) {
    echo json_encode(['success' => true, 'message' => 'Dieses Programm existiert nicht.']);
    http_response_code(400);
    exit;
}

$personen = db_select($mysqli, $db_tabelle_teilnehmende, "id", '`programm` = ?', [$programm_name]);

if (count($personen) < 1) {
    echo json_encode(['success' => true, 'message' => 'Es existieren keine Personen mit diesem Programm.']);
    http_response_code(400);
    exit;
}

$personen_id_array = array_column($personen, 'id');

$parram_array = array_fill(0, count($personen_id_array), "?");
$parram_string = implode(', ', $parram_array);

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

$value_array = array_merge($personen_id_array, [$current_wk_id]);

$stmt = $mysqli->prepare("DELETE FROM $db_tabelle_wertungen WHERE `person_id` IN ($parram_string) AND `wk_id` = ?");

$types_string = str_repeat("i", count($personen_id_array)) . "i"; 
$stmt->bind_param($types_string, ...$value_array);

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

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

$stmt->bind_param($types_string, ...$value_array);

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

echo json_encode(['success' => true, 'message' => 'Noten gelöscht']);
http_response_code(200);