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

verify_csrf();

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 json_encode(['success' => false, 'message' => 'Critical DB Error.']);
    exit;
}

require_once $baseDir . '/../scripts/cache/cache-creators/regenerate-display-dependencies-cache.php';

$action = $_POST['action'] ?? '';

if ($action === 'add') {
    $name = trim($_POST['name'] ?? '');
    $start_index = intval($_POST['start_index'] ?? 0);
    $color = trim($_POST['color'] ?? '#424242');
    $audiofile = intval($_POST['audiofile'] ?? 0);
    $audiofile_max_duration = (int) $_POST['audiofileMaxDuration'] ?? 0;

    if ($name === '') {
        echo json_encode(['success' => false, 'message' => 'Name ist erforderlich.']);
        exit;
    }

    $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_disziplinen (`name`, `start_index`, `color_kampfrichter`, `audiofile`, `audiofile_max_duration`) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sisii", $name, $start_index, $color, $audiofile, $audiofile_max_duration);
    $success = $stmt->execute();
    $new_id = $mysqli->insert_id;
    $stmt->close();

    if ($success) {
        echo json_encode(['success' => true, 'id' => $new_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Fehler beim Hinzufügen.']);
    }

    generateIntersectCache($mysqli, $baseDir);

} elseif ($action === 'update') {
    $id = intval($_POST['id'] ?? 0);
    $field = $_POST['field'] ?? '';
    $value = $_POST['value'] ?? '';
    $audiofile = intval($_POST['audiofile'] ?? 0);

    $allowedFields = ['name', 'start_index', 'color_kampfrichter', 'audiofile', 'audiofile_max_duration'];
    if ($id > 0 && in_array($field, $allowedFields)) {
        if ($field === 'start_index' || $field === 'audiofile' || $field === 'audiofile_max_duration') {
            $value = intval($value);
        }
        
        $updated = db_update($mysqli, $db_tabelle_disziplinen, [$field => $value], ['id' => $id]);
        if ($updated !== false) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'DB Update failed.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters.']);
    }

} elseif ($action === 'delete') {
    $id = intval($_POST['id'] ?? 0);

    if ($id > 0) {
        db_delete($mysqli, $db_tabelle_disziplinen, ['id' => $id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid ID.']);
    }

    generateIntersectCache($mysqli, $baseDir);

} else {
    echo json_encode(['success' => false, 'message' => 'Action not found.']);
}
