<?

global $parentSort;
$parentSort = array();

switch ($_GET["action"]) {
    case "moveup_knowledgecenter":
        moveup_knowledgecenter();
        require_once("knowledge_listform.inc.php");
        break;
    case "movedown_knowledgecenter":
        movedown_knowledgecenter();
        require_once("knowledge_listform.inc.php");
        break;
    case "moveleft_knowledgecenter":
        moveleft_knowledgecenter();
        require_once("knowledge_listform.inc.php");
        break;
    case "moveright_knowledgecenter":
        moveright_knowledgecenter();
        require_once("knowledge_listform.inc.php");
        break;
    case "reorder_knowledgecenter":
        reorder_knowledgecenter();
        break;
    case "delete_knowledgecenter":
        delete_knowledgecenter();
        require_once("knowledge_listform.inc.php");
        break;
    case "edit_knowledgecenter":
        edit_knowledgecenter();
        break;
    case "save_knowledgecenter":
        save_knowledgecenter($site, $language);
        break;
    case "new_knowledgecenter":
        require_once("knowledge_cardform.inc.php");
        break;
    case 'delete_image':
        delete_image();
        require_once("knowledge_listform.inc.php");
        break;
    default:
        require_once("knowledge_listform.inc.php");
        break;
}

function update_children( $_parentId, $_list, $_level ) {
    global $parentSort;

    foreach ($_list as $site) {
        if (!array_key_exists($_parentId, $parentSort)) {
            $parentSort[$_parentId] = 1;
        }
        $query = "UPDATE knowledgecenter_category SET parent_id = " . $_parentId . ", level = " . $_level . ", sorting = " . $parentSort[$_parentId] . " WHERE id = " . (int)$site['id'];
        mysqli_query($GLOBALS['mysql_con'], $query);
        $parentSort[$_parentId]++;
        if (isset($site['children']) && count($site['children'])) {
            update_children($site['id'], $site['children'], $_level + 1);
        }
    }
}

function reorder_knowledgecenter() {
    global $parentSort;
    $list = $_POST['list'];
    if (!is_array($list) || count($list) == 0) {
        return;
    }

    $level = 1;
    foreach ($list as $site) {
        if (!array_key_exists(0, $parentSort)) {
            $parentSort[0] = 1;
        }
        $query = "UPDATE knowledgecenter_category SET parent_id = 0, level = 1, sorting = " . $parentSort[0] . " WHERE id = " . (int)$site['id'];
        mysqli_query($GLOBALS['mysql_con'], $query);
        $parentSort[0]++;
        if (isset($site['children']) && count($site['children'])) {
            update_children($site['id'], $site['children'], $level + 1);
        }
    }
}

function edit_knowledgecenter( $_id = "", $messages = array() ) {
    if ((int)$_id > 0) {
        $input_id = $_id;
    } else {
        $input_id = $_REQUEST["input_knowledgecenter_id"];
    }
    if ($input_id <> '') {
        $query  = "SELECT * FROM knowledgecenter_category WHERE id = '" . $input_id . "' LIMIT 1";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        if (@mysqli_num_rows($result) == 1) {
            $input_knowledgecenter = @mysqli_fetch_array($result);
            require_once("knowledge_cardform.inc.php");
        }
    } else {
        require_once("knowledge_listform.inc.php");
    }
}

function delete_knowledgecenter() {
    if ($_POST["input_knowledgecenter_id"] <> '') {
        $query = "DELETE FROM knowledgecenter_category WHERE id = '" . $_POST["input_knowledgecenter_id"] . "' LIMIT 1";
        if (@mysqli_query($GLOBALS['mysql_con'], $query)) {
            @mysqli_query($GLOBALS['mysql_con'], "UPDATE knowledgecenter_category SET parent_id = 0, level = level -1 WHERE parent_id = '" . $_POST["input_knowledgecenter_id"] . "'");
        }
    }
}

function save_knowledgecenter( $site, $language ) {

    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $messages    = array();

    $input_id               = "";
    $input_active           = ($_POST["input_active"] == "on") ? 1 : 0;
    $description            = $_POST["input_description"];
    $tags            = $_POST["input_tags"];

    if ($_POST["input_knowledgecenter_id"] <> '') {
        $query = "UPDATE knowledgecenter_category SET
					description = '" . $description . "',
					active = '" . $input_active . "',
					tags = '" . $tags . "'
					WHERE id = '" . $_POST["input_knowledgecenter_id"] . "' LIMIT 1";

        $inserted = FALSE;
        $input_id = $_REQUEST["input_knowledgecenter_id"];
    } else {
        $result = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"] . "' AND level = 1 ORDER BY sorting DESC LIMIT 1");
        if (@mysqli_num_rows($result) == 1) {
            $curr_knowledgecenter = @mysqli_fetch_array($result);
        }
        $query = "INSERT INTO knowledgecenter_category (main_site_id,main_language_id,parent_id,sorting,level,description,tags,active)
			VALUES (
				" . $site["id"] . ",
				" . $language["id"] . ",
				0,
				" . ($curr_knowledgecenter["sorting"] + 1) . ",
				1,
				'" . $description . "',
				'" . $tags . "',
				" . $input_active . "
			)";

        $inserted = TRUE;
    }

    $result = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"] . "' AND description = '" . $_POST["input_description"] . "'");
    if ((@mysqli_num_rows($result) <> 0) && ($_POST["input_knowledgecenter_id"] == '')) {
        $messages[] = "<div class=\"errorbox\">" . $translation->get("error_textkey_exists") . "</div>\n";
        $error      = TRUE;
    }

    if (!$error) {        
        @mysqli_query($GLOBALS['mysql_con'], $query);

        if ($inserted == TRUE) {
            $input_id   = mysqli_insert_id($GLOBALS['mysql_con']);
            $messages[] = '<div class="successbox">' . $translation->get("knowledgecenter_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("knowledgecenter_msg_success2") . '</div>';
        }

        // saveImg

        // $mandant_ids = $_POST['select_mandant'];
        // $mandant = explode(',', $mandant_ids);
        // if (!empty($mandant) && is_array($mandant)) { 
        //     $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM knowledgecenter_category_mandant_link WHERE knowledgecenter_category_id ='".$input_id."'");    
        //     foreach($mandant as $key => $mandant_value){
        //         $query = "INSERT INTO knowledgecenter_category_mandant_link
        //         (knowledgecenter_category_id, main_mandant_id)
        //         VALUES (
        //             " . $input_id . ",
        //             " . $mandant_value . "
        //         )";
        //         @mysqli_query($GLOBALS['mysql_con'], $query);
        //     }
        // }
    
        if(isset($_FILES) && !empty($_FILES) && $_FILES['input_image']['size'] != 0 ){
            $fileName = saveImage('input_image', $input_id);

            $query = "UPDATE knowledgecenter_category SET
                    image = '/03_Module/01_Firmenwiki/" . $fileName. "'
                    WHERE id = '" . $input_id . "' LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'],$query);
        }
        
        // SaveImag

        save_knowladge_permission($input_id, 'mandant');
        save_knowladge_permission($input_id, 'department');
        save_knowladge_permission($input_id, 'role');
        save_knowladge_permission($input_id, 'fachbereich');
        save_knowladge_permission($input_id, 'einricht');

        edit_knowledgecenter($input_id, $messages);
    } else {
        header('EDIT_ERROR: 1');
        $query  = "SELECT * FROM knowledgecenter_category WHERE id = '" . $_POST["input_knowledgecenter_id"] . "' LIMIT 1";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        if (@mysqli_num_rows($result) == 1) {
            $input_knowledgecenter = @mysqli_fetch_array($result);
        }
        $input_knowledgecenter["description"]   = $_REQUEST["input_description"];
        $input_knowledgecenter["tags"]          = $_REQUEST["input_tags"];
        $input_knowledgecenter["active"]        = $input_active;
        require_once("knowledge_cardform.inc.php");
    }

}

function count_posts($category_id){
    $query = "SELECT * FROM knowledgecenter_collection_link WHERE knowledgecenter_category_id = '".$category_id."'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $count = 0;
    while($posts = @mysqli_fetch_array($result)) {
        $query2 = "SELECT * FROM main_collection_read WHERE main_collection_id = '".$posts['main_collection_id']. "' AND main_contact_id = '".$GLOBALS['main_contact']['id']."'";
        $result2 = @mysqli_query($GLOBALS['mysql_con'], $query2);
        $count++;
    }
    return $count;
}

function show_knowledgecenter( $site, $language ) {
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $result   = mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"]."'");
    $num_rows = mysqli_num_rows($result);
    $qq = "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"]."'";
    if ($num_rows > 0) {
        echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"linklist\"><tr>";
            echo "<td><div>" . $translation->get("name") . "</div></td>";
            echo "<td width=\"150\" align=\"left\"><div></div></td>";
            echo "<td  class=\"code\" width=\"300\" align=\"left\"><div>" . $translation->get("linked_posts") . "</div></td>";
            echo "<td class=\"status\" width=\"100\" align=\"left\"><div>" . $translation->get("state") . "</div></td>";
        echo "</tr>";
        echo "<tr>";
            echo "<td class=\"linklist_seperator\"></td>";
            echo "<td class=\"linklist_seperator\"></td>";
            echo "<td class=\"linklist_seperator\"></td>";
            echo "<td class=\"linklist_seperator\"></td>";
        echo "</tr>";

        echo "</table>";
        // echo "<script>console.log('".$qq."')</script>";
        show_knowledgecenter_rek($site, $language, 0, 1, 0, $num_rows);


    } else {
        echo "<div class=\"infobox\">" . $translation->get("no_rows_found") . "</div>";
    }
    echo "\n";
    return TRUE;
}


function show_knowledgecenter_rek( $site, $language, $parent_id, $level, $input_counter, $num_rows ) {
    $translation     = \DynCom\mysyde\common\classes\Registry::get("translation");
    try {
        //code...
    
    $parent_id_query = ($parent_id == 0) ? " AND parent_id = 0" : " AND parent_id = '" . $parent_id."'";
    // $qq = "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"]."'" . $parent_id_query . " ORDER BY sorting ASC";
    // echo "<script>console.log('".$qq."')</script>";
    $result          = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"]."'" . $parent_id_query . " ORDER BY sorting ASC");
    
    if (@mysqli_num_rows($result) > 0) {
        if ($parent_id == 0) {
            echo "<ol class=\"linklist sortable\">";
        } else {
            echo "<ol>";
        }

        while ($knowledgecenter = @mysqli_fetch_array($result)) {
            $parentclass = "";
            if ($level > 1) {
                $parentclass = " data-tt-parent-id=\"{$knowledgecenter['parent_id']}\"";
            }

            $checkedRow = "false";
            if (isset($_REQUEST['input_knowledgecenter_id']) && $_REQUEST['input_knowledgecenter_id'] == $knowledgecenter['id']) {
                $checkedRow = "true";
            }

            echo "<li id=\"list_{$knowledgecenter['id']}\">";
            echo "<div data-inputid=\"" . $knowledgecenter['id'] . "\" data-action=\"edit_knowledgecenter\" data-inputname=\"input_knowledgecenter_id\" data-checked=\"" . $checkedRow . "\" class=\"linklist_content dd-handle\"><span class=\"disclose\"><span>&nbsp;</span></span>" . htmlentities($knowledgecenter["description"], ENT_COMPAT, "UTF-8") . "<div class=\"dd-icon\"></div>";
            echo "<div class=\"dd-code\">" . count_posts($knowledgecenter['id']) . " Beiträge</div>";
            echo "<div class=\"dd-status\">" . ($knowledgecenter["active"] == 1 ? $translation->get("active") : $translation->get("inactive")) . "</div></div>";
            $input_counter++;
            $input_counter = show_knowledgecenter_rek($site, $language, $knowledgecenter["id"], ($level + 1), $input_counter, $num_rows);
            echo "</li>";
        }
        echo "</ol>";
    }
    } catch (\Throwable $th) {
        echo $th;
    }

    return $input_counter;
}

function moveup_knowledgecenter() {
    move_knowledgecenter_vertical("<", "DESC", $_POST["input_knowledgecenter_id"]);
}

function movedown_knowledgecenter() {
    move_knowledgecenter_vertical(">", "ASC", $_POST["input_knowledgecenter_id"]);
}

function move_knowledgecenter_vertical( $way, $order, $knowledgecenter_id ) {
    $query  = "SELECT * FROM knowledgecenter_category WHERE id = '" . $knowledgecenter_id . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_knowledgecenter = @mysqli_fetch_array($result);
    }
    $parent_query = ($curr_knowledgecenter["parent_id"] <> '') ? " parent_id = '" . $curr_knowledgecenter["parent_id"]."'" : " parent_id = 0";
    $query        = "SELECT * FROM knowledgecenter_category WHERE main_site_id = '" . $curr_knowledgecenter["main_site_id"] . "' AND main_language_id = '" . $curr_knowledgecenter["main_language_id"] . "' AND" . $parent_query . " AND sorting " . $way . " " . $curr_knowledgecenter["sorting"] . " ORDER BY sorting " . $order . " LIMIT 1";
    $result       = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $change_knowledgecenter = @mysqli_fetch_array($result);
    }
    if (($curr_knowledgecenter["id"] <> '') && ($change_knowledgecenter["id"] <> '')) {
        $query = "UPDATE knowledgecenter_category SET sorting = " . $change_knowledgecenter["sorting"] . " WHERE id = " . $curr_knowledgecenter["id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $query = "UPDATE knowledgecenter_category SET sorting = " . $curr_knowledgecenter["sorting"] . " WHERE id = " . $change_knowledgecenter["id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function moveleft_knowledgecenter() {
    $query  = "SELECT * FROM knowledgecenter_category WHERE id = '" . $_POST["input_knowledgecenter_id"] . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_knowledgecenter = @mysqli_fetch_array($result);
    }
    $query  = "SELECT * FROM knowledgecenter_category WHERE id = '" . $curr_knowledgecenter["parent_id"] . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $parent_knowledgecenter = @mysqli_fetch_array($result);
    }
    $query  = "SELECT * FROM knowledgecenter_category WHERE parent_id = '" . $curr_knowledgecenter["parent_id"] . "' ORDER BY sorting DESC LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $last_child_knowledgecenter = @mysqli_fetch_array($result);
    }

    if (($curr_knowledgecenter["id"] <> '') && ($parent_knowledgecenter["id"] <> '')) {
        // Eigentlichen Menüeintrag aktualisieren
        if ($parent_knowledgecenter["parent_id"] == '') {
            $parent_knowledgecenter["parent_id"] = "0";
        }
        $query = "UPDATE knowledgecenter_category SET parent_id = " . $parent_knowledgecenter["parent_id"] . ", level = " . $parent_knowledgecenter["level"] . ", sorting = " . ($parent_knowledgecenter["sorting"] + 1) . " WHERE id = " . $curr_knowledgecenter["id"];
        if (@mysqli_query($GLOBALS['mysql_con'], $query)) {
            // Level der ursprünglichen Untermenüpunkte aktualisieren
            update_knowledgecenter_children($curr_knowledgecenter["id"], "-");
            // Parent-ID und Sortierung der neuen Untermenüpunkte aktualisieren
            $parent_query = ($curr_knowledgecenter["parent_id"] <> '') ? " parent_id = '" . $curr_knowledgecenter["parent_id"]."'" : " parent_id = 0";
            $query        = "SELECT * FROM knowledgecenter_category WHERE" . $parent_query . " AND sorting > " . $curr_knowledgecenter["sorting"] . " AND main_site_id = '" . $GLOBALS["site"]["id"] . "' AND main_language_id = '" . $GLOBALS["language"]["id"]."'";
            $new_sorting  = 1;
            $result       = @mysqli_query($GLOBALS['mysql_con'], $query);
            if (@mysqli_num_rows($result) > 0) {
                while ($knowledgecenter = @mysqli_fetch_array($result)) {
                    $query = "UPDATE knowledgecenter_category SET parent_id = " . $curr_knowledgecenter["id"] . ", sorting = " . $new_sorting . " WHERE id = " . $knowledgecenter["id"] . " LIMIT 1";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                    $new_sorting++;
                }
            }
            // Sortierung der neuen Nachfolger aktualisieren
            $new_sorting  = $parent_knowledgecenter["sorting"] + 1;
            $parent_query = ($parent_knowledgecenter["parent_id"] <> '0') ? " parent_id = '" . $parent_knowledgecenter["parent_id"]."'" : " parent_id = 0";
            $query        = "SELECT * FROM knowledgecenter_category WHERE" . $parent_query . " AND id <> " . $curr_knowledgecenter["id"] . " AND sorting >= " . $new_sorting . " AND main_site_id = " . $GLOBALS["site"]["id"] . " AND main_language_id = " . $GLOBALS["language"]["id"];
            $result       = @mysqli_query($GLOBALS['mysql_con'], $query);
            if (@mysqli_num_rows($result) > 0) {
                while ($knowledgecenter = @mysqli_fetch_array($result)) {
                    $new_sorting++;
                    $query = "UPDATE knowledgecenter_category SET sorting = " . $new_sorting . " WHERE id = " . $knowledgecenter["id"] . " LIMIT 1";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
        }
    }
}

function moveright_knowledgecenter() {
    $query  = "SELECT * FROM knowledgecenter_category WHERE id = '" . $_POST["input_knowledgecenter_id"] . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_knowledgecenter = @mysqli_fetch_array($result);
    }
    $parent_query = ($curr_knowledgecenter["parent_id"] <> '') ? " parent_id = '" . $curr_knowledgecenter["parent_id"]."'" : " parent_id = 0";
    $query        = "SELECT * FROM knowledgecenter_category WHERE" . $parent_query . " AND sorting < " . $curr_knowledgecenter["sorting"] . " AND main_site_id = " . $GLOBALS["site"]["id"] . " AND main_language_id = " . $GLOBALS["language"]["id"] . " ORDER BY sorting DESC LIMIT 1";
    $result       = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $pre_knowledgecenter = @mysqli_fetch_array($result);
    }
    $query  = "SELECT * FROM knowledgecenter_category WHERE parent_id = '" . $pre_knowledgecenter["id"] . "' ORDER BY sorting DESC LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $lastprechild_knowledgecenter = @mysqli_fetch_array($result);
    }
    if (($curr_knowledgecenter["id"] <> '') && ($pre_knowledgecenter["id"] <> '')) {
        // Eigentlichen Menüeintrag aktualisieren
        if ($lastprechild_knowledgecenter["sorting"] == '') {
            $lastprechild_knowledgecenter["sorting"] = 0;
        }
        $query = "UPDATE knowledgecenter_category SET parent_id = " . $pre_knowledgecenter["id"] . ", level = " . ($curr_knowledgecenter["level"] + 1) . ", sorting = " . ($lastprechild_knowledgecenter["sorting"] + 1) . " WHERE id = " . $curr_knowledgecenter["id"] . " AND main_site_id = " . $GLOBALS["site"]["id"] . " AND main_language_id = " . $GLOBALS["language"]["id"];
        if (@mysqli_query($GLOBALS['mysql_con'], $query)) {
            // Level der ursprünglichen Untermenüpunkte aktualisieren
            update_knowledgecenter_children($curr_knowledgecenter["id"], "+");

            // Sortierung der neuen Nachfolger aktualisieren
            $new_sorting  = $curr_knowledgecenter["sorting"];
            $parent_query = ($curr_knowledgecenter["parent_id"] <> '') ? " parent_id = " . $curr_knowledgecenter["parent_id"] : " parent_id = 0";
            $query        = "SELECT * FROM knowledgecenter_category WHERE" . $parent_query . " AND sorting >= " . $new_sorting . " AND main_site_id = " . $GLOBALS["site"]["id"] . " AND main_language_id = " . $GLOBALS["language"]["id"];
            $result       = @mysqli_query($GLOBALS['mysql_con'], $query);
            if (@mysqli_num_rows($result) > 0) {
                while ($knowledgecenter = @mysqli_fetch_array($result)) {
                    $query = "UPDATE knowledgecenter_category SET sorting = " . $new_sorting . " WHERE id = " . $knowledgecenter["id"] . " LIMIT 1";
                    $new_sorting++;
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
        }
    }
}

function update_knowledgecenter_children( $knowledgecenter_id, $way ) {
    $query  = "SELECT * FROM knowledgecenter_category WHERE parent_id = '" . $knowledgecenter_id."'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) > 0) {
        while ($knowledgecenter = @mysqli_fetch_array($result)) {
            $query = "UPDATE knowledgecenter_category SET level = level " . $way . " 1 WHERE id = " . $knowledgecenter["id"] . " LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'], $query);
            update_knowledgecenter_children($knowledgecenter["id"], $way);
        }
    }
}

function saveImage($filekey = 'input_image', $input_id) {
    delete_image();

    $erlaubte_endungen = array("jpg", "jpeg", "gif", "png", "svg", "webp");
    $filename = strtolower($_FILES[$filekey]['name']);
    $filename_expl = explode(".", $filename);
    if (!in_array($filename_expl[count($filename_expl) - 1], $erlaubte_endungen)) {
        $messages = "<div class='errorbox'>" . $translation->get("error_slideshow_line2") . "</div>\n";
        $error = TRUE;
    }
    
    $saveFilename = $input_id . "_" . time() . "_" . cleanFilename($_FILES[$filekey]['name']);
    define("PATH_NAVIGATION", "../../userdata/03_Module/01_Firmenwiki/");
    move_uploaded_file($_FILES[$filekey]['tmp_name'], PATH_NAVIGATION . $saveFilename);

    return $saveFilename;
    
}
function delete_image() {
    $knowledgecenter_id = $_POST['input_knowledgecenter_id'];
    $query = "SELECT * FROM knowledgecenter_category WHERE id =".$knowledgecenter_id." LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $knowledgecenter = @mysqli_fetch_array($result);
    if(!empty($knowledgecenter)){
        $filename = $knowledgecenter['image'];
        define("PATH_NAVIGATION", "../../userdata/03_Module/01_Firmenwiki/");
        
        if (file_exists(PATH_NAVIGATION . $filename)) {
            unlink(PATH_NAVIGATION . $filename);
        }  
        $query = "UPDATE knowledgecenter_category SET
				image = ''
				WHERE id = '" . $knowledgecenter_id . "' LIMIT 1"; 
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}
function save_knowladge_permission($collection_id, $type){
    $type_ids = explode(',', $_POST['select_permission_'.$type]);
    if (count($type_ids) == 0 || $type_ids[0] == "") {
        @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM knowledgecenter_category_".$type."_link WHERE knowledgecenter_category_id = '".$collection_id."'");
        if ($type == "fachbereich") {
            $qeury_select = "SELECT id FROM organogramm_space";
        }elseif ($type == "einricht") {
            $qeury_select = "SELECT id FROM organigramm_einricht";
        }else {
            $qeury_select = "SELECT id FROM main_".$type."";
        }

        $sql_select = @mysqli_query($GLOBALS['mysql_con'], $qeury_select);

        while ($row = @mysqli_fetch_array($sql_select)) {
            $query = "INSERT IGNORE INTO knowledgecenter_category_".$type."_link
            (knowledgecenter_category_id, main_".$type."_id)
            VALUES (
                '" . $collection_id ."',
                '" .  $row["id"] . "'
            )";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
        
    }else {
        if(!empty($type_ids) && gettype($type_ids) == 'array')  { 
            @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM knowledgecenter_category_".$type."_link WHERE knowledgecenter_category_id = '".$collection_id."'");
            foreach($type_ids as $permission_type_id){
                if ($permission_type_id != "") {
                    $query = "INSERT IGNORE INTO knowledgecenter_category_".$type."_link
                    (knowledgecenter_category_id, main_".$type."_id)
                    VALUES (
                        '" . $collection_id ."',
                        '" .  $permission_type_id . "'
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            
            }
            @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM knowledgecenter_category_".$type."_link WHERE knowledgecenter_category_id = '".$collection_id."' AND main_".$type."_id = 0;");
        }
    }
    
}

function multi_select_permission($collection_id, $type){
    $translation   = \DynCom\mysyde\common\classes\Registry::get("translation");

    
    if ($type == "einricht") {
        $query = "SELECT * FROM organigramm_einricht";
    }elseif($type == "fachbereich"){
        $query = "SELECT * FROM organogramm_space";
    }else {
        $query = "SELECT * FROM main_".$type;
    }

    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    $preselect = array();
    
    if ($collection_id != null) {
        $query2 = "SELECT * FROM knowledgecenter_category_".$type."_link WHERE knowledgecenter_category_id = ".$collection_id;
        $result2 = @mysqli_query($GLOBALS['mysql_con'], $query2);
        $allselect = array();
        while($row2 = @mysqli_fetch_array($result2)){
            array_push($preselect,$row2['main_'.$type.'_id']);
        }
    }

    ?>
    <div class="label"><?= $translation->get("top_".$type)?></div>
    <div class="websites bc-select-ui ui fluid multiple search selection dropdown type_<?= $type ?>" style="clear:both;display:inline-block;">
        <input type="hidden" name="select_permission_<?= $type ?>">
        <i class="dropdown icon"></i>
        <div class="default text"><?= $translation->get("top_".$type)?></div>
        <div class="menu">
            <?  
            if ($collection_id != null) {
                while($row = @mysqli_fetch_array($result)) {
                    array_push($allselect, $row['id']);
                    echo "<div class=\"item\" data-value=\"{$row['id']}\">".$row["description"]."</div>";
                }
            }
            ?>
        </div>
    </div>
    <div class="save_button_coll">
        <div class="all_mandants" id="<?php echo "all_get".$type; ?>"><?php echo $translation->get("all_get_".$type)?></div>
        <div class="all_mandants" id="<?php echo "all_del".$type; ?>"><?php echo $translation->get("all_delete_".$type)?></div>
    </div>

    <script type="text/javascript" src="/plugins/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="/plugins/Semantic-UI-master/semantic.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/plugins/Semantic-UI-master/bc-semantic.css?time=<?= filemtime($_SERVER['DOCUMENT_ROOT'] . '/plugins/Semantic-UI-master/bc-semantic.css')?>">
    <script>

        var $y = jQuery.noConflict();
        $y( document ).ready(function() {
            $y('.websites.ui.fluid.multiple.dropdown.type_<?= $type ?>').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });
        $("<?php echo "#all_get".$type;?>").click(function() {
            $y('.websites.ui.fluid.multiple.dropdown.type_<?= $type ?>').dropdown('set selected', <?= json_encode($allselect) ?>); 
        });
        $("<?php echo "#all_del".$type;?>").click(function() {
            console.log("delete");
            $y('.websites.ui.fluid.multiple.dropdown.type_<?= $type ?>').dropdown('clear'); 
        });
    </script>
<?
}

function create_mandant_select($category_id){
    $translation   = \DynCom\mysyde\common\classes\Registry::get("translation");
    $query = "SELECT * FROM main_mandant";
    $mandant_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    $preselect = array();
    
    // Überprüfen, ob category_id vorhanden ist
    if (!empty($category_id)) {
        $query = "SELECT * FROM knowledgecenter_category_mandant_link WHERE knowledgecenter_category_id = ".$category_id;
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        
        while($row = @mysqli_fetch_array($result)){
            array_push($preselect,$row['main_mandant_id']);
        }
    }
    
    $allselect = array();
    ?>
    <div class="label"><?php echo $translation->get("mandant")?></div>
    <div class="mandant bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
        <input type="hidden" name="select_mandant">
        <i class="dropdown icon"></i>
        <div class="default text"><?php echo $translation->get("mandant")?></div>
        <div class="menu">
            <?php  
                while($mandant = @mysqli_fetch_array($mandant_result)) {
                    array_push($allselect,$mandant['id']);
                    echo "<div class=\"item\" data-value=\"{$mandant['id']}\">".$mandant["description"]."</div>";
                }
            ?>
        </div>
    </div>
    <div class='all_mandants' ><?php echo $translation->get("all_mandants")?></div>
    <script type="text/javascript" src="/plugins/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="/plugins/Semantic-UI-master/semantic.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/plugins/Semantic-UI-master/bc-semantic.css?time=<?= filemtime($_SERVER['DOCUMENT_ROOT'] . '/plugins/Semantic-UI-master/bc-semantic.css')?>">
    <script>
        var $y = jQuery.noConflict();

        $y( document ).ready(function() {
            $y('.mandant.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });

        $y(".all_mandants").click(function() {
            $y('.mandant.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($allselect) ?>); 
        });

    </script>
<?php
}
