{extends "../windowFrame.tpl"}
{block body_class}class="panel_frame"{/block}
{block content}
   <div class="container-fluid">
      <form name="editform" method="post" action="launch.php?s=products.parameters.php&amp;ID={$body.ID}" class="form-horizontal">
         <div class="row main-panel-title">
            <div class="col-md-6">
                {ifModule PARAMETER_GROUPS}
                   <div class="form-group pull-right" style="width:65%">
                      <div class="col-md-6 control-label">
                         <label>{'parameterGroup'|translate:'products'}</label>
                      </div>
                      <div class="col-md-6">
                         <select class="selecter" name="data[id_parameter_group]" data-type="parameter_groups"
                                 data-preload="parameterGroups"
                                 id="productsFrm_id_parameter_group">
                             {if $body.data.id_parameter_group}
                                <option value="{$body.data.id_parameter_group}" selected>{$body.data.id_parameter_group}</option>
                             {else}
                                <option value="">{'notSelected'|translate:'products'}</option>
                             {/if}
                         </select>
                      </div>
                   </div>
                {/ifModule}

               <h1 class="h4">
                   {'sectionParameters'|translate:'products'}
               </h1>
            </div>

            <div class="col-md-3">
               <p class="input-height pull-right">
                  <small>Zobrazit všechny parametry</small>
               </p>
            </div>
            <div class="col-md-1">
                {print_toggle name="show_all_params"}
            </div>
            <div class="col-md-2">
               <select class="selecter" data-add-parameter="" data-placeholder="Zobrazit parametr">
                  <option value=""></option>
                  <option value="new">-- Vytvořit nový parametr --</option>
                   {foreach $body.parameters as $parameter}
                      <option value="{$parameter.id}">{$parameter.name}</option>
                   {/foreach}
               </select>
               <script>
                   {ifModule PARAMETER_GROUPS}
                   var productParameterGroup_applyChosen = function ($selector) {
                      $selector.ajaxChosen({
                         minTermLength: 0,
                         dataType: 'json',
                         type: 'GET',
                         url: 'launch.php?s=autocomplete.php&type=' + $selector.data('type')
                      }, function (data) {
                         return data;
                      }, {
                         width: '100%',
                         allow_single_deselect: true,
                         placeholder_text_single: 'Vyberte možnost',
                         placeholder_text_multiple: 'Vyberte několik možností'
                      });
                   }
                   productParameterGroup_applyChosen($('#productsFrm_id_parameter_group'));
                   {/ifModule}

                   $('[data-add-parameter]').on('change', function () {
                      var me = $(this);

                      if (me.val() > 0) {
                         var $parameter = $('#parameters_' + me.val());
                         $parameter.show();
                         // scroll to parameter
                         $('html, body').animate({
                            scrollTop: $parameter.offset().top
                         }, 1000);
                      }

                      if (me.val() === 'new') {
                         createParameter();
                      }

                      // reset select
                      me.chosen('destroy');
                      me.prop('selectedIndex', 0);
                      me.chosen();
                   });

                   $('[data-add-parameter]').on('chosen:no_results', function (event, element) {
                      var $noResults = $(element.chosen.search_results).find('.no-results'),
                         value = $(element.chosen.search_results).find('span').text();

                      $noResults.attr('onclick', 'createParameter("' + value + '")');
                      $noResults.css('cursor', 'pointer');
                      $noResults.html('Žádný výsledek. Kliknutím vytvořit parametr <span>' + value + '</span>');
                   });

                   function createParameter(value) {
                      if (value != undefined) {
                         nw('parameters', null, 'data[name]=' + value);
                      } else {
                         nw('parameters');
                      }

                      return false;
                   }
               </script>
            </div>
         </div>

          {foreach $body.parameters as $id_parameter => $row}
             <div id="parameters_{$row.id}" class="parameters {if empty($row.active) && empty($row.values)}params_hidden{/if}"
                  {if empty($row.active) && empty($row.values)}style="display:none"{/if}>
                <div class="panel panel-default">
                   <div class="panel-heading panel-heading-sm" style="padding-top: 0;padding-bottom: 0;">
                      <div class="row">
                         <div class="col-md-5">
                            <h5>
                                {$row.name}
                               <a href="#" onclick="nw('parameters', '{$row.id}')">
                                  <span class="badge badge-default" style="margin-left: 10px">
                                     <i class="glyphicon glyphicon-cog"></i>
                                  </span>
                               </a>
                            </h5>
                         </div>
                          {if findModule('products_parameters', 'configurations')}
                             <div class="col-md-3 control-label" style="padding-top: 15px;">
                                <label>Volitelné u produktu</label>
                                <a class="help-tip" data-toggle="tooltip"
                                   title="Požadovat od zákazníka vybrat hodnotu parametru před vložením do košíku. Zvolíte-li příplatek, tato částka se přičte k ceně produktu."
                                   style="margin-top: 7px;">
                                   <i class="bi bi-question-circle"></i>
                                </a>
                             </div>
                             <div class="col-md-1" style="padding-top: 8px;">
                                 {print_toggle name="param][{$id_parameter}][parameters_configurations" value=$row.parameter_configuration class='parameters-configurations-toggle'}
                             </div>
                          {/if}

                          {* List values autocomplete *}
                          {if $row.value_type == 'list'}
                             <div class="col-md-4">
                                <input type="text" data-autocomplete-search="product_parameter_values_{$row.id}" autocomplete="off"
                                       class="form-control input-sm autocomplete-control" name="addParameterValue"
                                       placeholder="Rychlý výběr...">
                             </div>
                             <script type="application/javascript">
                                function _addParameterValue (me, itemIndex, valueId, parameterId, name) {
                                   var exists = me.getExistItems();

                                   if (!me.data.items[itemIndex]) {
                                      return false;
                                   }

                                   if (exists.indexOf(me.data.items[itemIndex]['id']) !== -1)
                                      return false;

                                   // add item
                                   $('[data-form-add="' + parameterId + '"]').click();

                                   var $addedItem = $('[data-autocomplete-items="' + parameterId + '"] [data-form-item]:first');
                                   $addedItem.attr('data-form-item', valueId);

                                   unstyleFormInputs($addedItem);
                                   $addedItem.find('select').append($('<option>', {
                                      value: valueId,
                                      text: name,
                                   }).prop('selected', 'selected'));
                                   styleFormInputs($addedItem);

                                   if (!me.options.$menu) {
                                      return;
                                   }

                                   var $autocompleteItem = me.options.$menu.find('[data-autocomplete-item="' + itemIndex + '"]');

                                   if (!$autocompleteItem) {
                                      return;
                                   }

                                   // mark item as added
                                   $autocompleteItem.find('.btn').text('').html('<span class="glyphicon glyphicon-ok"></span>').addClass('added');
                                }

                                $('[data-autocomplete-search="product_parameter_values_{$row.id}"]').multiAddAutoComplete({
                                   formWrapper: '{$row.id}',
                                   type: 'parametersListValuesByParameter',
                                   minLength: 0,
                                   parameters: 'id_parameter={$row.id}',
                                   subtemplates: {
                                       {literal}
                                      menuItem: '<div tabindex="-1" data-autocomplete-item="{{=index}}" data-autocomplete-value-id="{{=item.id}}" data-autocomplete-parameter-id="{{=item.id_parameter}}">' +
                                         '{{? item.parameter_type === "image"}} <img src="{{=item.description }}" alt="Obrázek"/> {{?}}  <p> {{=item.text}} <br></p>' +
                                         '{{#def.buttons}}' +
                                         '</div>',
                                      buttons: '<button type="button" class="btn btn-default add{{? it.exists.indexOf(item.id) !== -1}} added{{?}}" data-autocomplete-add>' +
                                         '{{? it.exists.indexOf(item.id) !== -1}}<span class="glyphicon glyphicon-ok"></span>{{??}}Přidat{{?}}' +
                                         '</button>'
                                       {/literal}
                                   },
                                    {block 'autocomplete-parameters-config'}
                                    {/block}
                                   addItems: function (e, items, me) {
                                      items.items.forEach((item, index) => {
                                         _addParameterValue(me, index, item.id, item.id_parameter, item.text);
                                      });

                                      return false;
                                   },
                                   addItem: function (e, $item, me) {
                                      var itemIndex = $item.data('autocomplete-item'),
                                         valueId = $item.data('autocomplete-value-id'),
                                         parameterId = $item.data('autocomplete-parameter-id');

                                      var name = $item.find('p')[0].textContent.trim();

                                      _addParameterValue(me, itemIndex, valueId, parameterId, name);
                                   },
                                });
                             </script>
                             <script>

                             </script>
                          {/if}

                         <div class="col-md-2 pull-right text-right">
                            <a href="#" class="btn btn-sm btn-success" data-form-add="{$row.id}"><span
                                  class="glyphicon glyphicon-plus"></span>&nbsp;Přidat
                               hodnotu</a>
                         </div>
                      </div>
                   </div>
                    {block "parameter-values"}
                       <div class="list-group" id="parameters_{$row.id}" data-input-area="{$row.id}" data-autocomplete-items="{$row.id}">
                           {foreach array_merge([['id' => 0]], $row.values|default:[]) as $id_value => $value}
                              <div class="list-group-item" {if $value@index == 0}data-form-new style="display:none"
                                   {else}data-form-item="{$value.value}"{/if}>
                                 <div class="row">
                                    <div class="col-md-5">
                                        {if $row.value_type == "list" and $row.value_meaning == 'text'}
                                           <select type="text" id="param{$row.id}" name="data[param][{$id_parameter}][{$value.id}][value]"
                                                   class="selecter"
                                                   data-preload="ParametersValuesOnly"
                                                   data-filter-type="autocomplete" data-autocomplete="parametersListValuesByParameter"
                                                   data-autocomplete-params="id_parameter={$row.id}">
                                              <option value="{$value.value}" selected="selected">
                                              </option>
                                           </select>
                                        {elseif $row.value_type == "list"}
                                           <select id="param{$row.id}" name="data[param][{$id_parameter}][{$value.id}][value]"
                                                   class="selecter">*}
                                               {if $value@index == 0}
                                               <option value="" {if $value.value == ''}selected="selected"{/if}>&nbsp;</option>{/if}
                                               {foreach $row->fetchListValues() as $list_value}
                                                  <option value="{$list_value.id}"
                                                          {if $row.value_meaning == 'color'}style="background:{$list_value.value}"{/if} {if $list_value.id == $value.value}selected="selected"{/if}>{$list_value.value}</option>
                                               {/foreach}
                                           </select>
                                        {else}
                                            {if $row.value_meaning == 'color'}
                                               <input type="color" class="form-control input-sm" id="param{$row.id}"
                                                      name="data[param][{$id_parameter}][{$value.id}][value]" size="10"
                                                      value="{$value.value}">
                                            {elseif $row.value_meaning == 'image'}
                                               <div class="input-group">
                                                  <input type="text" class="form-control input-sm" id="param{$row.id}"
                                                         name="data[param][{$id_parameter}][{$value.id}][value]" size="10"
                                                         value="{$value.value}">
                                                  <div class="input-group-btn">
                                                      {insert_file_browse link="attachLink"}
                                                  </div>
                                               </div>
                                            {else}
                                               <input type="text" class="form-control input-sm" id="param{$row.id}"
                                                      name="data[param][{$id_parameter}][{$value.id}][value]" size="10" maxlength="255"
                                                      value="{$value.value}" {if $row.value_type == "float"} onkeypress="checkInputData('float')"{/if}>
                                            {/if}
                                        {/if}
                                    </div>
                                    <div class="col-md-2">
                                        {if $row.unit|@count > 1 }
                                           <select name="data[param][{$id_parameter}][{$value.id}][unit]" class="selecter">
                                               {foreach $row.unit as $unit}
                                                  <option value="{$unit}" {if $unit == $value.unit}selected{/if}>{$unit}</option>
                                               {/foreach}
                                           </select>
                                        {else}
                                            {if $row.unit.0}
                                               <span style="display: inline-block; padding-top: 5px;">{$row.unit.0}</span>
                                            {/if}
                                           <input type="hidden" name="data[param][{$id_parameter}][{$value.id}][unit]" value=""/>
                                        {/if}
                                    </div>

                                     {if findModule('products_parameters', 'configurations')}
                                        <div class="col-md-3">
                                           <div class="input-group parameters-configurations"
                                                {if !$row.parameter_configuration}style="display: none"{/if}>
                                              <label class="input-group-addon">Příplatek</label>
                                              <input type="text" class="form-control text-center input-sm"
                                                     name="data[param][{$id_parameter}][{$value.id}][configuration_price]"
                                                     value="{$value.configuration_price}" placeholder="0">
                                              <span class="input-group-addon">{$dbcfg.currency}</span>
                                           </div>
                                        </div>
                                     {/if}

                                     {block parameterValueCustom}{/block}

                                    <div class="col-md-1 pull-right text-right">
                                       <a class="btn-sm btn btn-danger" data-form-delete>
                                          <input class="hidden" type="checkbox" name="data[param][{$id_parameter}][{$value.id}][delete]"/>
                                          <span class="glyphicon glyphicon-remove"></span>
                                       </a>
                                    </div>
                                 </div>
                              </div>
                           {/foreach}
                          <script type="application/javascript">
                             initForm({
                                selector: '#parameters_{$row.id}',
                                beforeAdd: function (callback) {
                                   var $item = callback();
                                   $item.find("#param{$row.id}").focus();
                                   window.preloadAutocompletes($item);
                                }
                             });
                          </script>
                       </div>
                    {/block}
                </div>
             </div>
          {/foreach}

         <div class="row bottom-space">
            <div class="col-md-4">
               <input type="submit" class="btn btn-primary btn-block" name="submit" data-type="save"
                      value="{'saveParameters'|translate:'products'}">
            </div>
         </div>
      </form>
   </div>
   <script>
      var show_all = false;

      $('[name="data[show_all_params]"]').parent().find('.handle').on('click', function () {
         show_all = !show_all;
         if (show_all) {
            $('.params_hidden').fadeIn(500);
         } else {
            $('.params_hidden').fadeOut(500);
         }
      });

      $('.parameters-configurations-toggle input').change(function () {
         if (typeof $(this).attr('checked') !== 'undefined') {
            $(this).closest('.parameters').find('.parameters-configurations').fadeIn(500);
         } else {
            $(this).closest('.parameters').find('.parameters-configurations').fadeOut(500);
         }
      });
   </script>
{/block}
