<?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';

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

$mysqli->close();

if ($wkName === null) {
    echo json_encode(["success" => false, "message" => "Keinen Wettkampfname angegeben. Setzen unter: /intern/wk-leitung/einstellungen"]);
    http_response_code(400);
    exit;
}

$programm = trim($_POST['prog'] ?? '');

$current_year = date('Y');
$monat = date('n');
if ($monat > 6) $current_year++;

$dir = $baseDir . '/files/ranglisten/';
$localPath = $dir . str_replace("/", "", str_replace(" ", "_", $wkName)) . "_Ergebnisse_" . str_replace("/", "", $programm) . "_" . $current_year . ".pdf";

if (!file_exists($localPath)) {
    echo json_encode(["success" => false, "message" => "Diese Rangliste existiert nicht."]);
    http_response_code(400);
    exit;
}

unlink($localPath);

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