<?

global $parentSort;
$parentSort = array();

switch ($_GET["action"]) {
    case "moveup_learning":
        moveup_learning();
        require_once("learning_listform.inc.php");
        break;
    case "movedown_learning":
        movedown_learning();
        require_once("learning_listform.inc.php");
        break;
    case "moveleft_learning":
        moveleft_learning();
        require_once("learning_listform.inc.php");
        break;
    case "moveright_learning":
        moveright_learning();
        require_once("learning_listform.inc.php");
        break;
    case "reorder_learning":
        reorder_learning();
        break;
    case "delete_learning":
        delete_learning();
        require_once("learning_listform.inc.php");
        break;
    case "edit_learning":
        edit_learning();
        break;
    case "save_learning":
        save_learning($site, $language);
        break;
    case "new_learning":
        require_once("learning_cardform.inc.php");
        break;
    case 'delete_image':
        delete_image();
        require_once("learning_listform.inc.php");
        break;
    default:
        require_once("learning_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 learning_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_learning() {
    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 learning_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_learning( $_id = "", $messages = array() ) {
    if ((int)$_id > 0) {
        $input_id = $_id;
    } else {
        $input_id = $_REQUEST["input_learning_id"];
    }
    if ($input_id <> '') {
        $query  = "SELECT * FROM learning_category WHERE id = '" . $input_id . "' LIMIT 1";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        if (@mysqli_num_rows($result) == 1) {
            $input_learning = @mysqli_fetch_array($result);
            require_once("learning_cardform.inc.php");
        }
    } else {
        require_once("learning_listform.inc.php");
    }
}

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

function save_learning( $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_learning_id"] <> '') {
        $query = "UPDATE learning_category SET
					description = '" . $description . "',
					active = '" . $input_active . "',
					tags = '" . $tags . "'
					WHERE id = '" . $_POST["input_learning_id"] . "' LIMIT 1";

        $inserted = FALSE;
        $input_id = $_REQUEST["input_learning_id"];
    } else {
        $result = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM learning_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_learning = @mysqli_fetch_array($result);
        }
        $query = "INSERT INTO learning_category (main_site_id,main_language_id,parent_id,sorting,level,description,tags,active)
			VALUES (
				" . $site["id"] . ",
				" . $language["id"] . ",
				0,
				" . ($curr_learning["sorting"] + 1) . ",
				1,
				'" . $description . "',
				'" . $tags . "',
				" . $input_active . "
			)";

        $inserted = TRUE;
    }

    $result = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM  learning_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"] . "' AND code = '" . $_POST["input_code"] . "'");
    if ((@mysqli_num_rows($result) <> 0) && ($_POST["input_learning_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("learning_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("learning_msg_success2") . '</div>';
        }

        // saveImg

        $mandant_ids = $_POST['select_mandant'];
        $mandant = explode(',', $mandant_ids);
        if(!empty($mandant) && gettype($mandant) == 'array')  { 
            $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM learning_category_mandant_link WHERE learning_category_id ='".$input_id."'");    
            foreach($mandant as $key => $mandant_value){
                $query = "INSERT INTO learning_category_mandant_link
                (learning_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 learning_category SET
                    image = '" . $fileName. "'
                    WHERE id = '" . $input_id . "' LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'],$query);
        }
        
        // SaveImag

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

}

function count_posts($category_id){
    $query = "SELECT * FROM learning_collection_link WHERE learning_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_learning( $site, $language ) {
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $result   = mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM learning_category WHERE main_site_id = '" . $site["id"] . "' AND main_language_id = '" . $language["id"]."'");
    $num_rows = mysqli_num_rows($result);
    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>";

        show_learning_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_learning_rek( $site, $language, $parent_id, $level, $input_counter, $num_rows ) {
    $translation     = \DynCom\mysyde\common\classes\Registry::get("translation");
    $parent_id_query = ($parent_id == 0) ? " AND parent_id = 0" : " AND parent_id = '" . $parent_id."'";
    $result          = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM learning_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 ($learning = @mysqli_fetch_array($result)) {
            $parentclass = "";
            if ($level > 1) {
                $parentclass = " data-tt-parent-id=\"{$learning['parent_id']}\"";
            }

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

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

    return $input_counter;
}

function moveup_learning() {
    move_learning_vertical("<", "DESC", $_POST["input_learning_id"]);
}

function movedown_learning() {
    move_learning_vertical(">", "ASC", $_POST["input_learning_id"]);
}

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

function moveleft_learning() {
    $query  = "SELECT * FROM learning_category WHERE id = '" . $_POST["input_learning_id"] . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_learning = @mysqli_fetch_array($result);
    }
    $query  = "SELECT * FROM learning_category WHERE id = '" . $curr_learning["parent_id"] . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $parent_learning = @mysqli_fetch_array($result);
    }
    $query  = "SELECT * FROM learning_category WHERE parent_id = '" . $curr_learning["parent_id"] . "' ORDER BY sorting DESC LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $last_child_learning = @mysqli_fetch_array($result);
    }

    if (($curr_learning["id"] <> '') && ($parent_learning["id"] <> '')) {
        // Eigentlichen Menüeintrag aktualisieren
        if ($parent_learning["parent_id"] == '') {
            $parent_learning["parent_id"] = "0";
        }
        $query = "UPDATE learning_category SET parent_id = " . $parent_learning["parent_id"] . ", level = " . $parent_learning["level"] . ", sorting = " . ($parent_learning["sorting"] + 1) . " WHERE id = " . $curr_learning["id"];
        if (@mysqli_query($GLOBALS['mysql_con'], $query)) {
            // Level der ursprünglichen Untermenüpunkte aktualisieren
            update_learning_children($curr_learning["id"], "-");
            // Parent-ID und Sortierung der neuen Untermenüpunkte aktualisieren
            $parent_query = ($curr_learning["parent_id"] <> '') ? " parent_id = '" . $curr_learning["parent_id"]."'" : " parent_id = 0";
            $query        = "SELECT * FROM learning_category WHERE" . $parent_query . " AND sorting > " . $curr_learning["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 ($learning = @mysqli_fetch_array($result)) {
                    $query = "UPDATE learning_category SET parent_id = " . $curr_learning["id"] . ", sorting = " . $new_sorting . " WHERE id = " . $learning["id"] . " LIMIT 1";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                    $new_sorting++;
                }
            }
            // Sortierung der neuen Nachfolger aktualisieren
            $new_sorting  = $parent_learning["sorting"] + 1;
            $parent_query = ($parent_learning["parent_id"] <> '0') ? " parent_id = '" . $parent_learning["parent_id"]."'" : " parent_id = 0";
            $query        = "SELECT * FROM learning_category WHERE" . $parent_query . " AND id <> " . $curr_learning["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 ($learning = @mysqli_fetch_array($result)) {
                    $new_sorting++;
                    $query = "UPDATE learning_category SET sorting = " . $new_sorting . " WHERE id = " . $learning["id"] . " LIMIT 1";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
        }
    }
}

function moveright_learning() {
    $query  = "SELECT * FROM learning_category WHERE id = '" . $_POST["input_learning_id"] . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_learning = @mysqli_fetch_array($result);
    }
    $parent_query = ($curr_learning["parent_id"] <> '') ? " parent_id = '" . $curr_learning["parent_id"]."'" : " parent_id = 0";
    $query        = "SELECT * FROM learning_category WHERE" . $parent_query . " AND sorting < " . $curr_learning["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_learning = @mysqli_fetch_array($result);
    }
    $query  = "SELECT * FROM learning_category WHERE parent_id = '" . $pre_learning["id"] . "' ORDER BY sorting DESC LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $lastprechild_learning = @mysqli_fetch_array($result);
    }
    if (($curr_learning["id"] <> '') && ($pre_learning["id"] <> '')) {
        // Eigentlichen Menüeintrag aktualisieren
        if ($lastprechild_learning["sorting"] == '') {
            $lastprechild_learning["sorting"] = 0;
        }
        $query = "UPDATE learning_category SET parent_id = " . $pre_learning["id"] . ", level = " . ($curr_learning["level"] + 1) . ", sorting = " . ($lastprechild_learning["sorting"] + 1) . " WHERE id = " . $curr_learning["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_learning_children($curr_learning["id"], "+");

            // Sortierung der neuen Nachfolger aktualisieren
            $new_sorting  = $curr_learning["sorting"];
            $parent_query = ($curr_learning["parent_id"] <> '') ? " parent_id = " . $curr_learning["parent_id"] : " parent_id = 0";
            $query        = "SELECT * FROM learning_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 ($learning = @mysqli_fetch_array($result)) {
                    $query = "UPDATE learning_category SET sorting = " . $new_sorting . " WHERE id = " . $learning["id"] . " LIMIT 1";
                    $new_sorting++;
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
        }
    }
}

function update_learning_children( $learning_id, $way ) {
    $query  = "SELECT * FROM learning_category WHERE parent_id = '" . $learning_id."'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) > 0) {
        while ($learning = @mysqli_fetch_array($result)) {
            $query = "UPDATE learning_category SET level = level " . $way . " 1 WHERE id = " . $learning["id"] . " LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'], $query);
            update_learning_children($learning["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_NAVIGATON", "../../userdata/learning/");
    move_uploaded_file($_FILES[$filekey]['tmp_name'], PATH_NAVIGATON . $saveFilename);

    return $saveFilename;
    
}
function delete_image() {
    $learning_id = $_POST['input_learning_id'];
    $query = "SELECT * FROM learning_category WHERE id =".$learning_id." LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $learning = @mysqli_fetch_array($result);
    if(!empty($learning)){
        $filename = $learning['image'];
        define("PATH_NAVIGATON", "../../userdata/learning/");
        
        if (file_exists(PATH_NAVIGATON . $filename)) {
            unlink(PATH_NAVIGATON . $filename);
        }  
        $query = "UPDATE learning_category SET
				image = ''
				WHERE id = '" . $learning_id . "' LIMIT 1"; 
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

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();
    
    $query = "SELECT * FROM learning_category_mandant_link WHERE learning_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">
            <?  
                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) ?>); 
        });

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

    </script>
<?
}