<?
switch ($_GET["action"]) {
    case 'edit':
        edit_unit();
        break;
    case 'delete':
        delete_unit($unit['id']);
        break;
    case 'new':
        require_once("learning_unit_cardform.inc.php");
        break;
    case 'save':
        save_unit();
        break;
    case 'save_line_unit':
        save_line_unit();
        break;
    case 'new_line_unit':
        require_once("learning_unit_line_cardform.inc.php");
        break;
    case 'edit_line_unit':
        edit_line_unit();
        break;
    case 'delete_line_unit':
        delete_line_unit();
        break;
    case 'moveup_line_unit':
        moveup_line_unit();
        edit_unit();
        break;
    case 'movedown_line_unit':
        movedown_line_unit();
        edit_unit();
        break;
    case 'open_card':
        open_card();
    default:
        require_once("learning_unit_listform.inc.php");
        break;
}

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

function edit_unit( $_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 learning_unit 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_unit = $result[0];
            require_once("learning_unit_cardform.inc.php");
        }
    } else {
        $input_unit = array();
        require_once("learning_unit_cardform.inc.php");
    }
}

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

function save_unit() {
    $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 learning_unit
			SET title = '" . $_POST['input_title'] . "',
			description = '" . $_POST['input_description'] . "',
			link = '" . $_POST['input_link'] . "'
			WHERE id = '" . $_POST["input_id"] . "' LIMIT 1";
    } else {
        $query    = "INSERT INTO learning_unit (id, title, description, link) VALUES (
			NULL,
			'" . $_POST['input_title'] . "',
			'" . $_POST['input_description'] . "',
			'" . $_POST['input_link'] . "'
			)";
        $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("unit_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("unit_msg_success2") . '</div>';
        } 
        save_mandant_link($input_id);
        save_category_link($input_id);
        save_unit_contact_list($input_id);
        edit_unit($input_id, $messages);
    } else {
        header('EDIT_ERROR: 1');
        $input_unit["id"]                = $_POST["input_id"];
        $input_unit["name"]              = $_POST["input_name"];
        $input_unit["email"]             = $_POST["input_email"];
        $input_unit["login"]             = $_POST["input_login"];
        require_once("learning_unit_cardform.inc.php");
    }
}

function save_unit_contact_list($unit_id){
    $datetime = new DateTime();
    $query = "SELECT * FROM main_contact WHERE active = 1 ORDER BY name ASC";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    while($row = @mysqli_fetch_array($result)) {
        $done = ($_POST["done_".$row['id']] == "on") ? 1 : 0;
        $active = ($_POST["active_".$row['id']] == "on") ? 1 : 0;
        $deleteActive = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM learning_unit_contact WHERE learning_unit_id=".$unit_id." AND main_contact_id = ".$row['id']);
        if($active == 1){
            $query_active = "INSERT INTO learning_unit_contact (learning_unit_id, main_contact_id, active)
            VALUES (
                '".$unit_id."',
                '".$row['id']."',
                '".$active."'
            )";
            $result_active = @mysqli_query($GLOBALS['mysql_con'], $query_active);
        }

        $query2 = "SELECT * FROM learning_unit_submit WHERE learning_unit_id = ".$unit_id." AND main_contact_id = ".$row['id']. " ORDER BY id DESC LIMIT 1";
        $result2 = @mysqli_query($GLOBALS['mysql_con'], $query2);
        $row2 = @mysqli_fetch_array($result2);
        $query3 = "";
        if($row2 != NULL){
            if($row2['correct'] != $done){
                $query3 = "UPDATE learning_unit_submit SET correct = ".$done.", datetime = '".$datetime->format('Y-m-d H:i:s')."' WHERE id = ".$row2['id'];
            }
        }else{
            if($done == 1){
                $query3 = "INSERT INTO learning_unit_submit (learning_unit_id, main_contact_id, datetime, correct)
                VALUES (
                    '".$unit_id."',
                    '".$row['id']."',
                    '".$datetime->format('Y-m-d H:i:s')."',
                    '".$done."'
                )";
            }
        }
        $result3 = @mysqli_query($GLOBALS['mysql_con'], $query3);
    }
}

function save_mandant_link($unit_id){
    $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM learning_unit_mandant_link WHERE learning_unit_id=".$unit_id);    

    $mandant_id = $_POST['select_mandant'];
    $mandante = explode(',', $mandant_id);
    if(!empty($mandant_id) && gettype($mandante) == 'array')  { 
        foreach($mandante as $key => $mandant){
            $query = "INSERT INTO learning_unit_mandant_link
            (learning_unit_id, main_mandant_id)
            VALUES (
                " .  $unit_id . ",
                '" . $mandant . "'
            )";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
    }
}

function save_category_link($unit_id){
    $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM learning_unit_link WHERE learning_unit_id=".$unit_id);    

    $ids = $_POST['select_category'];
    $categories = explode(',', $ids);
    if(!empty($categories) && gettype($categories) == 'array')  { 
        foreach($categories as $key => $category){
            $query = "INSERT INTO learning_unit_link
            (learning_unit_id, learning_category_id)
            VALUES (
                " .  $unit_id . ",
                '" . $category . "'
            )";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
    }
}

function create_mandant_select($unit_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 learning_unit_mandant_link WHERE learning_unit_id = ".$unit_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="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
}

function create_category_select($unit_id){
    $query = "SELECT * FROM learning_category";
    $unit_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    if (@mysqli_num_rows($unit_result) == 0) { 
        return;
    }
    
    $preselect = array();
    
    $query = "SELECT * FROM learning_unit_link WHERE learning_unit_id = ".$unit_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    while($row = @mysqli_fetch_array($result)){
        array_push($preselect,$row['learning_category_id']);
    }

?>
    <div class="label">Kategorie auswählen</div>
    <div class="unit 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($unit_category = @mysqli_fetch_array($unit_result)) {
                    echo "<div class=\"item\" data-value=\"{$unit_category['id']}\">".$unit_category["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('.unit.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });
    </script>
<?
}

function delete_line_unit() {
    if ($_REQUEST["input_line_id"] <> '') {
        $query = "DELETE FROM learning_unit_question WHERE id = '" . $_REQUEST["input_line_id"] . "' LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
        $queryDelete = "DELETE FROM learning_unit_answer WHERE question_id = '" .$_REQUEST["input_line_id"]."'";
        @mysqli_query($GLOBALS['mysql_con'], $queryDelete); 
    }
    edit_unit();
}

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

    if ($line_id <> '') {
        $query  = "SELECT * FROM learning_unit_question 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("learning_unit_line_cardform.inc.php");
}

function save_line_unit() {
    if ($_POST["input_line_id"] <> '') {
        $inserted = FALSE;
        $input_line_id = $_POST["input_line_id"];
        $query = "UPDATE learning_unit_question
			SET learning_unit_id = '" . $_POST['input_id'] . "',
			description = '" . $_POST['input_description'] . "',
			image = '" . $_POST['input_image'] . "',
			question_type = '" . $_POST['input_question_type'] . "'
			WHERE id = '" . $input_line_id . "' LIMIT 1";
    } else {
        $query = "INSERT INTO learning_unit_question (id, learning_unit_id, description, image, question_type) VALUES (
			NULL,
			'" . $_POST['input_id'] . "',
			'" . $_POST['input_description'] . "',
			'" . $_POST['input_image'] . "',
			'" . $_POST['input_question_type'] . "'
			)";
        $inserted = TRUE;
    }
    @mysqli_query($GLOBALS['mysql_con'], $query);
    if ($inserted == TRUE) {
        $input_line_id = mysqli_insert_id($GLOBALS['mysql_con']);
    }

    $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM learning_unit_answer WHERE question_id=".$input_line_id);    

    $num_inputs = 0;
    foreach ($_POST as $key => $value) {
      if (strpos($key, 'input_answer_') === 0) {
        $num_inputs++;
      }
    }

    for ($i = 1; $i <= $num_inputs; $i++) {
        $input_correct = ($_POST["input_correct_".$i] == "on") ? 1 : 0;

        $query = "INSERT INTO learning_unit_answer (id, question_id, description, correct) VALUES (
			NULL,
			'" . $input_line_id . "',
			'" . $_POST['input_answer_'.$i] . "',
			'" . $input_correct . "'
			)";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }

    edit_unit();
}

function unit_answers($question_id){
    $query  = "SELECT * FROM learning_unit_answer WHERE question_id = ".$question_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $i = 1;
    while($answer = @mysqli_fetch_array($result)) {
    $correct = ($answer['correct'] == "1") ? 'checked="checked"' : '';
    ?>
    <div class='answer_wrapper' data-id='<?= $i?>'>
        <label for='input_answer_"+count+"'><?= $i?>.</label>
        <input type='text' class='text' name='input_answer_<?= $i?>' id='input_answer_<?= $i?>' value='<?= $answer['description']?>'>
        <input type='checkbox' class='checkbox' name='input_correct_<?= $i?>' name='input_correct_<?= $i?>' <?= $correct?>>
        <div class='delete_answer'>X</div>
    </div>
    <?php
        $i++;
    }
    return $i;
}