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

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

if ($action === 'add') {
    $name = trim($_POST['name'] ?? '');
    $has_endtime = intval($_POST['has_endtime'] ?? 0);
    $index = intval($_POST['index'] ?? 0);

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

    $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_zeitplan_types (`name`, `has_endtime`, `display_index`) VALUES (?, ?, ?)");
    $stmt->bind_param("sii", $name, $has_endtime, $index);
    $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.']);
    }

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

    $allowedFields = ['name', 'has_endtime', 'display_index'];
    if ($id > 0 && in_array($field, $allowedFields)) {
        if ($field === 'display_index') {
            $value = intval($value);
        }
        
        $updated = db_update($mysqli, $db_tabelle_zeitplan_types, [$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_zeitplan_types, ['id' => $id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid ID.']);
    }

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