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

$sitepart_options = array();
if (isset($input_line['options'])) {
    $sitepart_options = unserialize($input_line['options']);
}
 
?>

<script type="text/javascript">

    $(document).ready(function(){
        loadFields();
    })

    function setCollectionType( _select ) {
        var collectiontype = jQuery(_select).find('option:selected').parent().attr('value');
        jQuery('#collection_type', jQuery('#<?php echo $formname; ?>')).val(collectiontype);
        if (collectiontype == 'siteparts') {
            load_sitepart_settings(jQuery(_select).val());
        } else {
            jQuery('#collection_type_settings').html('');
        }
    }

    function loadFields() {

        let _sitepartId = $('#main_input_choose_type').val();

        //Zeichenlängefeld
        if( _sitepartId == 1 || _sitepartId == 2 ) {
            $('#main_input_maxlength').closest('tr').show();
        } else {
            $('#main_input_maxlength').val('').closest('tr').hide();
        }

        //Zeichenlängefeld
        if( _sitepartId == 6 || _sitepartId == 7 ) {
            $('#main_input_option_string').closest('tr').show();
        } else {
            $('#main_input_option_string').val('').closest('tr').hide();
        }

        //Zeichenlängefeld
        if( _sitepartId == 2) {
            $('#main_input_is_bulletlist').closest('tr').show();
        } else {
            $('#main_input_is_bulletlist').val('').closest('tr').hide();
        }


    }

    function load_sitepart_settings( _sitepartId ) {

        loadFields();

        jQuery('#collection_type_settings').html('');
        var formData = new FormData(jQuery('#<?php echo $formname; ?>')[0]);
        formData.append("sitepartid", _sitepartId);
        $.ajax({
                   url        : "?action=load_sitepart_form",
                   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 {
                           jQuery('#collection_type_settings').html(output);
                       }
                   },
                   error      : function ( jqXHR, textStatus, errorThrown ) {
                       //console.log('ERRORS: ' + textStatus);
                   }
               });
    }

</script>

<div id="overlaycrumb">
    <?php if ($input_line["id"] == "") {
        echo $translation->get("new_collection_field");
    } else {
        echo $translation->get("edit_collection_field");
    }
    ?>
    <div id="closeoverlay" onclick="disableOverlay();"></div>
</div>

<ul class="toolbar_menu">
    <?php
    // Zurueck zur uebersicht
    button("left", $translation->get("back"), $formname, "loadCard('edit_collection_setup', true)");

    // Speichern buttons
    button("save", $translation->get("save"), $formname, "loadCard('save_line_collection_setup', true)");
    button("save", $translation->get("save_and_close"), $formname, "jQuery('#save_and_close', jQuery('#" . $formname . "')).val(1);loadCard('save_line_collection_setup', true)");

    if ($input_line["id"] != "") {
        echo button("delete", $translation->get("delete"), $formname, "loadCard('delete_line_collection_setup', true, '{$translation->get('delete_line_confirm')}')");
    }
    ?>
</ul>
<div class="clearfix"></div>

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


$is_teaser = 1;
if (isset($input_line["is_teaser"])) {
    $is_teaser = $input_line["is_teaser"];
}

$show_description_title = 0;
if (isset($input_line["show_description_title"])) {
    $show_description_title = $input_line["show_description_title"];
}

$is_bulletlist = 0;
if (isset($input_line["is_bulletlist"])) {
    $is_bulletlist = $input_line["is_bulletlist"];
}
?>

<form id="<?= $formname ?>" name="<?= $formname ?>" method="post">
    <input name="input_line_id" type="hidden" value="<?= $input_line["id"] ?>" />
    <input name="input_id" type="hidden" value="<?= $_REQUEST['input_id'] ?>">
    <input type="hidden" name="collection_type" id="collection_type" value="<?= $input_line["fieldtype"]; ?>" />
    <input name="save_and_close" id="save_and_close" type="hidden" value="0" />

    <table class="cardform" border="0" cellspacing="0" cellpadding="0">
        <?php if ($input_line['fieldtype'] == 'standard'): ?>
            <tr>
                <td>
                    <? create_type_select($translation->get("choose_type"), "main_input_choose_type", $input_line); ?>
                </td>
                <td>

                </td>
            </tr>
        <?php else: ?>
            <input type="hidden" name="main_input_choose_type" value="<?php echo $input_line['type_id']; ?>" />
        <?php endif; ?>
        
        <?php if ($input_line['fieldtype'] == 'standard') { ?>
        <tr>
            <td>
                <? input($translation->get("input_maxlength"), "main_input_maxlength", "number", $input_line["input_maxlength"]) ?>
            </td>

            <td>
            </td>
        </tr>  
        <?php } ?>

        <tr>
            <td>
            <?php if ($input_line['fieldtype'] != 'group' && $input_line['fieldtype'] != 'collection_preview') { ?>
                <? input($translation->get("note"), "main_input_note", "text", $input_line["note"]) ?>
            <?php } else{ ?>   
                <input type="hidden" name="main_input_note" value="" />
            <?php } ?> 
            </td>

            <td>
            </td>
        </tr>

        <tr>
            <td>
                <? input($translation->get("textkey"), "main_input_code", "code", $input_line["code"], 255) ?>
            </td>

            <td>

            </td>
        </tr>

        <tr>
            <td>
                <? input($translation->get("description"), "main_input_description", "text", $input_line["fieldname"], 45) ?>
            </td>
 
        </tr>
        <?php if($input_line['fieldtype'] == 'siteparts' && $input_line['type_id'] == '10'){ ?>
        <tr>
            <td>
                <? input($translation->get("height_px"), "height", "text", $input_line["height"], 45) ?>
            </td>
            <td>
                <? input($translation->get("width_px"), "width", "text", $input_line["width"], 45) ?>
            </td>
        </tr>
        <?php } ?>    
        <?php if($input_line['type_id'] == 8889){
         ?>
         <tr>
            <?php   
                $forms    = array();
                $form_ids = array();
                $forms[]    = '-----';
                $form_ids[] = 0;
                $query = "SELECT * FROM contactform_header WHERE is_survey = 0 AND is_multistep = 0 AND main_language_id = ".$GLOBALS["language"]['id'];
               
                if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
                    $num_rows = @mysqli_num_rows($result);
                    if ($num_rows >= 1) {
                        while($row = @mysqli_fetch_array($result)){
                            $forms[]    = $row['description'];
                            $form_ids[] = $row['id'];
                        }
                        
                    }
                }    
            ?>
            <td>
                    <? input_select($translation->get("select_contactform"), "select_contactform", $form_ids, $forms, $input_line['option_string']); ?>
                </td>
        </tr>        

        <?php }?>
          <?php if($input_line['type_id'] == 8888 && $input_line["id"] != ''){
         ?>
         <input type="hidden" name="preview_settings" value="1">
         <tr>
            <?php   
                $collections    = array();
                $collection_ids = array();
                $collections[]    = '-----';
                $collection_ids[] = 0;
                $query = "SELECT * FROM main_collection_setup WHERE  main_language_id = ".$GLOBALS["language"]['id'];
                
               
                if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
                    $num_rows = @mysqli_num_rows($result);
                    if ($num_rows >= 1) {
                        while($row = @mysqli_fetch_array($result)){
                            $collections[]    = $row['description'];
                            $collection_ids[] = $row['id'];
                        }
                        
                    }
                }    
            ?>
            </tr>
            <tr>
                <td>
                <?php
                    
                    $dataLinked = array();
                    $query = "SELECT * FROM main_collection_setup_preview WHERE main_collection_setup_id = ".$_REQUEST['input_id']." AND field_id = ".$input_line['id'];
                    $result            = @mysqli_query($GLOBALS['mysql_con'], $query);
  
                    while ($row = @mysqli_fetch_array($result, 1)) {
                        $dataLinked = $row;
                    }
                     
                ?>
                    <? input_select($translation->get("select_setup"), "select_setup", $collection_ids, $collections, $dataLinked['main_collection_setup_id_selected'], FALSE, FALSE, "onchange='loadPagesWithCollection(this.value);'"); ?>
                </td>
            </tr> 
            <tr> 
                <td>
                    
                    <? input_select($translation->get("collection_preview_type"), "main_collection_view_type", $values = array('0', '1'), $value_names = array($translation->get("single_collection"), $translation->get("collection_list")), $dataLinked['main_collection_view_type'], FALSE, FALSE, 'onchange="toggle_view_type(this.value);"'); ?>
                </td>
            </tr> 
            <tr>   
                <td>
                    <img class="loader" style="display:none;" src="/layout/admin/img/icons/ajax-loader.gif" />

                    <div class="collection_pages">
                        <?
                        $dataLinked['main_collection_setup_id'] =  $dataLinked['main_collection_setup_id_selected'];
                        create_page_with_collection_select($dataLinked['main_collection_setup_id'], $translation->get("page_with_collections"), "main_collection_page_list_id", $dataLinked, FALSE);
                        ?>
                    </div>
                </td>
            </tr> 
            <tr>       
                <td>

                    <?php
                     $display_list_choose;
                    if ($dataLinked["main_collection_view_type"] == 0) {
                        $display_list_choose = '';
                        $display_item_choose = 'style="display:none;"';
                    } else {
                        $display_item_choose = '';
                        $display_list_choose = 'style="display:none;"';
                    }

                    // einzelne kollektion
                    echo "<div class=\"collection_list_choose\" " .$display_list_choose." >";
                    $collections    = array();
                    $collection_ids = array();
                    $query  = "SELECT DISTINCT  mc.* FROM main_collection as mc  WHERE mc.main_collection_setup_id = " . $_REQUEST['input_id'];
                    if (!empty($dataLinked) && $dataLinked['main_collection_setup_id'] != "") {
                        $query  = "SELECT DISTINCT   mc.* FROM main_collection as mc WHERE mc.main_collection_setup_id = " . $dataLinked['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'];
                    }
                    
                    input_select($translation->get("choose_collection"), "main_collection_id", $values = !empty($dataLinked) ? $collection_ids : array(), $value_names = !empty($dataLinked) ? $collections : array(), $dataLinked['main_collection_id_selected'], FALSE, FALSE);
                    echo "</div>";
                  

                    // kollektionsliste
                    echo "<div class=\"collection_items_choose\" " . $display_item_choose . ">";
                    $items = 990;
                     
                    input($translation->get("collection_list_items"), "main_collection_items", "text", $items , 255);
                     
                     
                    // input($translation->get('job_specific'), 'job_selected'.$fieldSetup['id'], 'checkbox', $dataLinked["job_selected"] );
                    echo "</div>";
                    ?>

                </td>
        </tr>        

        <?php } else {?>
            <input type="hidden" name="preview_settings" value="0">
        <?php }?>    
       
        <?php if ($input_line['fieldtype'] == 'standard') { ?>
        <tr>
            <td>
                <? input($translation->get("optionvalues"), "main_input_option_string", "text", $input_line["option_string"], 400) ?>
            </td>

            <td>
            </td>
        </tr>
        <?php } ?>

        <tr>
            <td>
                <? input($translation->get("is_bulletlist"), "main_input_is_bulletlist", "checkbox", $is_bulletlist) ?>
            </td>

            <td>

            </td>
        </tr>
        <?php if ($input_line['fieldtype'] != 'group' && $input_line['fieldtype'] != 'collection_preview' && $input_line['type_id'] != 16) { ?>
        <tr>
            <td>
                <? input($translation->get("show_in_teaser"), "main_input_is_teaser", "checkbox", $is_teaser) ?>
            </td>

            <td>

            </td>
        </tr>

        <tr>
            <td>
                <? input($translation->get("show_description_title"), "main_input_show_description_title", "checkbox", $show_description_title) ?>
            </td>

            <td>

            </td>
        </tr>
            <?php } ?>
    </table>

    <div id="collection_type_settings">
        <?php
        if ($input_line['fieldtype'] == 'siteparts' && $input_line['type_id'] > 0) {
            $sitepartCode   = $siteparts[$input_line['type_id']]['code'];
            $sitepartfolder = $siteparts[$input_line['type_id']]['folder'];

            $include = MODULE_PATH . $sitepartfolder . "/collection_" . $sitepartCode . "_cardform.inc.php";
            if (file_exists($include)) {
                require_once($include);
            }
        } elseif ($input_line['fieldtype'] == 'standard' && $input_line['type_id'] == 5) {
            $include = MODULE_PATH . "collection/edit_collection_image_config.inc.php";
            if (file_exists($include)) {
                require_once($include);
            }
        }
        ?>
    </div>

</form>
<script type="text/javascript">
    function loadPagesWithCollection( collection_setup_id ) {
        load_collections(collection_setup_id);
        console.log('hello');
        $('.collection_pages', $('#<?php echo $formname; ?>')).html("");
        $('.collection_preview_group_select_container', $('#<?php echo $formname ?>')).html("");

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

        $('.loader', $('#<?php echo $formname ?>')).show();

        // 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"]; ?>');
        formData.append("input_id", $('input[name=input_line_id]').val());
         
        
        $.ajax({
                   url        : "?action=loadPage_collection",
                   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 ) {
                       console.log('log ist' + xhr.getResponseHeader('REQUIRES_AUTH'));
                       if (xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
                           window.location.replace("/mysyde/");
                       } else {
                           $('.loader').hide();
                           $('.collection_pages' ).html(output.page_with_collection_select);
                           $('.collection_preview_group_select_container' ).html(output.collection_preview_group_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("");
        console.log('form name ist' + '<?php echo $formname; ?>');
        var formData = new FormData(jQuery('#<?php echo $formname; ?>')[0]);
        formData.append("main_collection_setup_id_", collection_setup_id);
        formData.append("input_id", $('input[name=input_line_id]').val());
         
        
        $.ajax({
                   url        : "?action=load_collection",
                   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 ) {
                    console.log(output);
                       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);
                   }
               });
    }

    function toggle_view_type( _type ) {
        if (_type == 0) {
            $('.collection_list_choose' ).show();
            $('.collection_items_choose' ).hide();
        } else {
            $('.collection_list_choose' ).hide();
            $('.collection_items_choose' ).show();
        }
    }

    
</script>