{#**
 * Copyright since 2007 PrestaShop SA and Contributors
 * PrestaShop is an International Registered Trademark & Property of PrestaShop SA
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.md.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to https://devdocs.prestashop.com/ for more information.
 *
 * @author    PrestaShop SA and Contributors <contact@prestashop.com>
 * @copyright Since 2007 PrestaShop SA and Contributors
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 *#}
{% block typeahead_product_collection_widget %}
    <div
      class="autocomplete-search"
      data-formid="{{ form.vars.id }}"
      data-fullname="{{ form.vars.full_name }}"
      data-mappingvalue="{{ mapping_value }}"
      data-mappingname="{{ mapping_name }}"
      data-remoteurl="{{ remote_url|raw }}"
      data-limit="{{ limit }}"
    >
        <div class="search search-with-icon">
          {# We want the attributes from the form type to be added to the input so we merge class form attribute to required ones #}
          {%- set attr = attr|merge({'class': (attr.class|default('') ~ ' form-control search typeahead ' ~ form.vars.id)|trim }) -%}
          {# We do not want the initial input name because the data is handled via a collection input with name="full_name[data][]" #}
          {%- set full_name = '' -%}
          <input type="text" id="{{ form.vars.id }}" placeholder="{{ placeholder }}" autocomplete="off" {{ block('widget_attributes') }}>
        </div>
        <small class="form-text text-muted text-right typeahead-hint">
          {% if help %}
            {{ help|raw }}
          {% endif %}
        </small>
        <ul id="{{ form.vars.id }}-data" class="typeahead-list nostyle col-sm-12 product-list">
            {% if collection is defined and collection|length > 0 %}
                {% for item in collection %}
                    <li class="media">
                      <div class="media-left">
                        <img class="media-object image" src="{{ item.image }}" />
                      </div>
                      <div class="media-body media-middle">
                        {{ template_collection|format(item.name)|raw }}
                      </div>
                      <input type="hidden" name="{{ form.vars.full_name }}[data][]" value="{{ item.id }}" />
                    </li>
                {% endfor %}
            {% endif %}
        </ul>

        <div class="invisible" id="tplcollection-{{ form.vars.id }}">
          {{ template_collection|raw }}
        </div>
    </div>
    <script type="text/javascript">
      $('#{{ form.vars.id }}').on('focusout', function resetSearchBar() {
        $('#{{ form.vars.id }}').typeahead('val', '');
      });
    </script>
{% endblock %}

{% block typeahead_product_pack_collection_widget %}
    <h2 class="title-products {{ collection is defined and collection|length > 0 ? '' : 'hide' }}">{{ 'List of products for this pack'|trans({}, 'Admin.Catalog.Feature') }}</h2>
    <ul id="{{ form.vars.id }}-data" class="typeahead-list pack nostyle row">
        {% if collection is defined and collection|length > 0 %}
            {% for item in collection %}
                <li data-product="{{ item.id }}-{{ item.id_product_attribute }}" class="col-xl-3 col-lg-6 mb-1">
                    <div class="pack-product">
                        <img class="cover" src="{{ item.image }}" /> {{ template_collection|format(item.name, item.ref, item.quantity)|raw }}
                        <input type="hidden" name="{{ form.vars.full_name }}[data][]" value="{{ item.quantity }}x{{ item.id }}x{{ item.id_product_attribute }}" />
                        <input type="hidden" name="{{ form.vars.full_name }}[data][]" value="{{ item.quantity }}x{{ item.id }}x{{ item.id_product_attribute }}" />
                    </div>
                </li>
            {% endfor %}
        {% endif %}
    </ul>

    <h2>{{ form.vars.label }}</h2>

    <div class="row mb-2">
        <div class="col-md-6">
            <input type="text" id="{{ form.vars.id }}" class="form-control typeahead search {{ form.vars.id }}" placeholder="{{ placeholder }}" autocomplete="off" />
        </div>
        <div class="col-md-3">
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">×</span>
                </div>
                <input type="number" id="{{ form.vars.id }}-curPackItemQty" class="form-control curPackItemQty" min="1" value="1">
            </div>
        </div>
        <div class="col-md-3">
            <div class="input-group">
                <button id="{{ form.vars.id }}-curPackItemAdd" class="btn btn-secondary btn-block">
                    <i class="material-icons">add</i>
                    {{ "Add"|trans({}, "Admin.Actions") }}
                </button>
            </div>
        </div>
        <div class="clearfix"></div>

        <script>
            $( document ).ready(function() {
                //remove collection item
                $(document).on( 'click', '#{{ form.vars.id }}-data .delete', function(e) {
                    e.preventDefault();
                    var _this = $(this);

                    modalConfirmation.create(translate_javascripts['Are you sure you want to delete this item?'], null, {
                        onContinue: function(){
                            _this.closest('li').remove();
                            if(_this.parent().parent().length == 0){
                                $('#js_{{ form.vars.id }} h4.title-products').addClass('hide');
                            }
                        }
                    }).show();
                });

                $('#{{ form.vars.id }}-curPackItemAdd').click(function(e){
                    e.preventDefault();
                    if($(this).data('currentItem')){
                        var number = $('#{{ form.vars.id }}-curPackItemQty').val();
                        var data = $(this).data('currentItem');
                        var value = number + 'x' + data.id + 'x' + (data.id_product_attribute ? data.id_product_attribute : 0);

                        var html = '<li data-product="' + data.id + '-' + (data.id_product_attribute ? data.id_product_attribute : 0) + '" class="col-xl-3 col-lg-6 mb-1">';
                        html += '<div class="pack-product">';
                        html += '<img class="cover" src="' + data.image +'" />';
                        html += sprintf('{% spaceless %}{{ template_collection|raw }}{% endspaceless %}', data.{{ mapping_name }}, data.ref, number);
                        html += '<input type="hidden" name="{{ form.vars.full_name }}[data][]" value="' + value + '" />';
                        html += '</div>';
                        html += '</li>';

                        $('#{{ form.vars.id }}-data').append(html);
                        $('#js_{{ form.vars.id }} h4.title-products').removeClass('hide');

                        $('#{{ form.vars.id }}').val('');
                    }

                    $(this).data('currentItem', null);
                    $('#{{ form.vars.id }}-curPackItemQty').val(1);
                });

                //define source
                this['{{ form.vars.id }}_source'] = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.whitespace,
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    identify: function(obj) {
                        return obj.{{ mapping_value }};
                    },
                    remote: {
                        url: '{{ remote_url|raw }}',
                        cache: false,
                        wildcard: '%QUERY',
                        transform: function(response){
                            var newResponse = [];

                            if(!response){
                                return newResponse;
                            }

                            //generate excludes IDs and filter results
                            var excludeIds = [];
                            $.each($('#{{ form.vars.id }}-data li'), function(key, val){
                                excludeIds.push($(val).attr('data-product'));
                            });

                            $.each(response, function(key, item){
                                if(excludeIds.indexOf(item.id + '-' + item.id_product_attribute) === -1){
                                    newResponse.push(item);
                                }
                            });

                            return newResponse;
                        }
                    }
                });

                //define typeahead
                $('#{{ form.vars.id }}').typeahead({
                    limit: 20,
                    minLength: 2,
                    highlight: true,
                    hint: false
                }, {
                    display: '{{ mapping_name }}',
                    source: this['{{ form.vars.id }}_source'],
                    limit: 30,
                    templates: {
                        suggestion: function(item){
                            return '<div>' +
                                   '<table><tr>' +
                                   '<td rowspan="2"><img src="'+ item.image +'" style="width:50px; margin-right: 7px;" /></td>' +
                                   '<td>' + item.name + '</td></tr>' +
                                   '<tr><td>REF: ' + item.ref + '</td></tr>' +
                                   '</table></div>'
                        }
                    }
                }).bind('typeahead:select', function(ev, suggestion) {
                    $('#{{ form.vars.id }}-curPackItemAdd').data('currentItem', suggestion);
                });
            });
        </script>
    </div>
{% endblock %}

{% block typeahead_customer_collection_widget %}
    {{ form_errors(form) }}
    <input type="text" id="{{ form.vars.id }}" class="form-control typeahead {{ form.vars.id }}" placeholder="{{ placeholder }}" autocomplete="off" />
    <ul id="{{ form.vars.id }}-data" class="typeahead-list product-list nostyle col-sm-12">
      {% if collection is defined and collection|length > 0 %}
        {% for item in collection %}
            <li class="media">
                <div class="media-body">
                  {{ template_collection|format(item.name)|raw }}
                </div>
                <input type="hidden" name="{{ form.vars.full_name }}[data][]" value="{{ item.id }}" />
            </li>
        {% endfor %}
      {% endif %}
    </ul>
    <script>
        $( document ).ready(function() {
            //remove collection item
            $(document).on( 'click', '#{{ form.vars.id }}-data .delete', function(e) {
                e.preventDefault();
                var _this = $(this);

                modalConfirmation.create(translate_javascripts['Are you sure you want to delete this item?'], null, {
                    onContinue: function(){
                        _this.closest('li').remove();
                        _this.parent().parent().hide();
                        _this.parent().remove();
                    }
                }).show();
            });

            //define source
            this['{{ form.vars.id }}_source'] = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.whitespace,
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                identify: function(obj) {
                    return obj.{{ mapping_value }};
                },
                remote: {
                    url: '{{ remote_url|raw }}',
                    cache: false,
                    wildcard: '%QUERY',
                    transform: function(response){
                        if(!response){
                            return [];
                        }
                        return response;
                    }
                }
            });

            //define typeahead
            $('#{{ form.vars.id }}').typeahead({
                limit: 200,
                minLength: 2,
                highlight: true,
                cache: false,
                hint: false,
            }, {
                display: '{{ mapping_name }}',
                source: this['{{ form.vars.id }}_source'],
                limit: 30,
                templates: {
                    suggestion: function(item){
                        return '<div>'+ item.{{ mapping_name }} +'</div>'
                    }
                }
            }).bind('typeahead:select', function(ev, suggestion) {

                //if collection length is up to limit, return
                if({{ limit }} != 0 && $('#{{ form.vars.id }}-data li').length >= {{ limit }}){
                    return;
                }

                var value = suggestion.{{ mapping_value }};
                if (suggestion.id_product_attribute) {
                    value = value+','+suggestion.id_product_attribute;
                }

                var html = '<li class="media">';
                html += sprintf('{% spaceless %}{{ template_collection|raw }}{% endspaceless %}', suggestion.{{ mapping_name }});
                html += '<input type="hidden" name="{{ form.vars.full_name }}[data][]" value="' + value + '" />';
                html += '</li>';
                $('#{{ form.vars.id }}-data').show();
                $('#{{ form.vars.id }}-data').append(html);

            }).bind('typeahead:close', function(ev) {
                $(ev.target).val('');
            });
        });
    </script>
{% endblock %}
