<?
switch ($_GET["action"]) {
    case 'edit':
        edit_facility();
        break;
    case 'delete':
        delete_facility($role['id']);
        break;
    case 'new':
        require_once("edit_facility_cardform.inc.php");
        break;
    case 'save':
        save_facility();
        break;
    default:
        require_once("edit_facility_listform.inc.php");
        break;
}

function edit_facility( $_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 organigramm_einricht 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_role             = $result[0];
            $input_role["password"] = "nochange";
            require_once("edit_facility_cardform.inc.php");
        }
    } else {
        $input_role = array();
        require_once("edit_facility_cardform.inc.php");
    }
}

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

function save_facility() {
    $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 organigramm_einricht
			SET description= '" . $_POST['input_description'] . "'
            WHERE id = '" . $input_id . "' LIMIT 1";
    } else {
        $query    = "INSERT INTO organigramm_einricht (description) VALUES (
			'" . $_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("role_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("role_msg_success2") . '</div>';
        } 
        saveMandantLink($input_id);
        edit_role($input_id, $messages);
    } else {
        header('EDIT_ERROR: 1');
        // $input_role["id"]                = $_POST["input_id"];
        // $input_role["name"]              = $_POST["input_name"];
        // $input_role["email"]             = $_POST["input_email"];
        // $input_role["login"]             = $_POST["input_login"];
        require_once("edit_facility_cardform.inc.php");
    }
}

function saveMandantLink($role_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_role_mandant_link WHERE main_role_id = ".$role_id);    
    //     foreach($mandante as $key => $mandant){
    //         $query = "INSERT INTO main_role_mandant_link
    //         (main_role_id, main_mandant_id)
    //         VALUES (
    //             " .  $role_id . ",
    //             '" . $mandant . "'
    //         )";
    //         @mysqli_query($GLOBALS['mysql_con'], $query);
    //     }
    // }
}

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

    $query = "SELECT * FROM main_mandant";
    $result_mandant = @mysqli_query($GLOBALS['mysql_con'], $query);
        
    if (@mysqli_num_rows($result_mandant) == 0) { 
        return;
    }
        
    $preselect = array();
    
    // $query = "SELECT * FROM main_role_mandant_link WHERE main_role_id = '".$role_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("top_mandant")?></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_mandant")?></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_mandate")?></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
}