{% extends '@SyliusShop/Form/theme.html.twig' %}

{% block collection_widget -%}
    {% import _self as self %}
    {% set attr = attr|merge({'class': attr.class|default}) %}

    {% apply spaceless %}
        <div data-form-type="collection" {{ block('widget_container_attributes') }}
            {% if prototype is defined and allow_add %}
                data-prototype='{{ self.collection_item(prototype, allow_delete, button_delete_label, prototype.vars.name)|e }}'
                data-prototype-name='{{ prototype.vars.name }}'
            {%- endif -%}
        >
            {% if prototypes|default is iterable %}
                {% for key, subPrototype in prototypes %}
                    <input type="hidden" data-form-prototype="{{ key }}"
                           value="{{ self.collection_item(subPrototype, allow_delete, button_delete_label, subPrototype.vars.name)|e }}"
                           data-subprototype-name="{{ subPrototype.vars.name }}"
                    />
                {% endfor %}
            {% endif %}

            <div data-form-collection="list">
                {% for child in form %}
                    {{ self.collection_item(child, allow_delete, button_delete_label, loop.index0) }}
                {% endfor %}
            </div>

            {% if prototype is defined and allow_add %}
                <div class="btn-wrapper">
                    <button type="button" class="btn btn-secondary btn-icon" data-form-collection="add">
                        <span class="btn-icon-text">{{ button_add_label|trans }}</span>
                        <span class="btn-icon-svg">{% include '@SyliusShop/Icons/plus.html.twig' %}</span>
                    </button>
                </div>
            {% endif %}
        </div>
    {% endapply %}
{%- endblock collection_widget %}

{% macro collection_item(form, allow_delete, button_delete_label, index) %}
    {% apply spaceless %}
        <div class="row mb-4" data-form-collection="item" data-form-collection-index="{{ index }}">
            <div class="col-md-8">
                {{ form_widget(form) }}
                {% if form.vars.errors is not empty %}
                    {{ form_errors(form) }}
                {% endif %}
            </div>
            {% if allow_delete %}
                <div class="col-md-4">
                    <button type="button" data-form-collection="delete" class="btn btn-secondary btn-icon">
                        <span class="btn-icon-text">{{ button_delete_label|trans }}</span>
                        <span class="btn-icon-svg">{% include '@SyliusShop/Icons/cross.html.twig' %}</span>
                    </button>
                </div>
            {% endif %}
        </div>
    {% endapply %}
{% endmacro %}
