<?
switch ($_GET["action"]) {
    case 'edit':
        edit_department();
        break;
    case 'delete':
        delete_department($department['id']);
        break;
    case 'new':
        require_once("edit_space_cardform.inc.php");
        break;
    case 'save':
        save_department();
        break;
    default:
        require_once("edit_space_listform.inc.php");
        break;
}

function edit_department( $_id = "", $messages = array() ) {
    if ((int)$_id > 0) {
        $input_id = $_id;
    } else {
        $input_id = $_POST["input_id"];
    }

    if ($input_id <> '') {

        $pdoHost = getenv('MAIN_MYSQL_DB_HOST');
        $pdoPort = getenv('MAIN_MYSQL_DB_PORT');
        $pdoUser = getenv('MAIN_MYSQL_DB_USER');
        $pdoPass = getenv('MAIN_MYSQL_DB_PASS');
        $pdoSchema = getenv('MAIN_MYSQL_DB_SCHEMA');

        $pdo = new \DynCom\mysyde\common\classes\PDOQueryWrapper($pdoHost, $pdoPort, $pdoSchema, $pdoUser, $pdoPass);

        $prepStatement = "  SELECT * FROM organogramm_space WHERE id = :id LIMIT 1 ";
        $params = [
            [':id', $input_id, PDO::PARAM_STR],
        ];
        $pdo->setQuery($prepStatement);
        $pdo->prepareQuery();
        $pdo->bindParameters($params);
        $pdo->executePreparedStatement();
        $result = $pdo->getResultArray();

        if (count($result) == 1) {
            $input_department             = $result[0];
            $input_department["password"] = "nochange";
            require_once("edit_space_cardform.inc.php");
        }
    } else {
        $input_department = array();
        require_once("edit_space_cardform.inc.php");
    }
}

function delete_department($curr_department_id) {
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    if ($_POST["input_id"] <> '') {
        if ($_POST["input_id"] <> $curr_department_id) {
            $query      = "DELETE FROM organogramm_space WHERE id = '" . $_POST["input_id"] . "' LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        } else {
            header('EDIT_ERROR: 1');
            $messages[] = "<div class=\"errorbox\">" . $translation->get("department_error5") . "</div>";
            edit_department($_POST["input_id"], $messages);
        }
    }
    require_once("edit_space_listform.inc.php");
}

function save_department() {
    $messages    = array();
    $error       = FALSE;
    $input_id    = "";
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    if ($_POST["input_id"] <> '') {
        $inserted = FALSE;
        $input_id = $_POST["input_id"];
        $query = "UPDATE organogramm_space
			SET description = '" . $_POST['input_description'] . "'
            WHERE id = '" . $input_id . "' LIMIT 1";
        // $query_dep = "UPDATE organigramm_department_space SET department_id = '".$."'";
    } else {
        $query    = "INSERT INTO organogramm_space (id, description) VALUES (
			NULL,
			'" . $_POST['input_description'] . "'
			)";
        $inserted = TRUE;
        
    }

    if (!$error) {

        @mysqli_query($GLOBALS['mysql_con'], $query);
        if ($inserted == TRUE) {
            $input_id   = mysqli_insert_id($GLOBALS['mysql_con']);
            $messages[] = '<div class="successbox">' . $translation->get("department_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("department_msg_success2") . '</div>';
        } 
        saveMandantLink($input_id);
        edit_department($input_id, $messages);
    } else {
        header('EDIT_ERROR: 1');
        // $input_department["id"]                = $_POST["input_id"];
        // $input_department["name"]              = $_POST["input_name"];
        // $input_department["email"]             = $_POST["input_email"];
        // $input_department["login"]             = $_POST["input_login"];
        require_once("edit_space_cardform.inc.php");
    }
}

function saveMandantLink($department_id){
    $mandant_id = $_POST['select_mandant'];
    $mandante = explode(',', $mandant_id);
    if(!empty($mandante) && gettype($mandante) == 'array')  { 
        $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_fachbereich_einrichtung WHERE fachbereich_id = ".$department_id);    
        foreach($mandante as $key => $mandant){
            $query = "INSERT INTO main_fachbereich_einrichtung
            (fachbereich_id, einrichtung_id)
            VALUES (
                " .  $department_id . ",
                '" . $mandant . "'
            )";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
    }
}

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

    $query = "SELECT * FROM organigramm_einricht";
    $result_mandant = @mysqli_query($GLOBALS['mysql_con'], $query);
        
    if (@mysqli_num_rows($result_mandant) == 0) { 
        return;
    }
        
    $preselect = array();
    
    $query = "SELECT * FROM main_fachbereich_einrichtung WHERE fachbereich_id = ".$department_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    while($row = @mysqli_fetch_array($result)){
        array_push($preselect,$row['einrichtung_id']);
    }
    $allselect = array();
    ?>
    <div class="label"><?php echo $translation->get("top_facility")?></div>
    <div class="websites 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("top_facility")?></div>
        <div class="menu">
            <?  
                while($mandant = @mysqli_fetch_array($result_mandant)) {
                    array_push($allselect,$mandant['id']);
                    echo "<div class=\"item\" data-value=\"{$mandant['id']}\">".$mandant["description"]."</div>";
                }
            ?>
        </div>
    </div>
    <div class='all_mandate' ><?php echo $translation->get("all")?></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) ?>); 
        });
        $(".all_mandate").click(function() {
            $y('.websites.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($allselect) ?>); 
        });
    </script>
<?php
}