<?php
date_default_timezone_set('Europe/Berlin');
require_once(MODULE_PATH.'collection/custom_collection_functions.inc.php');
require_once(MODULE_PATH.'collection/masked_collection_functions.inc.php');

update_visitor_data(array(
    'collection_options' => array(
        'collection_edit' => TRUE
    )
));

$messages = array();
$error = FALSE;
global $masked;
$maked = FALSE;
if (isset($custom_action)) {
    $action = $custom_action;
} else {
    $action = $_REQUEST["action"];
}

$subaction = substr($action, strrpos($action, '_') + 1);

global $collection_setup_id;
$collection_setup_id = NULL;
if (isset($_GET["level_2"]) && (int)$_GET["level_2"]) {
    $collection_setup_id = $_GET["level_2"];
}
 
if ($action == "" || $subaction == 'collection') {
    switch ($action) {
        case 'new_collection':
            save_collection(TRUE);
            // require_once("edit_collection_cardform.inc.php");
            break;
        case 'save_collection':
            save_collection();
            break;
        case 'frontend_collection':
            global $collection_setup_id ;
            $collection_setup_id = $_REQUEST['main_collection_setup_id'];
            save_collection_frontend();
            break;    
        case 'edit_collection':
            edit_collection();
            break;
        case 'delete_collection':
            delete_collection();
            break;

            // Kollektionen filtern
        case 'filter_collection':
            filter_collection();
            break;

        case 'moveup_line_collection':
            moveup_collection();
            require_once("edit_collection_listform.inc.php");
            break;
        case 'movedown_line_collection':
            movedown_collection();
            require_once("edit_collection_listform.inc.php");
            break;

        case 'update_sortorder_collection':
            update_sortorder_collection();
            break;

        case 'open_card_collection':
            open_card_collection();
            break;
        //Custom Collection
        case 'newCustomLine_collection':
            new_line_collection_setup();    
        case 'loadsitepart_collection':
                load_sitepart_form();
                break; 
        case  'saveLine_collection':
                save_line_collection_setup();
                break; 
        case 'editLineSetup_collection':
              edit_line_collection_setup();
              break;  
        case 'deleteLineSetup_collection':      
              delete_line_collection_setup();
              break;      
        case 'editCustomSetup_collection':
              edit_collection_setup();
              break;  
        case 'update_sortorder_setup_collection':
                update_sortorder_collection_setup();
                break;      
        // Custom Collection End 
        case 'mask_collection';
                global $masked;
                $masked = TRUE;
            save_collection(TRUE);
            break;  
        case 'copy_collection':
            copy_collection();      
        // Masked Collection Funtions
            break;
        case 'create_collection';
            break;
        default:
            require_once("edit_collection_listform.inc.php");
            break;
    }
} else {
    // hier handelt es sich um ein sitepart
    require_once(MODULE_PATH . $subaction . "/edit_" . $subaction . ".inc.php");
}

function update_sortorder_collection()
{
    $sorting = 1;
    foreach ($_POST['linklistid'] as $itemId) {
        $query = "UPDATE main_collection SET sorting = " . $sorting . " WHERE id = '" . $itemId . "'";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $sorting++;
    }
}

function open_card_collection(){ ?>
    <script type="text/javascript">
        openCardOnStart = true;
        openCardAction = 'new_collection';
    </script>
<?php }

function get_collection_setup_info()
{
    global $collection_setup_id;
    $query = "SELECT * FROM main_collection_setup WHERE id = '" . $collection_setup_id . "'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

    return @mysqli_fetch_array($result);
}

function filter_collection()
{
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $filter_id = $_REQUEST['filter_id'];

    $where = "";
    if ((int)$filter_id > 0) {
        $where = " and main_collection_setup_id = " . $filter_id;
    }

    $query = "SELECT
		main_collection.id, 
		main_collection_setup.description AS '" . $translation->get("type") . "',
		main_collection.description AS '" . $translation->get("description") . "',
		from_unixtime(main_collection.modified_date, '%d.%m.%Y %H:%i:%s') AS '" . $translation->get("changed_on") . "', 
		main_admin_user.name AS '" . $translation->get("changed_by") . "' 
	from 
		main_collection left join main_admin_user
	ON 
		main_collection.modified_user = main_admin_user.id
		inner join main_collection_setup
	ON
	 	main_collection.main_collection_setup_id = main_collection_setup.id
	where 
		(main_collection_setup.main_language_id = " . (int)$GLOBALS["language"]['id'] . " OR main_collection_setup.all_languages = 1) $where ORDER BY id asc";

    $format = array('option', 'text', 'text', 'text', 'text');
    if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
        linklist($result, "form_collection_list", $format, "input_collection_id", "edit_collection");
    }
}

function editXML($input_id, $type){
    $file = MODULE_PATH . "collection/collections.xml";
    $xml = simplexml_load_file($file);
    if($type == 'UPDATE'){

    }elseif($type == 'DELETE'){
        foreach($xml->collection_setup as $collection_setup){
            foreach ($collection_setup as $collection) {
                // if($collection_setup['id'] == $input_id) {
                //     $dom=dom_import_simplexml($collection);
                //     $dom->parentNode->removeChild($dom);
                // }
            }
        }
    }elseif($type == 'INSERT'){
        $collection_setup = $xml->children('collection_setup');
        $collection = $collection_setup->addChild('collection');
        $collection->addAttribute('id', $input_id);
    }
    echo $xml->asXML();
}

function edit_line_collection($_id = "", $messages = array())
{

    if ((int)$_id > 0) {
        $line_id = $_id;
    } else {
        $line_id = $_REQUEST["input_line_id"];
    }

    if ($line_id <> '') {

        $query = "SELECT * FROM main_collection_content WHERE id = '" . $line_id . "' LIMIT 1";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);

        if (@mysqli_num_rows($result) == 1) {

            $input_line = @mysqli_fetch_array($result);

            require_once("edit_collection_line_cardform.php");
        }
    } else {

        require_once("edit_collection_line_cardform.php");
    }
}


/**
 * delete_picture() Löschen einzelner Bilder
 *
 * @param mixed $sitepart
 *
 * @return
 */

function edit_collection($_id = "", $messages = array(), $frontend = FALSE)
{

    if ((int)$_id > 0) {
        $input_id = $_id;
    } else {
        $input_id = $_REQUEST["input_collection_id"];
    }

    if ($input_id <> '') {

        $query = "SELECT * FROM main_collection WHERE id = '" . $input_id . "' LIMIT 1";

        $result = @mysqli_query($GLOBALS['mysql_con'], $query);

        if (@mysqli_num_rows($result) == 1) {

            $input_collection = @mysqli_fetch_array($result);
            if(!$frontend){
                require_once("edit_collection_cardform.inc.php");
            }else{
                
            //    ini_set('display_errors', '1');
            //     ini_set('display_startup_errors', '1');
            //     error_reporting(E_ALL);
                $_GET['setup_id'] = $input_collection['main_collection_setup_id'];
                return require_once("frontend_creation_cardform.inc.php");
            }
            
        }
    } else {
        if(!$frontend){
            require_once("edit_collection_cardform.inc.php");
        }else{
            require_once("frontend_creation_cardform.inc.php");
        }
         
    }
}


function save_collection($firstsave = FALSE)
{
    global $collection_setup_id;
    global $masked;
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $input_id = "";

    $input_registration = ($_POST["input_registration"] == "on") ? 1 : 0;
    $input_active = ($_POST["input_active"] == "on") ? 1 : 0;
    $input_readable = ($_POST["input_readable"] == "on") ? 1 : 0;
    $input_is_archived = (isset($_POST["input_is_archived"]) && $_POST["input_is_archived"] == "on") ? 1 : 0;
    $registration_contactform_id = 0;

    if ($input_registration == 1) {
        $registration_contactform_id = (int)$_POST['registration_contactform_id'];
    }

    $input_validity_from = datetosql($_POST["input_validity_from"]);
    $input_validity_to = datetosql($_POST["input_validity_to"]);

    $websites = array();
    $website_ids = $_POST['select_website'];
    if($website_ids == NULL && !isset($_POST['select_website'])){
        array_push($websites, $GLOBALS['site']['id']);
    }else{
        $websites = explode(',', $website_ids);
    }

    $groups = array();
    $group_ids = $_POST['select_group'];
    if($group_ids != NULL && isset($_POST['select_group'])){
        $groups = explode(',', $group_ids);
    } 

    //edit oder save
    if ($_REQUEST["input_collection_id"] <> '' && $firstsave === FALSE) {
        $insertquery = "UPDATE main_collection SET
				description = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST["input_description"]) . "',
				registration = " . $input_registration . ",
				registration_contactform_id = '" . $registration_contactform_id . "',
				validity_from = " . $input_validity_from . ",
				validity_to = " . $input_validity_to . ",
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
				active = 1,
                readable = " . $input_readable . ",
                is_archived = " . $input_is_archived . "
				WHERE id = '" . $_REQUEST["input_collection_id"] . "' 
			LIMIT 1";
        $inserted = FALSE;
        $input_id = $_REQUEST["input_collection_id"];
        save_collection_tags();
        $query = "DELETE FROM main_collection_read WHERE main_collection_id = " . $_REQUEST["input_collection_id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
        createMySydeLog('main_collection', $input_id, 'UPDATE');
    } else if(!$masked) {
        $sorting = @mysqli_fetch_array(@mysqli_query($GLOBALS['mysql_con'], "SELECT MAX(sorting)+1 AS 'newsorting' FROM main_collection WHERE main_collection_setup_id = '" . $collection_setup_id . "'"));
        $sorting = ($sorting["newsorting"] <> "") ? $sorting = $sorting["newsorting"] : $sorting = 1;

        $insertquery = "INSERT INTO main_collection
            (main_language_id, main_collection_setup_id, description, registration, registration_contactform_id, creation_date, modified_date, modified_user, validity_from, validity_to, sorting, is_archived)
			VALUES (
				" . $GLOBALS["language"]['id'] . ",
				'" . $collection_setup_id . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['input_description']) . "',
				" . $input_registration . ",
				'" . $registration_contactform_id . "',
				" . time() . ",
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
				" . $input_validity_from . ",
				" . $input_validity_to . ",
                " . $sorting . ",
                " . $input_is_archived . "
			)";
        $inserted = TRUE;
    }

    if ($firstsave === FALSE && ($_REQUEST["input_description"] == '')) {
        $messages[] = "<div class=\"errorbox\">" . $translation->get("error_textkey_description") . "</div>\n";
        $error = TRUE;
    }
    if ($_REQUEST["input_collection_id"] == '' && ($collection_setup_id === NULL)) {
        $messages[] = "<div class=\"errorbox\">" . $translation->get("error_collection_choose_setup") . "</div>\n";
        $error = TRUE;
    }

    if (!$error) {

        @mysqli_query($GLOBALS['mysql_con'], $insertquery);

        if ($inserted == TRUE) {
            $input_id = mysqli_insert_id($GLOBALS['mysql_con']);
            // editXML($input_id, "INSERT");
            save_collection_tags();
            createMySydeLog('main_collection', $input_id, 'INSERT');
            if ($firstsave === FALSE) {
                $messages[] = '<div class="successbox">' . $translation->get("collection_msg_success1") . '</div>';
            }
        } else {

            // hinzufuegen eines collection links aus NICHT siteparts
            
            foreach ($_POST as $key => $val) {
                if (strpos($key, "input_collection_hidden_info_") !== FALSE) {
                    $errorArr = handle_standard_content($key, $val, $input_id);

                    if (!empty($errorArr)) {
                        $error = $errorArr["error"];
                        $message = $errorArr["messages"];
                    }
                    continue;
                }

                if (strpos($key, "collection_modul_input_") !== FALSE) {
                    handle_sitepart_content($key, $val, $input_id);
                    continue;
                }
            }
            if (!$error) {
                $messages[] = '<div class="successbox">' . $translation->get("collection_msg_success2") . '</div>';
            } else {
                $messages[] = $message;
            }
        }

        if (!$error) {
            $_REQUEST["input_collection_id"] = $input_id;

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



            $type_ids = explode(',', $_POST["select_mandant"]);
            if(!empty($type_ids) && gettype($type_ids) == 'array')  { 
                @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_mandant_link WHERE main_collection_id = '".$input_id."'");
                foreach($type_ids as $permission_type_id){
                    $query = "INSERT IGNORE INTO main_collection_mandant_link
                    (main_collection_id, main_mandant_id)
                    VALUES (
                        '" . $input_id ."',
                        '" .  $permission_type_id . "'
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
                @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_mandant_link WHERE main_collection_id = '".$input_id."' AND main_mandant_id = 0;");
            }





            $category_ids = $_POST['select_category'];
            $categorys = explode(',', $category_ids);
            if(!empty($categorys) && gettype($categorys) == 'array')  { 
                $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM knowledgecenter_collection_link WHERE main_collection_id='".$input_id."'");    
                foreach($categorys as $key => $category){
                    $query = "INSERT INTO knowledgecenter_collection_link
                    (main_collection_id, knowledgecenter_category_id)
                    VALUES (
                        '" .  $input_id . "',
                        '" . $category . "'
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
            
            saveCalendarSerial($input_id);

            if(!empty($websites) && gettype($websites) == 'array')  { 
                $deleteOldWebShow = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_web_show WHERE main_collection_id='".$input_id."'");    
                foreach($websites as $key => $website){
                    $query = "INSERT INTO main_collection_web_show
                    (main_site_id, main_collection_setup_id, main_collection_id)
                    VALUES (
                        " .  $website . ",
                        '" . $collection_setup_id . "',
                        '" . $input_id . "'
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                } 
            }

            // gruppen speichern
            $query = "SELECT id, default_active FROM main_collection_setup_group WHERE main_collection_setup_id = '" . $_REQUEST['main_collection_setup_id'] . "'";
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            $box = array();
            while ($box = @mysqli_fetch_assoc($result)) {
                $query_2 = "SELECT id, active FROM main_collection_group_link WHERE main_collection_setup_group_id = '" . $box["id"] . "' AND main_collection_id = '" . $input_id . "' LIMIT 1";
                $result_2 = @mysqli_query($GLOBALS['mysql_con'], $query_2);
                // echo 'num ';print_r(@mysqli_num_rows($result_2));echo $query_2.'<br>';
                // $arr_ind = "input_collection_group_" . $box["id"] . "_active";
                if (!empty($groups) && in_array($box['id'], $groups)) {
                    $active = '1';
                } else {
                    $active = '0';
                }
                if (@mysqli_num_rows($result_2) == 0) {
                    
                    $query_3 = "INSERT INTO main_collection_group_link SET
					main_collection_id = " . $input_id . ",
					main_collection_setup_group_id = " . $box["id"] . ",
					active = " . $active;
                    @mysqli_query($GLOBALS['mysql_con'], $query_3);
                   
                } else {
                    $row = @mysqli_fetch_assoc($result_2);
                    $result_3 = $row[0];
                    if ($active != $result_3["active"]) {
                        $query_3 = "UPDATE main_collection_group_link SET
						active = " . $active . " WHERE
						main_collection_id = " . $input_id . " AND
						main_collection_setup_group_id = " . $box["id"];
                        @mysqli_query($GLOBALS['mysql_con'], $query_3);
                        
                    }
                }
            }

            // Neue Sortierung speichern, wenn gewuenscht
            if ($_REQUEST['input_change_sorting'] == 1) {
                // nach oben schieben
                $query = "UPDATE main_collection SET sorting = 1 WHERE id = " . $input_id;
                @mysqli_query($GLOBALS['mysql_con'], $query);

                $query = "SELECT id from main_collection where id != '" . $input_id . "' and main_collection_setup_id = '" . $collection_setup_id . "' order by sorting asc";
                $result = @mysqli_query($GLOBALS['mysql_con'], $query);
                $sorting = 2;
                while ($row = @mysqli_fetch_assoc($result)) {
                    $query = "UPDATE main_collection SET sorting = " . $sorting . " WHERE id = " . $row['id'];
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                    $sorting++;
                }
            } elseif ($_REQUEST['input_change_sorting'] == 2) {
                // nach unten schieben
                $sorting = @mysqli_fetch_array(@mysqli_query($GLOBALS['mysql_con'], "SELECT MAX(sorting)+1 AS 'newsorting' FROM main_collection WHERE main_collection_setup_id = " . $collection_setup_id));
                $sorting = ($sorting["newsorting"] <> "") ? $sorting = $sorting["newsorting"] : $sorting = 1;

                $query = "UPDATE main_collection SET sorting = " . $sorting . " WHERE id = " . $input_id;
                @mysqli_query($GLOBALS['mysql_con'], $query);
            }

            edit_collection($input_id, $messages);
        } else {
            $input_collection = array();
            $query = "SELECT * FROM main_collection WHERE id = '" . $input_id . "' LIMIT 1";
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            if (@mysqli_num_rows($result) == 1) {
                $input_collection = @mysqli_fetch_array($result);
            }
            header('EDIT_ERROR: 1');
            $input_collection["description"] = $_REQUEST["input_description"];
            require_once("edit_collection_cardform.inc.php");
        }
    } else {
        $input_collection = array();
        $query = "SELECT * FROM main_collection WHERE id = '" . $input_id . "' LIMIT 1";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        if (@mysqli_num_rows($result) == 1) {
            $input_collection = @mysqli_fetch_array($result);
        }

        header('EDIT_ERROR: 1');
        $input_collection["description"] = $_REQUEST["input_description"];

        require_once("edit_collection_cardform.inc.php");
    }
}
function save_collection_frontend($firstsave = FALSE)
{
    // ini_set('display_errors', '1');
    // ini_set('display_startup_errors', '1');
    // error_reporting(E_ALL);
    require_once("collection_config.inc.php");
    global $collection_setup_id;
   
    if($_REQUEST["input_collection_id_frontend"] == NULL || $_REQUEST["input_collection_id_frontend"] == ''){
        $firstsave = TRUE;
    }else{
        $_REQUEST['input_collection_id'] = $_REQUEST["input_collection_id_frontend"];
    }
    
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $input_id = "";

    $input_registration = 0;
    $registration_contactform_id = 0;

    if ($input_registration == 1) {
        $registration_contactform_id = (int)$_POST['registration_contactform_id'];
    }

    $input_validity_from = datetosql($_POST["input_validity_from"]);
    $input_validity_to = datetosql($_POST["input_validity_to"]);

    $websites = array();
     

    $groups = array();
     

    //edit oder save
    if ($_REQUEST["input_collection_id"] <> '' && $firstsave === FALSE) {
         
        $insertquery = "UPDATE main_collection SET
				description = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST["input_description"]) . "',
				registration = " . $input_registration . ",
				registration_contactform_id = '" . $registration_contactform_id . "',
				validity_from = " . $input_validity_from . ",
				validity_to = " . $input_validity_to . ",
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user_frontend"]['id'] . "
				WHERE id = '" . $_REQUEST["input_collection_id"] . "' 
			LIMIT 1";
        $inserted = FALSE;
        $input_id = $_REQUEST["input_collection_id"];
        save_collection_tags();
        
    } else  {
        $sorting = @mysqli_fetch_array(@mysqli_query($GLOBALS['mysql_con'], "SELECT MAX(sorting)+1 AS 'newsorting' FROM main_collection WHERE main_collection_setup_id = '" . $collection_setup_id . "'"));
        $sorting = ($sorting["newsorting"] <> "") ? $sorting = $sorting["newsorting"] : $sorting = 1;

        $insertquery = "INSERT INTO main_collection
			(main_language_id, main_collection_setup_id, description, registration, registration_contactform_id, creation_date, modified_date, modified_user, validity_from, validity_to, sorting, active)
			VALUES (
				" . $GLOBALS["language"]['id'] . ",
				'" . $collection_setup_id . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['input_description']) . "',
				" . $input_registration . ",
				'" . $registration_contactform_id . "',
				" . time() . ",
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
				" . $input_validity_from . ",
				" . $input_validity_to . ",
				" . $sorting . ",
				0
			)";
        $inserted = TRUE;
    }
    
    if ($firstsave === FALSE && ($_REQUEST["input_description"] == '')) {
        $messages[] = "<div class=\"errorbox\">" . $translation->get("error_textkey_description") . "</div>\n";
        $error = TRUE;
    }
    if ($_REQUEST["input_collection_id"] == '' && ($collection_setup_id === NULL)) {
        $messages[] = "<div class=\"errorbox\">" . $translation->get("error_collection_choose_setup") . "</div>\n";
        $error = TRUE;
    }

    if (!$error) {
        
        @mysqli_query($GLOBALS['mysql_con'], $insertquery);
       
        if ($inserted == TRUE) {
            $input_id = mysqli_insert_id($GLOBALS['mysql_con']);
            // editXML($input_id, "INSERT");
            save_collection_tags();
            require_once(CMS_PATH.'admin/mysyde_log.php');
            createMySydeLog('main_collection', $input_id, 'INSERT');
            
            if ($firstsave === FALSE) {
                $messages[] = '<div class="successbox">' . $translation->get("collection_msg_success1") . '</div>';
            }
        }  
       
            // hinzufuegen eines collection links aus NICHT siteparts
          
            foreach ($_POST as $key => $val) {
                if (strpos($key, "input_collection_hidden_info_") !== FALSE) {
                    $errorArr = handle_standard_content($key, $val, $input_id);
                   
                    if (!empty($errorArr)) {
                        $error = $errorArr["error"];
                        $message = $errorArr["messages"];
                    }
                    continue;
                }

                if (strpos($key, "collection_modul_input_") !== FALSE) {
                    handle_sitepart_content($key, $val, $input_id);
                    continue;
                }
            }
            if (!$error) {
                $messages[] = '<div class="successbox">' . $translation->get("collection_msg_success2") . '</div>';
            } else {
                $messages[] = $message;
            }
         

        if (!$error) {
            
            $_REQUEST["input_collection_id"] = $input_id;

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



            $type_ids = explode(',', $_POST["select_mandant"]);
            if(!empty($type_ids) && gettype($type_ids) == 'array')  { 
                @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_mandant_link WHERE main_collection_id = '".$input_id."'");
                foreach($type_ids as $permission_type_id){
                    $query = "INSERT IGNORE INTO main_collection_mandant_link
                    (main_collection_id, main_mandant_id)
                    VALUES (
                        '" . $input_id ."',
                        '" .  $permission_type_id . "'
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
                @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_mandant_link WHERE main_collection_id = '".$input_id."' AND main_mandant_id = 0;");
            }




            $category_ids = $_POST['select_category'];
            $categorys = explode(',', $category_ids);
            if(!empty($categorys) && gettype($categorys) == 'array')  { 
                $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM knowledgecenter_collection_link WHERE main_collection_id='".$input_id."'");    
                foreach($categorys as $key => $category){
                    $query = "INSERT INTO knowledgecenter_collection_link
                    (main_collection_id, knowledgecenter_category_id)
                    VALUES (
                        " .  $input_id . ",
                        " . $category . "
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            } 
            saveCalendarSerial($input_id);
            
            if(!empty($websites) && gettype($websites) == 'array')  { 
                $deleteOldWebShow = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_web_show WHERE main_collection_id='".$input_id."'");    
                
                    foreach($websites as $key => $website){
                        $query = "INSERT INTO main_collection_web_show
                        (main_site_id, main_collection_setup_id, main_collection_id)
                        VALUES (
                            " .  $website . ",
                            '" . $collection_setup_id . "',
                            '" . $input_id . "'
                        )";
                        @mysqli_query($GLOBALS['mysql_con'], $query);
                    }
            
                
            }

            // gruppen speichern
            $query = "SELECT id, default_active FROM main_collection_setup_group WHERE main_collection_setup_id = '" . $_REQUEST['main_collection_setup_id'] . "'";
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            $box = array();
            while ($box = @mysqli_fetch_assoc($result)) {
                $query_2 = "SELECT id, active FROM main_collection_group_link WHERE main_collection_setup_group_id = '" . $box["id"] . "' AND main_collection_id = '" . $input_id . "' LIMIT 1";
                $result_2 = @mysqli_query($GLOBALS['mysql_con'], $query_2);
                // echo 'num ';print_r(@mysqli_num_rows($result_2));echo $query_2.'<br>';
                // $arr_ind = "input_collection_group_" . $box["id"] . "_active";
                if (!empty($groups) && in_array($box['id'], $groups)) {
                    $active = '1';
                } else {
                    $active = '0';
                }
                if (@mysqli_num_rows($result_2) == 0) {
                    
                    $query_3 = "INSERT INTO main_collection_group_link SET
					main_collection_id = " . $input_id . ",
					main_collection_setup_group_id = " . $box["id"] . ",
					active = " . $active;
                    @mysqli_query($GLOBALS['mysql_con'], $query_3);
                   
                } else {
                    $row = @mysqli_fetch_assoc($result_2);
                    $result_3 = $row[0];
                    if ($active != $result_3["active"]) {
                        $query_3 = "UPDATE main_collection_group_link SET
						active = " . $active . " WHERE
						main_collection_id = " . $input_id . " AND
						main_collection_setup_group_id = " . $box["id"];
                        @mysqli_query($GLOBALS['mysql_con'], $query_3);
                        
                    }
                }
            }

            $query = "UPDATE main_collection SET sorting = 1 WHERE id = " . $input_id;
            @mysqli_query($GLOBALS['mysql_con'], $query);

            $query = "SELECT id from main_collection where id != '" . $input_id . "' and main_collection_setup_id = '" . $collection_setup_id . "' order by sorting asc";
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            $sorting = 2;
            while ($row = @mysqli_fetch_assoc($result)) {
                $query = "UPDATE main_collection SET sorting = " . $sorting . " WHERE id = " . $row['id'];
                @mysqli_query($GLOBALS['mysql_con'], $query);
                $sorting++;
            }
             
            edit_collection($input_id, $messages, TRUE);
        } else {
            $input_collection = array();
            $query = "SELECT * FROM main_collection WHERE id = '" . $input_id . "' LIMIT 1";
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            if (@mysqli_num_rows($result) == 1) {
                $input_collection = @mysqli_fetch_array($result);
            }
            header('EDIT_ERROR: 1');
            $input_collection["description"] = $_REQUEST["input_description"];
            // require_once("frontend_creation_cardform.inc.php");
        }
    } else {
        $input_collection = array();
        $query = "SELECT * FROM main_collection WHERE id = '" . $input_id . "' LIMIT 1";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        if (@mysqli_num_rows($result) == 1) {
            $input_collection = @mysqli_fetch_array($result);
        }

        header('EDIT_ERROR: 1');
        $input_collection["description"] = $_REQUEST["input_description"];

        // require_once("frontend_creation_cardform.inc.php");
    }
}

function handle_sitepart_content($key, $value, $input_id)
{
    switch ($value) {
        case 'textcontent':
            collection_save_textcontent($key);
            break;
        case 'facebook':
            collection_save_facebook($key);
            break;

        case 'youtube':
            collection_save_youtube($key);
            break;
        case 'iframe':
            collection_save_iframe($key);
            break;
        case 'shop_item_preview':
            collection_save_shop_item_preview($key);
            break;
        case 'faq':
            save_faq_data($key, $input_id);
            break;
        case 'table':
            save_table_data($key, $input_id);    
            break;    
        case 'gallery':
            save_gallery_data($key, $input_id);    
            break;   
        case 'filegallery':
            save_filegallery_data($key, $input_id);    
            break;   
    }
}

function collection_save_textcontent($key)
{
    // pruefen ob header existiert und speichern
    $setup_line_id = substr($key, strlen("collection_modul_input_"));
    $collection_link = get_collection_link($_REQUEST['input_collection_id'], $setup_line_id);
    if (is_array($collection_link)) {
        // update
        $query = "UPDATE textcontent_header SET
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
				content = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_textcontent_text_' . $setup_line_id]) . "', 
				type = 0
				WHERE id = " . $collection_link['main_sitepart_header_id'] . " 
			LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    } else {
        // insert
        $query = "INSERT INTO textcontent_header
			(main_language_id, description, modified_date, modified_user, type, content, collection_header)
			VALUES (
				'" . $GLOBALS["language"]['id'] . "',
				'',
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
				0,
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_textcontent_text_' . $setup_line_id]) . "',
				1
			)";


        @mysqli_query($GLOBALS['mysql_con'], $query);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
		VALUES (
			'" . $_REQUEST['input_collection_id'] . "',
			" . $setup_line_id . ",
			" . $header_id . ",
			1
		)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function collection_save_facebook($key)
{
    // pruefen ob header existiert und speichern
    $setup_line_id = substr($key, strlen("collection_modul_input_"));
    $collection_link = get_collection_link($_REQUEST['input_collection_id'], $setup_line_id);

    $input_show_faces = ($_POST["module_input_facebook_show_faces_" . $setup_line_id] == "on") ? 1 : 0;
    $input_show_posts = ($_POST["module_input_facebook_show_posts_" . $setup_line_id] == "on") ? 1 : 0;

    if (is_array($collection_link)) {
        $query = "UPDATE facebook_header SET
				description = '',
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
				width = '" . (int)$_REQUEST["module_input_facebook_width_" . $setup_line_id] . "', 
				height = '" . (int)$_REQUEST["module_input_facebook_height_" . $setup_line_id] . "', 
				show_faces = " . $input_show_faces . ", 
				show_posts = " . $input_show_posts . ", 
				url = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST["module_input_facebook_url_" . $setup_line_id]) . "'
				WHERE id = " . $collection_link['main_sitepart_header_id'] . " 
			LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    } else {
        $query = "INSERT INTO facebook_header
			(main_language_id, description, modified_date, modified_user, width, height, show_faces, show_posts, url, collection_header)
			VALUES (
				" . (int)$GLOBALS["language"]['id'] . ",
				'',
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
				'" . (int)$_REQUEST["module_input_facebook_width_" . $setup_line_id] . "',
				'" . (int)$_REQUEST["module_input_facebook_height_" . $setup_line_id] . "',
				" . $input_show_faces . ",
				" . $input_show_posts . ",
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST["module_input_facebook_url_" . $setup_line_id]) . "',
				1
			)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
		VALUES (
			'" . $_REQUEST['input_collection_id'] . "',
			" . $setup_line_id . ",
			" . $header_id . ",
			9
		)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function collection_save_youtube($key)
{
    // pruefen ob header existiert und speichern
    $setup_line_id = substr($key, strlen("collection_modul_input_"));
    $collection_link = get_collection_link($_REQUEST['input_collection_id'], $setup_line_id);
    $youtube_id = "";

    preg_match(
        '/[\\?\\&]v=([^\\?\\&]+)/',
        $_REQUEST["module_input_youtube_url_" . $setup_line_id],
        $matches
    );
    if (isset($matches[1])) {
        $youtube_id = $matches[1];
    }

    if (is_array($collection_link)) {
        $query = "UPDATE youtube_header SET
				description = '',
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
				width = '" . (int)$_REQUEST["module_input_youtube_width_" . $setup_line_id] . "', 
				height = '" . (int)$_REQUEST["module_input_youtube_height_" . $setup_line_id] . "', 
				url = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST["module_input_youtube_url_" . $setup_line_id]) . "',
				youtube_id = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $youtube_id) . "'
				WHERE id = " . $collection_link['main_sitepart_header_id'] . " 
			LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    } else {
        $query = "INSERT INTO youtube_header
			(main_language_id, description, modified_date, modified_user, width, height, url, youtube_id, collection_header)
			VALUES (
				" . (int)$GLOBALS["language"]['id'] . ",
				'',
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
				'" . (int)$_REQUEST["module_input_youtube_width_" . $setup_line_id] . "',
				'" . (int)$_REQUEST["module_input_youtube_height_" . $setup_line_id] . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST["module_input_youtube_url_" . $setup_line_id]) . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $youtube_id) . "',
				1
			)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
		VALUES (
			'" . $_REQUEST['input_collection_id'] . "',
			" . $setup_line_id . ",
			" . $header_id . ",
			10
		)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function collection_save_iframe($key)
{
    // pruefen ob header existiert und speichern
    $setup_line_id = substr($key, strlen("collection_modul_input_"));
    $collection_link = get_collection_link($_REQUEST['input_collection_id'], $setup_line_id);

    if (is_array($collection_link)) {
        $query = "UPDATE iframe_header SET
				description = '',
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
				width = '" . (int)$_REQUEST["module_input_iframe_width_" . $setup_line_id] . "', 
				height = '" . (int)$_REQUEST["module_input_iframe_height_" . $setup_line_id] . "', 
				url = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], addhttp($_REQUEST["module_input_iframe_url_" . $setup_line_id])) . "'
				WHERE id = " . $collection_link['main_sitepart_header_id'] . " 
			LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    } else {
        $query = "INSERT INTO iframe_header
			(main_language_id, description, modified_date, modified_user, width, height, url, collection_header)
			VALUES (
				'" . $GLOBALS["language"]['id'] . "',
				'',
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
				'" . (int)$_REQUEST["module_input_iframe_width_" . $setup_line_id] . "',
				'" . (int)$_REQUEST["module_input_iframe_height_" . $setup_line_id] . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], addhttp($_REQUEST["module_input_iframe_url_" . $setup_line_id])) . "',
				1
			)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
		VALUES (
			'" . $_REQUEST['input_collection_id'] . "',
			" . $setup_line_id . ",
			" . $header_id . ",
			11
		)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function collection_save_shop_item_preview($key)
{
    // pruefen ob header existiert und speichern
    $setup_line_id = substr($key, strlen("collection_modul_input_"));
    $collection_link = get_collection_link($_REQUEST['input_collection_id'], $setup_line_id);

    if (is_array($collection_link)) {
        $query    = "UPDATE main_shop_item_preview SET
				description = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_description_' . $setup_line_id]) . "',
				no_of_items = '" . (int)$_REQUEST["module_input_no_of_items_" . $setup_line_id] . "',
				category_code_string = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_category_code_string_' . $setup_line_id]) . "',
				item_no_string = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_item_no_string_' . $setup_line_id]) . "',
				modified_date = FROM_UNIXTIME (" . time() . "),
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . "
				WHERE id = " . $collection_link['main_sitepart_header_id'] . " 
			LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    } else {
        $query    = "INSERT INTO main_shop_item_preview
			(main_language_id, description, no_of_items, category_code_string, item_no_string, modified_date, modified_user)
			VALUES (
				'" . $GLOBALS["language"]['id'] . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_description_' . $setup_line_id]) . "',
				'" . (int)$_REQUEST["module_input_no_of_items_" . $setup_line_id] . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_category_code_string_' . $setup_line_id]) . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_REQUEST['module_input_item_no_string_' . $setup_line_id]) . "',
				FROM_UNIXTIME (" . time() . "),
				" . (int)$GLOBALS["admin_user"]['id'] . "
			)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
		VALUES (
			'" . $_REQUEST['input_collection_id'] . "',
			" . $setup_line_id . ",
			" . $header_id . ",
			14
		)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function handle_standard_content($key, $value, $input_id)
{
    $collection_setup_content = substr($key, strlen("input_collection_hidden_info_"));
    $postValue = '';
    // $postValue = $_REQUEST['input_collection_link_' . $collection_setup_content];
    if(isset($_POST['input_collection_contact_linked_'.$collection_setup_content])){
        $postValue = $_REQUEST['input_collection_contact_linked_' . $collection_setup_content];
    }
    else{
        $postValue = $_REQUEST['input_collection_link_' . $collection_setup_content];
    }
    $linkText = '';
    $sitepart_header_id = '';
    $type_id = $_REQUEST['input_collection_hidden_info_' . $collection_setup_content];
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $newlink = TRUE;
    $query = "SELECT * FROM main_collection_link WHERE main_collection_id = '" . $input_id . "' AND main_collection_setup_content_id = '" . (int)$collection_setup_content . "'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $linkData = array();
    if (@mysqli_num_rows($result) == 1) {
        $newlink = FALSE;
        $linkData = @mysqli_fetch_array($result);
    }

    // einzelnes bild entfernen, falls checkbox gesetzt
    if (isset($_POST['delete_collection_image_' . $collection_setup_content]) && $_POST['delete_collection_image_' . $collection_setup_content] == "on") {
        delete_collection_image($linkData['data']);
        $linkData['data'] = "";
    }

    $options = array();
    $query = "SELECT * FROM main_collection_setup_content WHERE id = '" . (int)$collection_setup_content . "'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $row = @mysqli_fetch_array($result);
        $options = unserialize($row['options']);
    }
    switch ($type_id) {

        case 4: //link
            // $postValue = addhttp($postValue);
            $sitepart_header_id = ($_POST["input_collection_link_target_". $collection_setup_content] == "on") ? 1 : 0;
            $linkText = $_REQUEST['input_collection_link_text_' . $collection_setup_content];
            break;
        case 5: // bild
            // $postValue = $linkData['data'];
            break;
        case 6: //Dropdown

            $serialized = serialize($postValue);
            $postValue = $serialized;
            break;
        case 7: //checkbox
            $checked_values = array();

            $postValue = $_POST['input_collection_link_' . $collection_setup_content];
             $postValue = implode(';',explode(',', $postValue ));
             
            // if(!empty($_POST)){
            //     $postValue = "";
            //     $box = '1';
            //     foreach($_POST['input_collection_link_' . $collection_setup_content] as $value) {
            //         $postValue = 1;
            //         $box .= "Checked:";
            //     }
            // } 
            // $i = 1;
            //  foreach($postValue as $check) {
            //      if($check == 'on') {
            //          $checked_values += [$i => 'on'];
            //      }
            //      $i++;
            //  }


            //$serialized_check = serialize($checked_values);
            


            // print_r($serialized_check);
            // $postValue = 'a';
            break;
        case 8888:
            add_to_preview($key, $value, $input_id, $postValue);   
        case 8889:
            add_contact_to_collection($key, $value, $input_id, $postValue);
            break   ;     
        default:
            // nichts machen
            break;
    }



    if (!$error) {

        if ($newlink === FALSE) {
            $query = "  UPDATE main_collection_link SET data = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $postValue) . "', linkText = '".$linkText."', main_sitepart_header_id = '".$sitepart_header_id."' WHERE main_collection_id = '" . $input_id . "'  AND main_collection_setup_content_id = '" . (int)$collection_setup_content . "'";
        } else {
            $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id, data, linkText)
			VALUES (
				'" . $input_id . "',
				'" . (int)$collection_setup_content . "',
				'".$sitepart_header_id."',
				0,
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $postValue) . "',
				'".$linkText."'
			)
		";
        }
        @mysqli_query($GLOBALS['mysql_con'], $query);
    } else {
        header('EDIT_ERROR: 1');
        return array('messages' => $messages, 'error' => $error);
    }
}


function add_contact_to_collection($key, $value, $input_id, $postValue){
    $key = substr($key, strlen("input_collection_hidden_info_"));
    $query = "SELECT * FROM main_collection_contact_linked where main_collection_id = ".$input_id.' AND field_id = '.$key.' LIMIT 1';
    $result =  @mysqli_query($GLOBALS['mysql_con'], $query);
    $receiver_email = '';
    if(isset($_POST['receiver_email'.$key]) && $_POST['receiver_email'.$key]  != NULL){
        $receiver_email = $_POST['receiver_email'.$key];
    }
    $receiver_name = '';
    if(isset($_POST['receiver_name'.$key]) && $_POST['receiver_name'.$key]  != NULL){
        $receiver_name = $_POST['receiver_name'.$key];
    }

    $header_id = '';
    if(isset($_POST['header_id'.$key]) && $_POST['header_id'.$key]  != NULL){
        $header_id = $_POST['header_id'.$key];
    }

    $queryLinked = '';
    if (@mysqli_num_rows($result)  > 0) {
        $row = @mysqli_fetch_array($result);
        $queryLinked =  "UPDATE main_collection_contact_linked SET
                        main_collection_id = '" . $input_id . "',
                        field_id = ".$key.",
                        header_id = " . $header_id . ",
                        receiver_email = '" . $receiver_email . "',
                        receiver_name = '" . $receiver_name . "'
                        WHERE id = '" . $row["id"] . "' 
                        LIMIT 1";
    }else{
        $queryLinked = "INSERT INTO main_collection_contact_linked
			(main_collection_id, field_id, header_id, receiver_email, receiver_name)
			VALUES (
				" . $input_id . ",
				'" . $key . "',
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $header_id) . "',
				'" . $receiver_email . "',
				'" . $receiver_name . "'
				 
			)";
    }
     
    if(isset($_POST['receiver_email'.$key]) && $_POST['receiver_email'.$key]  != NULL){
        @mysqli_query($GLOBALS['mysql_con'], $queryLinked);
    }

}

function delete_collection() {
    global $collection_setup_id;

    if ($_REQUEST["input_collection_id"] <> '') {
        $query = "DELETE FROM main_collection WHERE id = '" . $_REQUEST["input_collection_id"] . "' LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);

        $query = "DELETE FROM main_collection_link WHERE main_collection_id = '" . $_REQUEST["input_collection_id"] . "'";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        createMySydeLog('main_collection', $_REQUEST["input_collection_id"], 'DELETE');

        if($_POST["input_readable"] == "on"){
            $query = "DELETE FROM main_collection_read WHERE main_collection_id = " . $_REQUEST["input_collection_id"];
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }

        $query = "DELETE FROM main_collection_mandant_link WHERE main_collection_id = " . $_REQUEST["input_collection_id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
        delete_knowledgecenter($_REQUEST["input_collection_id"]);
    }
    
    require_once("edit_collection_listform.inc.php");
}

function create_collection_input_field($fieldSetup, $collectionData) {
    //Übersetzung anzeigen
    $translation   = \DynCom\mysyde\common\classes\Registry::get("translation");
    //Pflichtfeld einblenden wenn vorhanden
    if (isset($fieldSetup['mandatory']) && $fieldSetup['mandatory'] != 0) {
        $mandatory = "<span class=\"mandatory\"> *</span>";
    }

    $class_current = 'current';
    $class_active = 'active';
    
    echo "<div class='collection_field ".$class_current." ".$fieldSetup['code']."'>";
    echo "<div onclick='btnClicked(this)' class=\"label\"><label for=\"" . $fieldSetup['code'] . "\">" . $fieldSetup['fieldname'] . $mandatory . "</label></div>";
    echo "	<div class='input ".$class_active."'>";
    // echo "<div class=customer_help>";
    // echo "<div class=customer_help_content>";
    // echo $translation->get("customer_help".$fieldSetup['type_id']);
    // echo "</div>";
    // echo "</div>";
    //Hinweis einblenden wenn vorhanden
    if (isset($fieldSetup['note']) && $fieldSetup['note'] != '') {
        echo  "<div class=\"input_note\">" . $translation->get("note") . ": " . $fieldSetup['note'] . "</div>";
    }

    if ($fieldSetup['fieldtype'] == 'siteparts') {
        $siteparts = \DynCom\mysyde\common\classes\Siteparts::get();
        $sitepartConfig = $siteparts[$fieldSetup['type_id']];
        $headerData = get_sitepart_header_data($collectionData['id'], $fieldSetup['id']);
        require(MODULE_PATH . $sitepartConfig['folder'] . "/collection_" . $sitepartConfig['code'] . "_line_listform.inc.php");
    } else {

        // vorhandenen value auslesen
        $data = '';
        $linkText = '';
        $sitepart_header_id = '';
        $query = "SELECT data, linkText, main_sitepart_header_id FROM main_collection_link WHERE main_collection_setup_content_id = " . $fieldSetup['id'] . " AND main_collection_id = " . $collectionData['id'];
         
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        if (@mysqli_num_rows($result) == 1) {
            $row = @mysqli_fetch_array($result);
            $data = $row['data'];
            $linkText = $row['linkText'];
            $sitepart_header_id = $row['main_sitepart_header_id'];
        }

        echo "<form id=\"form_collection_input_" . $fieldSetup['id'] . "\" method=\"post\" name=\"form_collection_input_" . $fieldSetup['id'] . "\">";
        echo "<input type=\"hidden\" name=\"input_collection_hidden_info_" . $fieldSetup['id'] . "\" value=\"" . $fieldSetup['type_id'] . "\" />";

        if ($fieldSetup['type_id'] != 2) {
            $input_maxlength = 255;
        }

        if (isset($fieldSetup['input_maxlength']) && $fieldSetup['input_maxlength'] != 0) {
            $input_maxlength = $fieldSetup['input_maxlength'];
        }

        switch ($fieldSetup['type_id']) {

            case 2: // textarea
                echo "<textarea id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"normal\" maxlength=\"" . $input_maxlength . "\" name=\"input_collection_link_" . $fieldSetup['id'] . "\">" . $data . "</textarea>";
                break;

            case 3: // datumsfeld
                echo "<input type='date' id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"code datepicker\" type=\"text\" value=\"" . $data . "\" maxlength=\"255\" name=\"input_collection_link_" . $fieldSetup['id'] . "\">";
                break;
            case 10: // Uhrzeitfeld
                echo "<input type='time' id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"code\" type=\"text\" value=\"" . $data . "\" maxlength=\"255\" name=\"input_collection_link_" . $fieldSetup['id'] . "\">";
                break;
            case 4: // link
                ?>
                    <div class='link_url_group'><?= input($translation->get("link_url"), "input_collection_link_" . $fieldSetup['id'], "text", $data, 255);?></div>
                    <div class='link_text_group'><?= input($translation->get("link_text"), "input_collection_link_text_" . $fieldSetup['id'], "text", $linkText, 255);?></div>
                    <div class='link_target_group'><?= input($translation->get("open_in_new_tab"),"input_collection_link_target_" . $fieldSetup['id'], "checkbox",$sitepart_header_id);?></div>
                <?php
                break;

            case 5: // einzelnes bild oder video
                if(isset($_SESSION['login_id'])){
                    input("", "input_collection_link_".$fieldSetup['id'], "file", $data);
                }else{
                    echo '<ul class="toolbar_menu">';
                    input("", "input_collection_link_".$fieldSetup['id'], "hidden", $data);
                    button("new", $translation->get("new"), $formname, "openGallery('input_collection_link_".$fieldSetup['id']."', 'collection_image_".$fieldSetup['id']."','collection', 'single')", "", FALSE);
                    button("delete", $translation->get("delete"), $formname, "delete_collection_image('input_collection_link_".$fieldSetup['id']."', 'collection_image_".$fieldSetup['id']."')", "", FALSE);
                    echo '</ul>';
                    $video_erweiterungen = array('mp4', 'avi', 'mkv', 'mov', 'wmv');
                    $dateierweiterung = strtolower(pathinfo($data, PATHINFO_EXTENSION));
                    if(in_array($dateierweiterung, $video_erweiterungen)){
                        echo "<img class='icon' alt='Inhalt auswählen' id='collection_image_".$fieldSetup['id']."' src='/layout/admin/img/icons/video_placeholder.png'>";
                    } elseif ($data !== "") {
                        echo "<img class='icon' alt='Inhalt auswählen' id='collection_image_".$fieldSetup['id']."' src='/userdata/".$data."?time=".time()."'>";
                    }else{
                        echo "<img class='icon' alt='Inhalt auswählen' id='collection_image_".$fieldSetup['id']."' src='/layout/admin/img/icons/placeholder_image.jpg'>";
                    }
                }
                break;

            case 6: // Dropdown
                echo "<select style=\"float:left;\" id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"code\" type=\"text\" name=\"input_collection_link_" . $fieldSetup['id'] . "\" >";
                //Get all option_values
                $options = explode(";", $fieldSetup["option_string"]);
                //Values als Integer
                $value = 0;
                $data = unserialize($data);
                foreach ($options as $option) {
                    $selected_text = ($data == $value) ? " selected=\"selected\"" : "";
                    echo "<option" . $selected_text . " value=\"" . $value . "\">" . $option . "</option>";
                    $value++;
                }
                echo "</select>";

                if ($fieldSetup['id'] == 38 || $fieldSetup['id'] == 45 || $fieldSetup['id'] == 57) {
                    echo "<div class=\"dropdownPreview\" data-image=\"" . $fieldSetup['id'] . "\" style=\"float:left\" >dsadas</div>";
                }
                break;

            case 7: // Checkbox
                create_checkbox($fieldSetup, $data);
                break;
            case 666: // connected_form
                load_connected_form($fieldSetup['id'], $data);  
                break;
            case 8888: // Kollektion in Kollektion
                echo "<input type=\"hidden\" name=\"input_collection_hidden_info_" . $fieldSetup['id'] . "\" value=\"" . $fieldSetup['type_id'] . "\" />";
                echo "<input type=\"hidden\" name=\"input_collection_preview_" . $fieldSetup['id'] . "\" value=\"" . $fieldSetup['type_id'] . "\" />";
                loadCollectionsForCollections($fieldSetup['id'], $collectionData['id']);  
                break;
            case 8889:
                echo "<input type=\"hidden\" name=\"input_collection_contact_linked_" . $fieldSetup['id'] . "\" value=\"" . $fieldSetup['type_id'] . "\" />";
                load_collection_contactform($fieldSetup, $collectionData);
            break;    
            case 1: // normales inputfeld
            default:
                echo "<input id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"code\" type=\"text\" value=\"" . htmlspecialchars($data) . "\" maxlength=\"" . $input_maxlength . "\" name=\"input_collection_link_" . $fieldSetup['id'] . "\">";
                break;
            case 8: // icon dropdown
                getCollectionIcons($fieldSetup, $data, $collectionData['main_collection_setup_id']);
                break;
            case 9: // contact dropdown
                if($fieldSetup['code'] == 'select_multi_contact'){
                    create_contact_select($data, $fieldSetup['id']);
                }else{
                    create_contact_select($data, $fieldSetup['id']);
                }
        }
        echo "</form>";
    }

    echo "	</div>";
    echo "</div>";
}

function load_connected_form($field_id, $data){
    $query = "SELECT * FROM contactform_header";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

    echo "<select style=\"float:left;\" id=\"input_collection_link_" . $field_id . "\" class=\"code\" type=\"text\" name=\"input_collection_link_" . $field_id . "\" >";
    echo "<option value=''>---</option>";
    while($row = @mysqli_fetch_array($result)){
        $selected = '';
        if($data == $row['id']){
            $selected = "selected";
        }
        echo "<option ".$selected." value='".$row['id']."'>".$row['description']."</option>";
    }
    echo "</select>";
}

function load_collection_contactform($fieldSetup, $collectionData){
    $query = "SELECT * FROM main_collection_contact_linked WHERE main_collection_id = ".$collectionData['id']." AND field_id = ".$fieldSetup['id'];
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $dataLinked = @mysqli_fetch_array($result);
    require(MODULE_PATH . "collection/collection_contact_form_option.inc.php");
}
function create_checkbox($fieldSetup, $data){
    load_multiJSfiles();
        $preselect  = array();
        if($data != NULL && $data != ''){
            $preselect = explode(';', $data);
        } 
        
            echo "<label id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"checkbox\" >";
                        //Get all option_values
                        $options = explode(";", $fieldSetup["option_string"]);
                        //Values als Integer
                        $value = $data;?>
                        <div class="full-block">
                                
                                <div class="input_collection_link_<?=$fieldSetup['id'];?> bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
                                    <input type="hidden" name="input_collection_link_<?=$fieldSetup['id'];?>"  >
                                    <i class="dropdown icon"></i>
                                    <div class="default text">---</div>
                                    <div class="menu">
                                        <?                
                                            foreach ($options as $option) {
                                                echo "<div class=\"item\" data-value=\"{$option}\">".$option."</div>";
                                                //$selected_text = ($data == $value) ? " selected=\"selected\"" : "";
                                                
                                                }
                                            
                                        ?>
                                    </div>
                                </div>
                        </div>
                    <? echo "</label>";  
                    initializeMultiSelect("input_collection_link_".$fieldSetup['id'], $preselect );
}
function initializeMultiSelect ($fieldName, $preselect = array()){
?>
            <script>
                    var $y = jQuery.noConflict();

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

            </script>
<?            
}
function load_multiJSfiles(){?>
                <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')?>">
                

<?}

function get_sitepart_header_data($collection_id, $setup_content_id)
{
    $siteparts = \DynCom\mysyde\common\classes\Siteparts::get();

    $collection_link = get_collection_link($collection_id, $setup_content_id);
    if (!is_array($collection_link)) {
        return array();
    }

    if ($collection_link['main_sitepart_id'] == 0) {
        return array();
    }

    $query = "SELECT * FROM " . $siteparts[$collection_link['main_sitepart_id']]['header_table'] . " WHERE id = " . $collection_link['main_sitepart_header_id'];
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $row = @mysqli_fetch_array($result);
        return $row;
    }

    return array();
}

function moveup_line_collection()
{
    move_line_collection("<", "DESC", $_POST["input_line_id"]);
}

function movedown_line_collection()
{
    move_line_collection(">", "ASC", $_POST["input_line_id"]);
}

function move_line_collection($way, $order, $pic_id)
{
    $query = "SELECT * FROM main_collection_content WHERE id = '" . $pic_id . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_pic = @mysqli_fetch_array($result);
    }
    $query = "SELECT * FROM main_collection_content WHERE main_collection_id = " . $curr_pic['main_collection_id'] . " AND sorting " . $way . " " . $curr_pic["sorting"] . " ORDER BY sorting " . $order . " LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $change_pic = @mysqli_fetch_array($result);
    }
    if (($curr_pic["id"] <> '') && ($change_pic["id"] <> '')) {
        $query = "UPDATE main_collection_content SET sorting = " . $change_pic["sorting"] . " WHERE id = " . $curr_pic["id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $query = "UPDATE main_collection_content SET sorting = " . $curr_pic["sorting"] . " WHERE id = " . $change_pic["id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function collection_link_exists($collection_id, $setup_content_id)
{
    $query = "SELECT id FROM main_collection_link WHERE main_collection_id = '" . $collection_id . "' AND main_collection_setup_content_id = '" . $setup_content_id . "'";
    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 0) {
        return FALSE;
    } else {
        return TRUE;
    }
}

function get_collection_link($collection_id, $setup_content_id)
{
    $query = "SELECT * FROM main_collection_link WHERE main_collection_id = '" . $collection_id . "' AND main_collection_setup_content_id = '" . $setup_content_id . "'";
    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    return $row;
}

function delete_collection_image($filename)
{

    if (file_exists(PATH_ORIGINAL_PICTURE_COLLECTION . $filename) && !empty($filename)) {
        unlink(PATH_ORIGINAL_PICTURE_COLLECTION . $filename);
    }
    if (file_exists("../.." . PATH_ICON_COLLECTION . $filename) && !empty($filename)) {
        unlink("../.." . PATH_ICON_COLLECTION . $filename);
    }
    if (file_exists(PATH_RESIZE_COLLECTION . $filename) && !empty($filename)) {
        unlink(PATH_RESIZE_COLLECTION . $filename);
    }
}

function collection_filter($site_id, $language_id)
{
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    echo "<div class=\"input\"><select onchange=\"filter_collection();\" class=\"bigselect\" name=\"collection_filter\" id=\"collection_filter\">";
    echo "<option value=''>" . $translation->get("show_all") . "</option>";
    collection_filter_rek($site_id, $language_id);
    echo "</select>";
    echo "</div>";
}

function collection_filter_rek($site_id, $language_id)
{
    $result = @mysqli_query($GLOBALS['mysql_con'], "SELECT * FROM main_collection_setup WHERE (main_language_id = " . $language_id . " OR all_languages = 1) ORDER BY id ASC");
    if (@mysqli_num_rows($result) > 0) {
        while ($nav = @mysqli_fetch_array($result)) {
            $active = "";
            if (isset($_REQUEST['filter_id']) && $_REQUEST['filter_id'] == $nav['id']) {
                $active = 'selected="selected"';
            }
            echo "\n<option " . $active . " value=\"" . $nav["id"] . "\">" . $nav["description"] . "</option>";
        }
    }
    return TRUE;
}

/**
 * moveup_pic() Bild nach oben
 *
 * @return
 */
function moveup_collection()
{
    move_collection("<", "DESC", $_POST["input_collection_id"]);
}

/**
 * movedown_pic() Bild nach unten
 *
 * @return
 */
function movedown_collection()
{
    move_collection(">", "ASC", $_POST["input_collection_id"]);
}

/**
 * move_pic() Soprtierung der Galerieeintraege
 *
 * @param mixed $way
 * @param mixed $order
 * @param mixed $pic_id
 *
 * @return
 */
function move_collection($way, $order, $pic_id)
{
    $query = "SELECT main_collection_setup_id FROM main_collection WHERE id = '" . $pic_id . "'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);

    $main_collection_setup_id = $row['main_collection_setup_id'];

    $query = "SELECT * FROM main_collection WHERE id = '" . $pic_id . "' LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $curr_pic = @mysqli_fetch_array($result);
    }
    $query = "SELECT * FROM main_collection WHERE main_collection_setup_id = '" . $main_collection_setup_id . "' AND sorting " . $way . " " . $curr_pic["sorting"] . " ORDER BY sorting " . $order . " LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $change_pic = @mysqli_fetch_array($result);
    }
    if (($curr_pic["id"] <> '') && ($change_pic["id"] <> '')) {
        $query = "UPDATE main_collection SET sorting = " . $change_pic["sorting"] . " WHERE id = " . $curr_pic["id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $query = "UPDATE main_collection SET sorting = " . $curr_pic["sorting"] . " WHERE id = " . $change_pic["id"];
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function create_collection_tags(){
    $collection_id = $_POST['input_collection_id'];

    $query = "SELECT * FROM main_collection_tag WHERE main_collection_id = '" . $collection_id . "'";
    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    $tags = array();
    while($row = @mysqli_fetch_array($result)){
        array_push($tags,$row['code']);
    }

    $tags = implode(', ', $tags);

    input("Tags", "input_tags", "text", $tags, 999);
}

function save_collection_tags(){
    $collection_id = $_POST['input_collection_id'];
    $tags = $_POST['input_tags'];
    $tags = explode(', ', $tags);

    $stmt = mysqli_prepare($GLOBALS["mysql_con"], "DELETE FROM main_collection_tag WHERE main_collection_id = ?");
    mysqli_stmt_bind_param($stmt, "i", $collection_id);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    $stmt = mysqli_prepare($GLOBALS["mysql_con"], "INSERT INTO main_collection_tag (main_collection_id, code) VALUES (?, ?)");
    mysqli_stmt_bind_param($stmt, "is", $collection_id, $tag);

    foreach($tags as $key => $tag){
        mysqli_stmt_execute($stmt);
    }

    mysqli_stmt_close($stmt);
}


function create_collection_groups_select($input_collection){
    $translation   = \DynCom\mysyde\common\classes\Registry::get("translation");


    $collection_id = $_POST['input_collection_id'];
    $setup_id = $input_collection['main_collection_setup_id'];

    $query = "SELECT * FROM main_collection_setup_group WHERE main_collection_setup_id = '" . $setup_id . "'";
    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 0) {
        return;
    }

    $preselect = array();
    $query2 = "SELECT * FROM main_collection_group_link WHERE main_collection_id = '" . $collection_id . "' AND active = 1";
    $result2 = mysqli_query($GLOBALS['mysql_con'], $query2);

    while($row2 = @mysqli_fetch_array($result2)){
        array_push($preselect,$row2['main_collection_setup_group_id']);
    }

    ?>
     <div class="label"><?php echo $translation->get("collection_groups"); ?></div>
            <div class="groups bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
                <input type="hidden" name="select_group">
                <i class="dropdown icon"></i>
                <div class="default text"><?php echo $translation->get("collection_groups"); ?></div>
                <div class="menu">
                    <?  
                        
                    
                        while($row = @mysqli_fetch_array($result)) {
                            echo "<div class=\"item\" data-value=\"{$row['id']}\">".$row["description"]."</div>";
                        }
                      
                    ?>
                </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('.groups.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
                    });


        </script>
    <? }
/**
     * Copy collections
     *
     * @return bool
     */
function copy_collection($addCopySuffix = TRUE) {
        $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
        $siteparts = \DynCom\mysyde\common\classes\Siteparts::get();
        $setupId = $_POST['main_collection_setup_id'];
        $query = 'SELECT * FROM main_collection_setup WHERE id ="'.$setupId.'" LIMIT 1';
        $result =  @mysqli_query($GLOBALS['mysql_con'], $query);
        $setup = @mysqli_fetch_array($result);
        $languageId = $setup['main_language_id'];
         

        $collection_id = $_POST['input_collection_id'];

        $table = "main_collection";
        $columns = get_column_names_to_copy($table);

        $query = "SELECT * FROM $table WHERE  id = ".$collection_id;
        if($setupId != "") {
            $query .= " AND main_collection_setup_id = '" . $setupId."'";
        }

        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        while($row = mysqli_fetch_array($result)) {
            $finalColumns = $columns;
            $finalColumns['main_collection_setup_id'] = $setupId;
            if($row['registration_contactform_id'] > 0) {
                $finalColumns['registration_contactform_id'] = get_new_id($row['registration_contactform_id'], 'contactform_header');
            }
            if($addCopySuffix) {
                $finalColumns['description'] = "CONCAT(description, ' (" . $translation->get("copy") . ")')";
            }

            $query = "INSERT INTO $table
                            SELECT " . join(", ", $finalColumns) . " FROM $table
                            WHERE id = " . $row['id'];
                           
            @mysqli_query($GLOBALS['mysql_con'], $query);
            $newId = mysqli_insert_id($GLOBALS['mysql_con']);

            insert_copy_link($row['id'], $newId, $table);

            // collection group link kopieren
            $collectionGroupLinkColumns = get_column_names_to_copy("main_collection_group_link");
            $query = "SELECT * FROM main_collection_group_link WHERE main_collection_id = " . $row['id'];
            $lineResult = @mysqli_query($GLOBALS['mysql_con'], $query);
            while($lineRow = mysqli_fetch_array($lineResult)) {
                $finalLineColumns = $collectionGroupLinkColumns;
                $finalLineColumns["main_collection_id"] = $newId;
                $finalLineColumns["main_collection_setup_group_id"] = get_new_id($lineRow['main_collection_setup_group_id'], 'main_collection_setup_group');

                $query = "INSERT INTO main_collection_group_link 
                            SELECT " . join(", ", $finalLineColumns) . " FROM main_collection_group_link 
                            WHERE id = " . $lineRow['id'];
                @mysqli_query($GLOBALS['mysql_con'], $query);
                $newLineId = mysqli_insert_id($GLOBALS['mysql_con']);

                insert_copy_link($lineRow['id'], $newLineId, "main_collection_group_link");
            }

            // collection web show kopieren
            $collectionWebShowColumns = get_column_names_to_copy("main_collection_web_show");
            $query = "SELECT * FROM main_collection_web_show WHERE main_collection_id = " . $row['id'];
            $lineResult = @mysqli_query($GLOBALS['mysql_con'], $query);
            while($lineRow = mysqli_fetch_array($lineResult)) {
                $finalLineColumns = $collectionWebShowColumns;
                $finalLineColumns["main_collection_id"] = $newId;
                $finalLineColumns["main_collection_setup_id"] = get_new_id($lineRow['main_collection_setup_id'], 'main_collection_web_show');
                $finalLineColumns["main_site_id"] = $lineRow['main_site_id'];
            
                $query = "INSERT INTO main_collection_web_show 
                            SELECT " . join(", ", $finalLineColumns) . " FROM main_collection_web_show 
                            WHERE id = " . $lineRow['id'];
                @mysqli_query($GLOBALS['mysql_con'], $query);
                $newLineId = mysqli_insert_id($GLOBALS['mysql_con']);
            
                insert_copy_link($lineRow['id'], $newLineId, "main_collection_web_show");
            }
            
            // collection table link kopieren
            $collectionTableLinkColumns = get_column_names_to_copy("main_collection_table_link");
            $query = "SELECT * FROM main_collection_table_link WHERE main_collection_id = " . $row['id'];
            $lineResult = @mysqli_query($GLOBALS['mysql_con'], $query);
            while($lineRow = mysqli_fetch_array($lineResult)) {
                $finalLineColumns = $collectionTableLinkColumns;
                $finalLineColumns["main_collection_id"] = $newId;
                $finalLineColumns["table_id"] = get_new_id($lineRow['table_id'], 'main_collection_table_link');
                $finalLineColumns["field_id"] = $lineRow['field_id'];
            
                $query = "INSERT INTO main_collection_table_link 
                            SELECT " . join(", ", $finalLineColumns) . " FROM main_collection_table_link 
                            WHERE id = " . $lineRow['id'];
                @mysqli_query($GLOBALS['mysql_con'], $query);
                $newLineId = mysqli_insert_id($GLOBALS['mysql_con']);

                    $query = "SELECT * FROM table_header WHERE id = " . $lineRow['table_id'];
                    $tableHeader = @mysqli_query($GLOBALS['mysql_con'], $query);
                    if(@mysqli_num_rows($tableHeader) > 0) {
                        $tableHeaderRow = mysqli_fetch_array($tableHeader);
                        $contentColumns = get_column_names_to_copy("table_header");
                        $query = "INSERT INTO table_header 
                            SELECT " . join(", ", $contentColumns) . " FROM table_header 
                            WHERE id = " . $lineRow['table_id'];
                            @mysqli_query($GLOBALS['mysql_con'], $query);
                            $newContentID = mysqli_insert_id($GLOBALS['mysql_con']);
                            insert_copy_link($lineRow['main_sitepart_header_id'], $newContentID, "table_header");
                            $query = "UPDATE main_collection_table_link SET table_id = '" . $newContentID . "' where id = " . $newLineId;
                            @mysqli_query($GLOBALS['mysql_con'], $query);

                        $query = "SELECT * FROM table_line WHERE table_id = " . $lineRow['table_id'];
                        $tableLine = @mysqli_query($GLOBALS['mysql_con'], $query);
                        $TableLineColumns = get_column_names_to_copy("table_line");
                        while($tableLineRow = mysqli_fetch_array($tableLine)) {
                            $finalLineColumns = $TableLineColumns;
                            $finalLineColumns["table_id"] = $newContentID;
                            $finalLineColumns["row_no"] = $tableLineRow['row_no'];
                            $finalLineColumns["column_no"] = $tableLineRow['column_no'];
                            $finalLineColumns["data"] = "'".$tableLineRow['data']."'";
                            $query = "INSERT INTO table_line 
                                SELECT " . join(", ", $finalLineColumns) . " FROM table_line 
                                WHERE id = " . $tableLineRow['id'];
                                @mysqli_query($GLOBALS['mysql_con'], $query);
                                insert_copy_link($lineRow['main_sitepart_header_id'], $newContentID, "table_line");
                        }
                    }
            
                insert_copy_link($lineRow['id'], $newLineId, "main_collection_table_link");
            }

        // collection link kopieren
        $collectionLinkColumns = get_column_names_to_copy("main_collection_link");
        $query = "SELECT * FROM main_collection_link WHERE main_collection_id = " . $row['id'];
        $lineResult = @mysqli_query($GLOBALS['mysql_con'], $query);
        while($lineRow = mysqli_fetch_array($lineResult)) {
            $finalLineColumns = $collectionLinkColumns;
            $finalLineColumns["main_collection_id"] = $newId;
            // $finalLineColumns["main_collection_setup_content_id"] = get_new_id($lineRow['main_collection_setup_content_id'], 'main_collection_setup_content');
            if($lineRow['main_sitepart_id'] > 0) {
                $finalLineColumns['main_sitepart_header_id'] = get_new_id($lineRow['main_sitepart_header_id'], $siteparts[$lineRow['main_sitepart_id']]['header_table']);
            }
        
            $query = "INSERT INTO main_collection_link 
                        SELECT " . join(", ", $finalLineColumns) . " FROM main_collection_link 
                        WHERE id = " . $lineRow['id'];

            @mysqli_query($GLOBALS['mysql_con'], $query);
            $newLineId = mysqli_insert_id($GLOBALS['mysql_con']);
        
            if($lineRow['main_sitepart_id'] == 0) {
                $query = "SELECT type_id from main_collection_setup_content where id = " . $lineRow['main_collection_setup_content_id'];
                $setupContentResult = @mysqli_query($GLOBALS['mysql_con'], $query);
                $setupContentRow = mysqli_fetch_array($setupContentResult);
                if($setupContentRow['type_id'] == 5) { // Bild
                    copy_collection_image($newLineId, $lineRow);
                }
            }
        
            // Textcontent
            if($lineRow['main_sitepart_header_id'] != 0 && $lineRow['main_sitepart_id'] == 1) {
                $query = "SELECT * from textcontent_header where id = " . $lineRow['main_sitepart_header_id'];
                $textContent = @mysqli_query($GLOBALS['mysql_con'], $query);
                if(@mysqli_num_rows($textContent) > 0) {
                    $textContentRow = mysqli_fetch_array($textContent);
                    $contentColumns = get_column_names_to_copy("textcontent_header");
                    $query = "INSERT INTO textcontent_header 
                        SELECT " . join(", ", $contentColumns) . " FROM textcontent_header 
                        WHERE id = " . $lineRow['main_sitepart_header_id'];
                        @mysqli_query($GLOBALS['mysql_con'], $query);
                        $newContentID = mysqli_insert_id($GLOBALS['mysql_con']);
                        insert_copy_link($lineRow['main_sitepart_header_id'], $newContentID, "textcontent_header");
                        $query = "UPDATE main_collection_link SET main_sitepart_header_id = '" . $newContentID . "' WHERE id = " . $newLineId;
                        @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
        
            // Gallery
            if($lineRow['main_sitepart_id'] == 6) {
                $query = "SELECT * FROM gallery_header WHERE id = " . $lineRow['main_sitepart_header_id'];
                $galleryHeader = @mysqli_query($GLOBALS['mysql_con'], $query);
                if(@mysqli_num_rows($galleryHeader) > 0) {
                    $galleryHeaderRow = mysqli_fetch_array($galleryHeader);
                    $contentColumns = get_column_names_to_copy("gallery_header");
                    $query = "INSERT INTO gallery_header 
                        SELECT " . join(", ", $contentColumns) . " FROM gallery_header 
                        WHERE id = " . $lineRow['main_sitepart_header_id'];
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                    $newContentID = mysqli_insert_id($GLOBALS['mysql_con']);
                    insert_copy_link($lineRow['main_sitepart_header_id'], $newContentID, "gallery_header");
                    $query = "UPDATE main_collection_link SET main_sitepart_header_id = '" . $newContentID . "' WHERE id = " . $newLineId;
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }

            // Filegallery
            if($lineRow['main_sitepart_id'] == 5) {
                $query = "SELECT * FROM filegallery_header WHERE id = " . $lineRow['main_sitepart_header_id'];
                $filegalleryHeader = @mysqli_query($GLOBALS['mysql_con'], $query);
                if(@mysqli_num_rows($filegalleryHeader) > 0) {
                    if (!defined('PATH_ORIGINAL_FILEGALLERY')) {
                        require_once(MODULE_PATH . "filegallery/filegallery.config.inc.php");
                    }

                    $contentColumns = get_column_names_to_copy("filegallery_header");
                    $query = "INSERT INTO filegallery_header
                        SELECT " . join(", ", $contentColumns) . " FROM filegallery_header
                        WHERE id = " . $lineRow['main_sitepart_header_id'];
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                    $newContentID = mysqli_insert_id($GLOBALS['mysql_con']);
                    insert_copy_link($lineRow['main_sitepart_header_id'], $newContentID, "filegallery_header");

                    $query = "UPDATE main_collection_link SET main_sitepart_header_id = '" . $newContentID . "' WHERE id = " . $newLineId;
                    @mysqli_query($GLOBALS['mysql_con'], $query);

                    $lineColumns = get_column_names_to_copy("filegallery_line");
                    $query = "SELECT * FROM filegallery_line WHERE header_id = " . $lineRow['main_sitepart_header_id'];
                    $filegalleryLineResult = @mysqli_query($GLOBALS['mysql_con'], $query);
                    while($filegalleryLineRow = @mysqli_fetch_array($filegalleryLineResult)) {
                        $finalLineColumns = $lineColumns;
                        $finalLineColumns['header_id'] = $newContentID;

                        $query = "INSERT INTO filegallery_line
                            SELECT " . join(", ", $finalLineColumns) . " FROM filegallery_line
                            WHERE id = " . $filegalleryLineRow['id'];
                        @mysqli_query($GLOBALS['mysql_con'], $query);
                        $newFilegalleryLineId = mysqli_insert_id($GLOBALS['mysql_con']);
                        insert_copy_link($filegalleryLineRow['id'], $newFilegalleryLineId, "filegallery_line");

                        if (!empty($filegalleryLineRow['filename'])) {
                            $filenameParts = explode('_', $filegalleryLineRow['filename'], 2);
                            $sourceFilename = $filegalleryLineRow['filename'];
                            $baseFilename = (count($filenameParts) === 2) ? $filenameParts[1] : $sourceFilename;
                            $targetFilename = $newFilegalleryLineId . "_" . $baseFilename;

                            if (file_exists(PATH_ORIGINAL_FILEGALLERY . $sourceFilename)) {
                                copy(PATH_ORIGINAL_FILEGALLERY . $sourceFilename, PATH_ORIGINAL_FILEGALLERY . $targetFilename);
                                $query = "UPDATE filegallery_line SET filename = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $targetFilename) . "' WHERE id = " . $newFilegalleryLineId;
                                @mysqli_query($GLOBALS['mysql_con'], $query);
                            }
                        }
                    }
                }
            }
        
        
            // Youtube
            if($lineRow['main_sitepart_id'] == 10) {
                $query = "SELECT * FROM youtube_header WHERE id = " . $lineRow['main_sitepart_header_id'];
                $youtubeHeader = @mysqli_query($GLOBALS['mysql_con'], $query);
                if(@mysqli_num_rows($youtubeHeader) > 0) {
                    $youtubeHeaderRow = mysqli_fetch_array($youtubeHeader);
                    $contentColumns = get_column_names_to_copy("youtube_header");
                    $query = "INSERT INTO youtube_header 
                        SELECT " . join(", ", $contentColumns) . " FROM youtube_header 
                        WHERE id = " . $lineRow['main_sitepart_header_id'];
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                    $newContentID = mysqli_insert_id($GLOBALS['mysql_con']);
                    insert_copy_link($lineRow['main_sitepart_header_id'], $newContentID, "youtube_header");
                    $query = "UPDATE main_collection_link SET main_sitepart_header_id = '" . $newContentID . "' WHERE id = " . $newLineId;
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            }
                

                insert_copy_link($lineRow['id'], $newLineId, "main_collection_link");
            }
        }

        return true;
    }

   
function get_column_names_to_copy($table) {
        $columns = array();
        $query = "SHOW COLUMNS FROM " . $table;
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        while($row = mysqli_fetch_array($result)) {
            if($row['Field'] == "id") {
                $columns[] = 'null';
                continue;
            }
            if($row['Field'] == "modified_date") {
                $columns[] = time();
                continue;
            }
    
            if($row['Field'] == "modified_user") {
                $columns[] = (int)$GLOBALS["admin_user"]['id'];
                continue;
            }
    
            $columns[$row['Field']] = $row['Field'];
        }
    
        return $columns;
}
function insert_copy_link($oldId, $newId, $table) {
    $query = "INSERT INTO copy_link (old_id, new_id, source_table, session_id) VALUES 
              (
                " . $oldId . ",
                " . $newId . ",
                '" . $table . "',
                '" . session_id() . "'
              )";
    @mysqli_query($GLOBALS['mysql_con'], $query);
}
/**
     * Helper function to copy the file of a collection image row
     *
     * @param $newLineId
     * @param $lineRow
     */
function copy_collection_image($newLineId, $lineRow) {
        $filename = $lineRow['data'];
        $newFilename = $newLineId . "_" . $filename;

        $query = "UPDATE main_collection_link SET data = '" . $newFilename . "' where id = " . $newLineId;
        @mysqli_query($GLOBALS['mysql_con'], $query);

        if(!file_exists(MODULE_PATH . "collection/" . PATH_ORIGINAL_PICTURE_COLLECTION . $filename)) {
            return;
        }

        copy(MODULE_PATH . "collection/" . PATH_ORIGINAL_PICTURE_COLLECTION . $filename     , MODULE_PATH . "collection/" . PATH_ORIGINAL_PICTURE_COLLECTION . $newFilename);
        copy(MODULE_PATH . "collection/" . PATH_RESIZE_COLLECTION . $filename               , MODULE_PATH . "collection/" . PATH_RESIZE_COLLECTION . $newFilename);
        copy(MODULE_PATH . "collection/../.." . PATH_ICON_COLLECTION . $filename                 , MODULE_PATH . "collection/../.." . PATH_ICON_COLLECTION . $newFilename);
    }

/**
 * Get new generated id of a table for a specific oldId
 *
 * @param $oldId
 * @param $table
 * @return array|bool|null
 */
 function get_new_id($oldId, $table) {
    $query = "SELECT new_id FROM copy_link WHERE old_id = '".$oldId."' AND source_table = '" . $table . "' AND session_id = '" . session_id() . "'";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if(@mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_array($result);
        return $row['new_id'];
    } else {
        return $oldId;
    }
}
// Holen Sie sich die Site-Sprachen zur Auswahl (Get the site languages for selection)
function collection_language($collection_id, $language_id, $setup_id){
   
    
    $query = "SELECT *  FROM main_collection_setup as mcs  WHERE mcs.id=".$setup_id." AND mcs.is_multidomain = 1";
    
    $response = @mysqli_query($GLOBALS['mysql_con'], $query);
    if(@mysqli_num_rows($response) != 0){

            $query = "SELECT main_site.id , main_language.name, main_site.name as site_name  FROM main_language Join  main_site on main_language.main_site_id = main_site.id INNER JOIN main_site_admin_user_link as msul on main_site.id = msul.main_site_id INNER JOIN main_collection_setup_websites AS mcsw on main_site.id = mcsw.main_site_id WHERE main_admin_user_id = ".$GLOBALS["admin_user"]['id']." AND mcsw.main_collection_setup_id = ".$setup_id;
            
            $site_collection = @mysqli_query($GLOBALS['mysql_con'], $query);
            
            if (@mysqli_num_rows($site_collection) == 0) { 
            return;
            }
            
            
            $preselect = array();
            $query = 'SELECT * FROM main_collection WHERE id='.$collection_id;
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            $response = @mysqli_fetch_array($result);
            
                $query = "SELECT * FROM main_collection_web_show WHERE  main_collection_id = ".$collection_id;
            
            
            
            $result = @mysqli_query($GLOBALS['mysql_con'], $query);
            
            while($row = @mysqli_fetch_array($result)){
            
                array_push($preselect,$row['main_site_id']);
            }

            ?>
            <div class="label">Website auswählen</div>
            <div class="websites bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
                <input type="hidden" name="select_website">
                <i class="dropdown icon"></i>
                <div class="default text">Website auswählen</div>
                <div class="menu">
                    <?  
                        
                    
                        while($site = @mysqli_fetch_array($site_collection)) {
                            echo "<div class=\"item\" data-value=\"{$site['id']}\">".$site["site_name"]."</div>";
                        }
                    ?>
                </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').dropdown('set selected', <?= json_encode($preselect) ?>); 
                });

            </script>
    


<?
        }else{
            return  '<input type="hidden" name="select_website" value="">';
        }
}

function getCollectionIcons($fieldSetup, $selected_data, $collection_setup_id){
    $query = "SELECT * FROM main_collection_setup WHERE id = ".$collection_setup_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $code = @mysqli_fetch_array($result);

    require 'collection_config.inc.php';
    echo "<select style=\"float:left;\" id=\"input_collection_link_" . $fieldSetup['id'] . "\" class=\"code\" type=\"text\" name=\"input_collection_link_" . $fieldSetup['id'] . "\" >";
    foreach ($collection_icon_images[$fieldSetup['code']] as $key => $data) {
        $selected_text = ($key == $selected_data) ? " selected=\"selected\"" : "";
        echo "<option value=\"" . $key . "\" $selected_text>" . $data["name"] . "</option>";
        $value++;
    }
    echo "</select>";
}

function loadCollectionsForCollections($field_id, $collection_id){
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $collection_id = $_POST['input_collection_id'];
    $setup_id = $input_collection['main_collection_setup_id'];

    $query = "SELECT mc.* FROM main_collection_setup mcs INNER JOIN main_collection as mc on mcs.id = mc.main_collection_setup_id INNER JOIN main_collection_setup_preview as mcsp on mcs.id = mcsp.main_collection_setup_id_selected WHERE mcsp.field_id = ".$field_id."  AND mc.id != ".$collection_id;

    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 0) {
        return;
    }

    $preselect = array();
    $query2 = "SELECT * FROM main_collection_preview_link WHERE main_collection_id = '" . $collection_id . "' AND field_id = ".$field_id." AND active = 1";
    
    $result2 = mysqli_query($GLOBALS['mysql_con'], $query2);

    while($row2 = @mysqli_fetch_array($result2)){
        array_push($preselect,$row2['collection_id_selected']);
    }
    
    ?>
    
    <div class="label"></div>
    <div class="products<?= $field_id;?> multiple bc-select-ui ui fluid  search selection dropdown" style="clear:both;display:inline-block;">
        <input type="hidden" name="collection_id_selected_<?= $field_id;?>">
        <i class="dropdown icon"></i>
        <div class="default text"><?php echo $translation->get('choose_collection');?>
        </div>
        <div class="menu">
            <? 
                while($row = @mysqli_fetch_array($result)) {
                    echo "<div class=\"item\" data-value=\"{$row['id']}\">".$row["description"]."</div>";
                }
            ?>
        </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('.products<?= $field_id;?>.multiple.ui.fluid.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });
    </script>
<? } 

function loadFAQGroupCollection($faq_id, $field_id){
    // Faq group
    
 
                $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
                $query = "SELECT * FROM main_faq_setup_group";

                $result = mysqli_query($GLOBALS['mysql_con'], $query);
                if (@mysqli_num_rows($result) == 0) {
                    return;
                }
            
                $preselect = array();
                $groups = array();
                while ($row = @mysqli_fetch_array($result)) {
                    array_push($groups,$row);
                    $query2 = "SELECT * FROM main_collection_faq_header_group_link WHERE header_id =" . $faq_id . " AND faq_group_id = " . $row['id'];
                    $result2 = @mysqli_query($GLOBALS['mysql_con'], $query2);
                    $row2 = @mysqli_fetch_array($result2);
                    $checked = 0;
                    if(isset($row2) && $row2['active']){
                        array_push($preselect,$row2['faq_group_id']);
                    }
                    // input($row['description'], "input_group_".$row['id'].$field_id, "checkbox", $checked);
                }
                 
                ?>
                 <div class="label"><?php echo $translation->get('select_groups'); ?></div>
                        <div class="faq_groups multiple bc-select-ui ui fluid  search selection dropdown" style="clear:both;display:inline-block;">
                            <input type="hidden" name="faq_groups_<?= $field_id;?>">
                            <i class="dropdown icon"></i>
                            <div class="default text"><?php echo $translation->get('select_groups');?></div>
                            <div class="menu">
                                <?  
                                    
                                
                                    foreach($groups as $row) {
                                        echo "<div class=\"item\" data-value=\"{$row['id']}\">".$row["description"]."</div>";
                                    }
                                  
                                ?>
                            </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('.faq_groups.multiple.ui.fluid.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
                                });
            
            
                    </script>
<?  
    // Faq group end
    
    $query = "SELECT * FROM main_faq_setup_group";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

    if (@mysqli_num_rows($result) == 0) {
        return;
    }
    
}
// save FAQ group
function save_header_group($faq_id, $field_id, $collection_id){
    $query = "SELECT * FROM main_faq_setup_group";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

    if (@mysqli_num_rows($result) == 0) {
        return;
    }
    $queryUpdate = "UPDATE main_collection_faq_header_group_link SET
            active = 0
            WHERE field_id = '" . $field_id . "' AND main_collection_id = ".$collection_id;
            @mysqli_query($GLOBALS['mysql_con'], $queryUpdate);   
     
    while ($row = @mysqli_fetch_array($result)) {
        $faqGroups = array();
        
        if( isset($_POST['faq_groups_'.$field_id])){
            $faqGroups = explode(',', $_POST['faq_groups_'.$field_id]);
        }

        if(!empty($faqGroups) && gettype($faqGroups) == 'array' && in_array($row['id'],$faqGroups)){
            $active = 1;
           
        }else {
            continue;
           
        }
        $query2 = "SELECT * FROM main_collection_faq_header_group_link WHERE header_id =" . $faq_id . " AND faq_group_id = " . $row['id'];
        
        $result2 = @mysqli_query($GLOBALS['mysql_con'], $query2);
        $row2 = @mysqli_fetch_array($result2);
        $query3 = '';
        if(isset($row2)){
            $query3 = "UPDATE main_collection_faq_header_group_link SET
            active = ".$active."
            WHERE id = '" . $row2['id'] . "' 
            LIMIT 1";
        }else {
            $query3 = "INSERT INTO main_collection_faq_header_group_link
            (header_id, faq_group_id, active,field_id ,main_collection_id)
            VALUES (
                " . $faq_id . ",
                " . $row['id'] . ",
                " . $active . ",
                ".$field_id.",
                ".$collection_id."
            )";
        }
          
        @mysqli_query($GLOBALS['mysql_con'], $query3);
    }
}
// Save FAQ data
function save_faq_data($keyData, $input_id){
    $key  = substr($keyData, strlen("collection_modul_input_"));;
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $description = '';
    if(isset($_POST['input_description_faq'.$key]) && $_POST['input_description_faq'.$key]  != NULL){
        $description = $_POST['input_description_faq'.$key];
    }
    $header_id = 0;
    if(isset($_POST['input_id_faq'.$key]) && $_POST['input_id_faq'.$key]  != NULL){
        $header_id = $_POST['input_id_faq'.$key];
    }
    $query = '';
     
    $error = FALSE;
   
    if ($header_id <> 0) {

        $query = "UPDATE main_faq_header SET
                description = '" . mysqli_real_escape_string($GLOBALS['mysql_con'],$description) . "',
                modified_date = " . time() . ",
                modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
                
                all_languages = " . '0'. "
                WHERE id = '" . $header_id . "' 
            LIMIT 1";
        $inserted    = FALSE;
         
    } else {
        $query = "INSERT INTO main_faq_header
            ( main_language_id, modified_date, modified_user, description, all_languages)
            VALUES (
               
                " . (int)$GLOBALS["language"]['id'] . ",
                " . time() . ",
                " . (int)$GLOBALS["admin_user"]['id'] . ",
                '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $description) . "',
                " . '0' . "
            )";
       
    }
  
 
    if (($description == '')) {
        $messages[] = "<div class=\"errorbox\">" . $translation->get("error_description") . "</div>\n";
        $error      = TRUE;
    }
    
    if(!$error){
        
        @mysqli_query($GLOBALS['mysql_con'], $query);
        if($header_id == 0){
            $header_id   = mysqli_insert_id($GLOBALS['mysql_con']);
        }
        save_header_group($header_id, $key, $input_id);
    }else{
         
        return "";
    }
}

function saveCalendarSerial($collection_id){
    $repeating_type = $_POST['input_repeating_type'];
    
    $date_from = "''";
    $date_to = "''";
    if(isset($_POST['date_from']) && $_POST['date_from'] != NULL){
        $date_from = datetosql($_POST["date_from"]);
    }
    if(isset($_POST['date_to']) && $_POST['date_to'] != NULL){
        $date_to = datetosql($_POST["date_to"]);
    }

    $start_time = $_POST['start_time'];
    $end_time = $_POST['end_time'];

    $monday = 0;
    $tuesday = 0;
    $wednesday = 0;
    $thursday = 0;
    $friday = 0;
    $saturday = 0;
    $sunday = 0;

    $day_nr = 0;
    $week_nr = 0;
    $month_nr = 0;
    $year_nr = 0;
    $repeating_radio = 0;

    switch ($repeating_type) {
        case 'daily':
            $day_nr = $_POST['daily_count'];
            break;
        case 'weekly':
            $week_nr = $_POST['weekly_count'];
            $monday = ($_POST["monday"] == "on") ? 1 : 0;
            $tuesday = ($_POST["tuesday"] == "on") ? 1 : 0;
            $wednesday = ($_POST["wednesday"] == "on") ? 1 : 0;
            $thursday = ($_POST["thursday"] == "on") ? 1 : 0;
            $friday = ($_POST["friday"] == "on") ? 1 : 0;
            $saturday = ($_POST["saturday"] == "on") ? 1 : 0;
            $sunday = ($_POST["sunday"] == "on") ? 1 : 0;
            break;
        case 'monthly':
            if($_POST['input_repeating_radio'] == 1){
                $repeating_radio = 1;
                $day_nr = $_POST['monthly_day_1'];
                $month_nr = $_POST['monthly_count_1'];
            }else{
                $repeating_radio = 2;
                $day_nr = $_POST['monthly_day_2'];
                $week_nr = $_POST['monthly_week_2'];
                $month_nr = $_POST['montly_count_2'];
            }
            break;
        case 'yearly':
            $year_nr = $_POST['yearly_count'];
            if($_POST['input_repeating_radio'] == 1){
                $repeating_radio = 1;
                $day_nr = $_POST['yearly_day_1'];
                $month_nr = $_POST['yearly_month_1'];
            }else{
                $repeating_radio = 2;
                $day_nr = $_POST['yearly_day_2'];
                $week_nr = $_POST['yearly_week_2'];
                $month_nr = $_POST['yearly_month_2'];
            }
            break;
        default:
            break;
    }

    $deleteSerial = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM calendar_serial WHERE main_collection_id='".$collection_id."'");   

    $insertquery = "INSERT INTO calendar_serial
    (main_collection_id, date_from, date_to, start_time, end_time, repeating_type, monday, tuesday, wednesday, thursday, friday, saturday, sunday, day_nr, week_nr, month_nr, year_nr, repeating_radio)
    VALUES (
        '" . $collection_id . "',
        " . $date_from . ",
        " . $date_to . ",
        '" . $start_time . "',
        '" . $end_time . "',
        '" . $repeating_type . "',
        " . $monday . ",
        " . $tuesday . ",
        " . $wednesday. ",
        " . $thursday . ",
        " . $friday . ",
        " . $saturday . ",
        " . $sunday . ",
        " . $day_nr . ",
        " . $week_nr . ",
        " . $month_nr . ",
        " . $year_nr . ",
        " . $repeating_radio . "
    )";
    @mysqli_query($GLOBALS['mysql_con'], $insertquery);
}

// save table data
function save_table_data($keyData, $input_id){
    $inserted;
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $key  = substr($keyData, strlen("collection_modul_input_"));;
    $table_id = 0;
    if(isset($_POST['input_table_id_'.$key]) && $_POST['input_table_id_'.$key]  != NULL){
        $table_id = $_POST['input_table_id_'.$key];
    }
    $code = '';
    if(isset($_POST['input_table_code_'.$key]) && $_POST['input_table_code_'.$key]  != NULL){
        $code = $_POST['input_table_code_'.$key];
    }
    $description = '';
    if(isset($_POST['input_table_description_'.$key]) && $_POST['input_table_description_'.$key]  != NULL){
        $description = $_POST['input_table_description_'.$key];
    }
     $no_rows = '';
    if(isset($_POST['no_rows_'.$key]) && $_POST['no_rows_'.$key]  != NULL){
        $no_rows = $_POST['no_rows_'.$key];
    }
    $no_columns = '';
    if(isset($_POST['no_columns_'.$key]) && $_POST['no_columns_'.$key]  != NULL){
        $no_columns = $_POST['no_columns_'.$key];
    }
    
    $query = '';
    if ($table_id != 0) {
        $query    = "UPDATE table_header SET
				description = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $description) . "',
                 
				modified_date = " . time() . ",
				modified_user = " . (int)$GLOBALS["admin_user"]['id'] . ",
                code = '". mysqli_real_escape_string($GLOBALS['mysql_con'], $code)."',
                no_rows = '". mysqli_real_escape_string($GLOBALS['mysql_con'], $no_rows)."',
                no_columns = '". mysqli_real_escape_string($GLOBALS['mysql_con'], $no_columns)."'
				 
				WHERE id = '" . $table_id . "'
			LIMIT 1";
        $inserted = FALSE;
        
      
       
    }
    
     else {
        
        $query    = "INSERT INTO table_header
			(main_language_id, description, modified_date, modified_user, code, no_rows, no_columns)
			VALUES (
				" . (int)$GLOBALS["language"]['id'] . ",
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $description) . "',
				" . time() . ",
				" . (int)$GLOBALS["admin_user"]['id'] . ",
                '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $code) . "',
                '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $no_rows) . "',
                '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $no_columns) . "'
			)";
            
        $inserted = TRUE;
    }
   
    $errors = FALSE;
     
    
    
    if (!$errors) {
        @mysqli_query($GLOBALS['mysql_con'], $query);
       
        if ($inserted == TRUE) {
            $table_id   = mysqli_insert_id($GLOBALS['mysql_con']);

            $queryLink    = "INSERT INTO main_collection_table_link
			(table_id, main_collection_id, field_id)
			VALUES (
				" . $table_id . ",
				'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $input_id) . "',
				" . $key . "
			)";
            @mysqli_query($GLOBALS['mysql_con'], $queryLink);
            $messages[] = '<div class="successbox">' . $translation->get("data_success_1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("data_success_2") . '</div>';
        }
 
        if ($inserted == FALSE) {
            for($row = 1; $row <= $no_rows; $row++){
                for($column = 1; $column <= $no_columns; $column++){
                   if (array_key_exists("input_rowline_" . $table_id."_".$row."_".$column,$_POST) && $_POST["input_rowline_" . $table_id."_".$row."_".$column] != "" && $_POST["input_rowline_" . $table_id."_".$row."_".$column] != NULL) {
                        add_to_table_line($row, $column, $table_id, $_POST["input_rowline_" . $table_id."_".$row."_".$column]);
                    } else{
                        $deleteData = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM table_line WHERE table_id='".$table_id."' AND row_no = '".$row."' AND column_no = '".$column."'" );
    
                    }  
                }
            }
        }
         
        

    }

}
function create_collection_table_set($input_tableform, $collection_id, $field_id){

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

    
    for($i = 1; $i <= $input_tableform['no_rows']; $i++ ){
        echo '<tr style="outline: thin solid #d8dce3;padding:2px;">';
        for($j = 1; $j <= $input_tableform['no_columns']; $j++ ){
            echo '<td style="width:auto; float:none;">';
            $query = "SELECT * FROM table_line WHERE table_id = '" . $input_tableform['id'] . "' AND row_no = ".$i." AND column_no = ".$j." LIMIT 1";
            $result = mysqli_query($GLOBALS['mysql_con'], $query);
            $value = '';
            if (@mysqli_num_rows($result) > 0) {
                $row = @mysqli_fetch_array($result);
                $value = $row['data'];
            }
            input($translation->get("description"), "input_rowline_".$input_tableform['id']."_".$i."_".$j, "text", $value, 255) ;
            echo '</td>';
        }
        echo '</tr>';
    }
    
}
function add_to_table_line($row, $column, $input_id, $data){
    $query = "SELECT * FROM table_line WHERE table_id = '" . $input_id . "' AND row_no = ".$row." AND column_no = ".$column." LIMIT 1";
    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    $queryLine = '';
    if (@mysqli_num_rows($result) > 0) {
        $tableData = @mysqli_fetch_array($result);
        $queryLine    = "UPDATE table_line SET
                        table_id = " . $input_id . ",
                        row_no = '". mysqli_real_escape_string($GLOBALS['mysql_con'], $row)."',
                        column_no = '". mysqli_real_escape_string($GLOBALS['mysql_con'], $column)."',
                        data = '". mysqli_real_escape_string($GLOBALS['mysql_con'], $data)."'
                        WHERE id = '" . $tableData["id"] . "'
                        LIMIT 1";
        

    } else {

        $queryLine    = "INSERT INTO table_line
                    (table_id, row_no, column_no, data)
                    VALUES (
                         
                        " . $input_id . ",
                        '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $row) . "',
                        '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $column) . "',
                        '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $data) . "'
                    )";
            
    }
    @mysqli_query($GLOBALS['mysql_con'], $queryLine);
}

function add_to_preview($key, $value, $input_id, $postValue){
    $key = substr($key, strlen("input_collection_hidden_info_"));
     
    $collectionIds = array();
    if(isset($_POST['collection_id_selected_'.$key]) && $_POST['collection_id_selected_'.$key]  != NULL){
        $collections = $_POST['collection_id_selected_'.$key];
        $collectionIds = explode(',', $collections);
    }
    $delKey = "DELETE FROM main_collection_preview_link WHERE main_collection_id='".$input_id."' AND field_id = ".$key ;
    $deleteOld = @mysqli_query($GLOBALS["mysql_con"], $delKey);

    if(!empty($collectionIds) && gettype($collectionIds) == 'array')  {
        foreach($collectionIds as $keys => $collection){
           $query = "INSERT INTO main_collection_preview_link
           (field_id, collection_id_selected, main_collection_id, active)
           VALUES (
               " .  $key . ",
               '" . $collection . "',
               '" . $input_id . "',
               '1'
           )";
           @mysqli_query($GLOBALS['mysql_con'], $query);
        }  
    }
}

function create_knowledegecenter_category_select($collection_id){
    $query = "SELECT * FROM knowledgecenter_category";
    $knowledgecenter_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    if (@mysqli_num_rows($knowledgecenter_result) == 0) { 
        return;
    }
    
    $preselect = array();
    
    $query = "SELECT * FROM knowledgecenter_collection_link WHERE main_collection_id = ".$collection_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    while($row = @mysqli_fetch_array($result)){
        array_push($preselect,$row['knowledgecenter_category_id']);
    }

?>
    <div class="label">Kategorie auswählen</div>
    <div class="knowledgecenter bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
        <input type="hidden" name="select_category">
        <i class="dropdown icon"></i>
        <div class="default text">Kategorie auswählen</div>
        <div class="menu">
            <?  
                while($knowledgecenter = @mysqli_fetch_array($knowledgecenter_result)) {
                    echo "<div class=\"item\" data-value=\"{$knowledgecenter['id']}\">".$knowledgecenter["description"]."</div>";
                }
            ?>
        </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('.knowledgecenter.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });
    </script>
<?
}

function create_contact_select($data, $setup_id){
    $translation   = \DynCom\mysyde\common\classes\Registry::get("translation");
    $query = "SELECT * FROM main_contact ORDER BY name";
    $contact_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    $preselect = array();
    
    $contact_ids = explode(',', $data);
    foreach($contact_ids as $key => $contact_value){
        array_push($preselect,$contact_value);
    }
    ?>
    <div class="label"><?php echo $translation->get("contact")?></div>
    <div class="contact_<?= $setup_id ?> bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
    <input id='input_collection_link_<?= $setup_id ?>' class='code' type='hidden' name='input_collection_link_<?= $setup_id?>'>
        <i class="dropdown icon"></i>
        <div class="default text"><?php echo $translation->get("contact")?></div>
        <div class="menu">
            <?  
                while($contact = @mysqli_fetch_array($contact_result)) {
                    echo "<div class=\"item\" data-value=\"{$contact['id']}\">".$contact["name"]."</div>";
                }
            ?>
        </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('.contact_<?= $setup_id ?>.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });
    </script>
<?
}

function create_mandant_select($collection_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 main_collection_mandant_link WHERE main_collection_id = ".$collection_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>
<?
}

function select_contact($data, $fieldSetup_id) {
    // SQL-Abfrage zur Auswahl aller Kontakte
    $query = "SELECT * FROM main_contact ORDER BY name";
    $contact_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    // Beginne das select-Element
    echo "<select name='input_collection_link_" . $fieldSetup_id . "' id='input_collection_link_" . $fieldSetup_id . "'>";
    
    // Füge die leere Option als erste Option hinzu
    echo "<option value=''>Keine Auswahl getroffen</option>";
    
    // Schleife durch die Ergebnisse der SQL-Abfrage
    while ($contact = @mysqli_fetch_array($contact_result)) {
        $selected = '';
        if ($contact['id'] == $data) {
            $selected = 'selected';
        }
        echo "<option " . $selected . " value='" . $contact['id'] . "'>" . $contact['name'] . "</option>";
    }
    
    // Beende das select-Element
    echo "</select>";
}

function delete_knowledgecenter($collection_id){
    $query = "DELETE FROM main_collection_mark WHERE main_collection_id = " . $collection_id;
    @mysqli_query($GLOBALS['mysql_con'], $query);
    $query = "DELETE FROM knowledgecenter_collection_link WHERE main_collection_id = " . $collection_id;
    @mysqli_query($GLOBALS['mysql_con'], $query);
}

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();
    
    $query2 = "SELECT * FROM main_collection_".$type."_link WHERE main_collection_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">
            <?  
                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 save_collection_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 main_collection_".$type."_link WHERE main_collection_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 main_collection_".$type."_link
            (main_collection_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 main_collection_".$type."_link WHERE main_collection_id = '".$collection_id."'");
            foreach($type_ids as $permission_type_id){
                if ($permission_type_id != "") {
                    $query = "INSERT IGNORE INTO main_collection_".$type."_link
                    (main_collection_id, main_".$type."_id)
                    VALUES (
                        '" . $collection_id ."',
                        '" .  $permission_type_id . "'
                    )";
                    @mysqli_query($GLOBALS['mysql_con'], $query);
                }
            
            }
            @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_collection_".$type."_link WHERE main_collection_id = '".$collection_id."' AND main_".$type."_id = 0;");
        }
    }
    
}

function save_gallery_data($keyData, $input_id){
    $setup_line_id  = substr($keyData, strlen("collection_modul_input_"));
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $selected_files = $_REQUEST['module_input_gallery_' . $setup_line_id];
    if($selected_files == ""){
        return;
    }
    $selected_files = explode(", ", $selected_files);

    $header_id = 0;

    $query = "SELECT * FROM main_collection_link WHERE main_collection_id = ".$input_id." AND main_collection_setup_content_id = ".$setup_line_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $row = @mysqli_fetch_array($result);
        $header_id = $row['main_sitepart_header_id'];
    }

    if($header_id == 0){
        $query  = "SELECT options FROM main_collection_setup_content WHERE id = '" . $setup_line_id."'";
        $result = mysqli_query($GLOBALS['mysql_con'], $query);
        $row    = mysqli_fetch_array($result);
    
        $options = unserialize($row['options']);
        // hinzufuegen zur datenbank
        $insertquery = "INSERT INTO gallery_header
            (main_language_id, description, modified_date, modified_user, width, height, thumb_width, thumb_height, collection_header)
            VALUES (
                '" . $GLOBALS["language"]['id'] . "',
                '',
                " . time() . ",
                " . (int)$GLOBALS["admin_user"]['id'] . ",
                " . (int)$options['collection_setup_gallery_width'] . ",
                " . (int)$options['collection_setup_gallery_height'] . ",
                " . (int)$options['collection_setup_gallery_thumb_width'] . ",
                " . (int)$options['collection_setup_gallery_thumb_height'] . ",
                1
            )";
    
        @mysqli_query($GLOBALS['mysql_con'], $insertquery);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);
        
        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
        VALUES (
            '" . $_REQUEST['input_collection_id'] . "',
            '" . $setup_line_id . "',
            " . $header_id . ",
            6
        )";
        mysqli_query($GLOBALS['mysql_con'], $query);
    }


    foreach ($selected_files as $key => $value) {
        $previewImageString = "<img src=\"/userdata/". $value . "?time=" . time() ."\">";

        $sorting  = mysqli_fetch_array(@mysqli_query($GLOBALS['mysql_con'], "SELECT MAX(sorting)+1 AS 'newsorting' FROM gallery_line WHERE header_id = '" . $header_id."'"));
        $sorting  = ($sorting["newsorting"] <> "") ? $sorting = $sorting["newsorting"] : $sorting = 1;

        $query = "INSERT INTO gallery_line
        (header_id, preview, filename, description, sorting, modified_date, modified_user)
        VALUES (
            ".$header_id.",
            '" .$previewImageString. "',
            '" .$value. "',
            '" .$value. "',
            '" .$sorting. "',
            " . time() . ",
            " . (int)$GLOBALS["admin_user"]['id'] . "
        )";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

function save_filegallery_data($keyData, $input_id){
    $setup_line_id  = substr($keyData, strlen("collection_modul_input_"));
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $selected_files = $_REQUEST['module_input_filegallery_' . $setup_line_id];
    if($selected_files == ""){
        return;
    }
    $selected_files = explode(", ", $selected_files);

    $header_id = 0;

    $query = "SELECT * FROM main_collection_link WHERE main_collection_id = ".$input_id." AND main_collection_setup_content_id = ".$setup_line_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) == 1) {
        $row = @mysqli_fetch_array($result);
        $header_id = $row['main_sitepart_header_id'];
    }

    if($header_id == 0){
        $insertquery = "INSERT INTO filegallery_header
            (main_language_id, description, modified_date, modified_user, collection_header)
            VALUES (
                '" . $GLOBALS["language"]['id'] . "',
                '',
                " . time() . ",
                " . (int)$GLOBALS["admin_user"]['id'] . ",
                1
            )";
    
        @mysqli_query($GLOBALS['mysql_con'], $insertquery);
        $header_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $query = "INSERT INTO main_collection_link (main_collection_id, main_collection_setup_content_id, main_sitepart_header_id, main_sitepart_id)
        VALUES (
            '" . $_REQUEST['input_collection_id'] . "',
            '" . $setup_line_id . "',
            " . $header_id . ",
            5
        )";
        mysqli_query($GLOBALS['mysql_con'], $query);
    }

    foreach ($selected_files as $key => $value) {
        $extension = pathinfo($value, PATHINFO_EXTENSION);

        $sorting  = mysqli_fetch_array(@mysqli_query($GLOBALS['mysql_con'], "SELECT MAX(sorting)+1 AS 'newsorting' FROM filegallery_line WHERE header_id = '" . $header_id."'"));
        $sorting  = ($sorting["newsorting"] <> "") ? $sorting = $sorting["newsorting"] : $sorting = 1;

        $position = strrpos($value, '/');
        $description = substr($value, $position + 1);

        $query = "INSERT INTO filegallery_line
        (header_id, extension, filename, description, sorting, modified_date, modified_user)
        VALUES (
            ".$header_id.",
            '" .$extension. "',
            '" .$value. "',
            '" .$description. "',
            '" .$sorting. "',
            " . time() . ",
            " . (int)$GLOBALS["admin_user"]['id'] . "
        )";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}