<?
switch ($_GET["action"]) {
    case 'edit':
        edit_certificate();
        break;
    case 'delete':
        delete_certificate($certificate['id']);
        break;
    case 'new':
        require_once("certificate_cardform.inc.php");
        break;
    case 'save':
        save_certificate();
        break;
    case 'save_line_certificate':
        save_line_certificate();
        break;
    case 'new_line_certificate':
        require_once("certificate_line_cardform.inc.php");
        // new_line_certificate();
        break;
    case 'edit_line_certificate':
        edit_line_certificate();
        break;
    case 'delete_line_certificate':
        delete_line_certificate();
        break;
    case 'moveup_line_certificate':
        moveup_line_certificate();
        edit_certificate();
        break;
    case 'movedown_line_certificate':
        movedown_line_certificate();
        edit_certificate();
        break;
    case 'open_card':
        open_card();
    case 'load_collection_pages' : load_collection_pages(); break;
    case 'load_collections' :  load_collections(); break;
    default:
        require_once("certificate_listform.inc.php");
        break;
}

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

function edit_certificate( $_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 main_certificate 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_certificate = $result[0];
            require_once("certificate_cardform.inc.php");
        }
    } else {
        $input_certificate = array();
        require_once("certificate_cardform.inc.php");
    }
}

function delete_certificate() {
    if ($_POST["input_id"] <> '') {
        $query = "DELETE FROM main_certificate WHERE id = '" . $_POST["input_id"] . "' LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
}

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

    $input_recurring = ($_POST["input_recurring"] == "on") ? 1 : 0;

    if ($_POST["input_id"] <> '') {
        $inserted = FALSE;
        $input_id = $_POST["input_id"];
        $query = "UPDATE main_certificate
			SET title = '" . $_POST['input_title'] . "',
			description = '" . $_POST['input_description'] . "',
			recurring = '" . $input_recurring . "',  
			validity_period = '" . $_POST['input_validity_period'] . "',
			access_type = '" . $_POST['input_access_type'] . "',
			main_collection_page_list_id = '" . $_POST['main_collection_page_list_id'] . "',
			main_collection_setup_id = '" . $_POST['main_collection_setup_id'] . "',
			main_collection_id = '" . $_POST['main_collection_id'] . "'
			WHERE id = '" . $_POST["input_id"] . "' LIMIT 1";
    } else {
        $query    = "INSERT INTO main_certificate (id, title, description, recurring, validity_period, access_type, main_collection_page_list_id, main_collection_setup_id, main_collection_id) VALUES (
			NULL,
			'" . $_POST['input_title'] . "',
			'" . $_POST['input_description'] . "',
			'" . $input_recurring . "',
			'" . $_POST['input_validity_period'] . "',
			'" . $_POST['input_access_type'] . "',
			'" . $_POST['main_collection_page_list_id'] . "',
			'" . $_POST['main_collection_setup_id'] . "',
			'" . $_POST['main_collection_id'] . "'
			)";
        $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("certificate_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("certificate_msg_success2") . '</div>';
        } 

        $mandant_ids = $_POST['select_mandant'];
        $mandant = explode(',', $mandant_ids);
        if(!empty($mandant) && gettype($mandant) == 'array')  { 
            $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM certificate_mandant_link WHERE main_certificate_id = ".$input_id);    
            foreach($mandant as $key => $mandant_value){
                $query = "INSERT INTO certificate_mandant_link
                (main_certificate_id, main_mandant_id)
                VALUES (
                    " . $input_id . ",
                    " . $mandant_value . "
                )";
                @mysqli_query($GLOBALS['mysql_con'], $query);
            }
        }
        save_certificate_contact_list($input_id);
        edit_certificate($input_id, $messages);
    } else {
        require_once("edit_certificate_cardform.inc.php");
    }
}

function save_certificate_contact_list($certificate_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 certificate_contact WHERE certificate_id=".$certificate_id." AND main_contact_id = ".$row['id']);
        if($active == 1){
            $query_active = "INSERT INTO certificate_contact (certificate_id, main_contact_id, active)
            VALUES (
                '".$certificate_id."',
                '".$row['id']."',
                '".$active."'
            )";
            $result_active = @mysqli_query($GLOBALS['mysql_con'], $query_active);
        }

        $query2 = "SELECT * FROM certificate_contact_submit WHERE certificate_id = ".$certificate_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 certificate_contact_submit SET correct = ".$done.", issue_date = '".$datetime->format('Y-m-d H:i:s')."' WHERE id = ".$row2['id'];
            }
        }else{
            if($done == 1){
                $query3 = "INSERT INTO certificate_contact_submit (certificate_id, main_contact_id, issue_date, correct)
                VALUES (
                    '".$certificate_id."',
                    '".$row['id']."',
                    '".$datetime->format('Y-m-d H:i:s')."',
                    '".$done."'
                )";
            }
        }
        $result3 = @mysqli_query($GLOBALS['mysql_con'], $query3);
    }
}

function load_collection_pages() {
	$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
	ob_start();
	create_page_with_collection_select($_POST['collection_setup_id'], $translation->get("page_with_collections"), "main_collection_page_list_id", array(), false);
	$output1 = ob_get_clean();
	
	$active_groups = array();
	$query = "SELECT main_collection_setup_group_id from main_page_collection_group_link where main_page_link_id = '" . $_POST['page_link_id']."'";
	$result = @mysqli_query($GLOBALS['mysql_con'],$query);
	while ($row = @mysqli_fetch_array($result)) {
		$active_groups[] = $row['main_collection_setup_group_id'];	
	}	
	ob_start();
	create_collection_preview_group_select($_POST['collection_setup_id'], $_POST['page_link_id'], $active_groups);
	$output2 = ob_get_clean();
	
	echo json_encode(array('page_with_collection_select' => $output1, 'collection_preview_group_select' => $output2));
}

function load_collections() {
	// ajax call
	$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
	$setup_id = $_POST['main_collection_setup_id'];
	$collections = array();
	$collection_ids = array();
	if($setup_id != "") {
		$query = "SELECT * FROM main_collection WHERE main_collection_setup_id = '" . $setup_id . "'";
		$result = @mysqli_query($GLOBALS['mysql_con'],$query);
		while ($row = @mysqli_fetch_array($result,1)) {
			$collections[] = $row['description'];
			$collection_ids[] = $row['id'];
		}
	}
	
	input_select($translation->get("choose_collection"),"main_collection_id",$values = $collection_ids,$value_names = $collections,"", false, false);
}

function create_mandant_select($category_id){
    $translation   = \DynCom\mysyde\common\classes\Registry::get("translation");
    $query = "SELECT * FROM main_mandant";
    $mandant_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    $preselect = array();
    
    $query = "SELECT * FROM certificate_mandant_link WHERE main_certificate_id = ".$category_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    while($row = @mysqli_fetch_array($result)){
        array_push($preselect,$row['main_mandant_id']);
    }
    $allselect = array();
    ?>
    <div class="label"><?php echo $translation->get("mandant")?></div>
    <div class="mandant bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
        <input type="hidden" name="select_mandant">
        <i class="dropdown icon"></i>
        <div class="default text"><?php echo $translation->get("mandant")?></div>
        <div class="menu">
            <?  
                while($mandant = @mysqli_fetch_array($mandant_result)) {
                    array_push($allselect,$mandant['id']);
                    echo "<div class=\"item\" data-value=\"{$mandant['id']}\">".$mandant["description"]."</div>";
                }
            ?>
        </div>
    </div>
    <div class='all_mandants' ><?php echo $translation->get("all_mandants")?></div>
    <script type="text/javascript" src="/plugins/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="/plugins/Semantic-UI-master/semantic.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/plugins/Semantic-UI-master/bc-semantic.css?time=<?= filemtime($_SERVER['DOCUMENT_ROOT'] . '/plugins/Semantic-UI-master/bc-semantic.css')?>">
    <script>
        var $y = jQuery.noConflict();

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

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

    </script>
<?
}