<?php
$formname    = "form_certificate_card";
$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
$inputname   = "input_id";

$collection_setups = array();
$query             = "SELECT * FROM main_collection_setup WHERE (main_language_id = " . (int)$GLOBALS["language"]['id'] . " OR all_languages = 1)";
$result            = @mysqli_query($GLOBALS['mysql_con'], $query);
while ($row = @mysqli_fetch_array($result, 1)) {
    $collection_setups[$row['id']] = $row;
}

$collections    = array();
$collection_ids = array();
if ($input_certificate['main_collection_setup_id'] != "") {
    $query  = "SELECT * FROM main_collection WHERE main_collection_setup_id = " . $input_certificate['main_collection_setup_id'];
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    while ($row = @mysqli_fetch_array($result, 1)) {
        $collections[]    = $row['description'];
        $collection_ids[] = $row['id'];
    }
}
?>

<div id="overlaycrumb">
    <?php if ($input_certificate["id"] == "") {
        echo $translation->get("new_certificate");
    } else {
        echo $translation->get("edit_certificate");
    }
    ?>
    <div id="closeoverlay" onclick="disableOverlay();"></div>
</div>
    <ul class="toolbar_menu">
        <?= button("save", $translation->get("save"), $formname, "loadCard('save', true)"); ?>
        <?= button("save", $translation->get("save_and_close"), $formname, "loadCard('save', true, '', true)"); ?>
        <li>
            <ul>
                <?= button("delete", $translation->get("delete"), $formname, "loadCard('delete', true, '{$translation->get('delete_user_confirm')}', true)", "", FALSE); ?>
            </ul>
        </li>
    </ul>

<?php
if ($messages !== null) {
    if (count($messages)) {
            echo '<div id="overlayMessages">' . join("\r\n", $messages) . '</div>';
    } 
 }
 
?>

<form id="<?= $formname ?>" name="<?= $formname ?>" method="post">
    <input name="input_id" type="hidden" value="<?= $input_certificate["id"] ?>">

    <table class="cardform" border="0" cellspacing="0" cellpadding="0">
        <tr class="certificate_table_row">
            <td class="w-100">
                <? input($translation->get("title"), "input_title", "text", $input_certificate["title"], 255) ?>
                <? input($translation->get("description"), "input_description", "textarea", $input_certificate["description"]) ?>
            </td>
            <td class="w-100">
                <div class="basic_settings">
                    <div class="toggle_headline opened">
                        <h3><?= $translation->get("basic_settings") ?></h3>
                        <div class="chevron"></div>
                    </div>
                    <div class="toggle_area">
                        <div class="recurring_group">
                            <div class="recurring_input">
                                <? input($translation->get("recurring"), "input_recurring", "checkbox", $input_certificate["recurring"]) ?>
                            </div>
                                <?php
                                    $types = [
                                        '3' => "3 Monate",
                                        '6' => "6 Monate",
                                        '12' => "12 Monate",
                                        '24' => "24 Monate",
                                        '36' => "36 Monate (Mindestlaufzeit)",
                                    ];
                                    $preselect = 4;
                                    if(isset($input_certificate['validity_period']) ){
                                        $preselect = $input_certificate['validity_period'];
                                    }
                                ?>
                            <div class="recurring_select">
                                <? input_select($translation->get("validity_period"), "input_validity_period", $values = array_keys($types), $value_names = array_values($types), $preselect, FALSE, FALSE); ?>
                            </div>
                        </div>
                        <div class='basic_setting_inputs'>
                            <div class='collection_setup'>
                                <? create_collection_select($collection_setups, $translation->get("choose_collection_type"), "main_collection_setup_id", $input_certificate['main_collection_setup_id'], FALSE, TRUE, "loadPagesWithCollection(this.value);"); ?>
                            </div></div>
                            <div class="collection_pages">
                                <? create_page_with_collection_select($input_certificate['main_collection_setup_id'], $translation->get("page_with_collections"), "main_collection_page_list_id", $input_certificate['main_collection_page_list_id'], FALSE); ?>
                            </div></div>
                            <div class="collection_list_choose">
                                <? input_select($translation->get("choose_collection"), "main_collection_id", $values = $collection_ids, $value_names = $collections, $input_certificate["main_collection_id"], FALSE, FALSE); ?>
                            </div>
                        </div>
                </div>
                <?= create_mandant_select($input_certificate['id']); ?>
            </td>

        </tr>

    </table>
    <?php
    if ($input_certificate['id'] != "") {
        require_once 'certificate_contact_listform.inc.php';
    }?>
</form>

<script>

    $(document).ready(function(){
  $('#input_recurring').change(function(){
    if(this.checked){
      $('.recurring_select').show();
    }
    else{
      $('.recurring_select').hide();
    }
  });

  $(".toggle_headline").click(function() {
    $(this).next().slideToggle();
    $(this).toggleClass("opened");

})
});
</script>

<script type="text/javascript">
    function loadPagesWithCollection( collection_setup_id ) {
        load_collections(collection_setup_id);
        $('.collection_pages').html("");

        if (collection_setup_id == "" || collection_setup_id == 0) {
            return;
        }

        // ajax
        var formData = new FormData(jQuery('#<?php echo $formname; ?>')[0]);
        formData.append("collection_setup_id", collection_setup_id);
        formData.append("page_link_id", '<?php echo $input_line["id"]; ?>');
        $.ajax({
                   url        : "?action=load_collection_pages",
                   type       : 'POST',
                   data       : formData,
                   cache      : false,
                   processData: false, // Don't process the files
                   contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                   dataType   : 'json',
                   success    : function ( output, status, xhr ) {
                       
                       if (xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
                           window.location.replace("/mysyde/");
                       } else {
                           $('.collection_pages').html(output.page_with_collection_select);
                       }
                   },
                   error: function (jqXHR, exception) {
                        var msg = '';
                        if (jqXHR.status === 0) {
                            msg = 'Not connect.\n Verify Network.';
                        } else if (jqXHR.status == 404) {
                            msg = 'Requested page not found. [404]';
                        } else if (jqXHR.status == 500) {
                            msg = 'Internal Server Error [500].';
                        } else if (exception === 'parsererror') {
                            msg = 'Requested JSON parse failed.';
                        } else if (exception === 'timeout') {
                            msg = 'Time out error.';
                        } else if (exception === 'abort') {
                            msg = 'Ajax request aborted.';
                        } else {
                            msg = 'Uncaught Error.\n' + jqXHR.responseText;
                        }
                        console.log(msg);
                   }
                  
               });
    }

    function load_collections( collection_setup_id ) {
        $('.collection_list_choose').html("");
        var formData = new FormData(jQuery('#<?php echo $formname; ?>')[0]);
        formData.append("main_collection_setup_id", collection_setup_id);
        $.ajax({
                   url        : "?action=load_collections",
                   type       : 'POST',
                   data       : formData,
                   cache      : false,
                   processData: false, // Don't process the files
                   contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                   success    : function ( output, status, xhr ) {
                       if (xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
                           window.location.replace("/mysyde/");
                       } else {
                           $('.collection_list_choose').html(output);
                       }
                   },
                   error      : function ( jqXHR, textStatus, errorThrown ) {
                       //console.log('ERRORS: ' + textStatus);
                   }
               });
    }
</script>