{% set _entity_config = easyadmin_entity(app.request.query.get('entity')) %}
{% trans_default_domain _entity_config.translation_domain %}
{% set _trans_parameters = { '%entity_name%': _entity_config.name|trans, '%entity_label%': _entity_config.label|trans } %}

{% extends _entity_config.templates.layout %}

{% set _request_parameters = app.request.query.all|merge(_request_parameters|default({}))|merge({
    action: app.request.get('action'),
    entity: _entity_config.name,
    menuIndex: app.request.get('menuIndex'),
    submenuIndex: app.request.get('submenuIndex'),
    sortField: app.request.get('sortField'),
    sortDirection: app.request.get('sortDirection'),
    page: app.request.get('page', 1),
    filters: app.request.get('filters', []),
    referer: null
}) %}

{% if 'search' == app.request.get('action') %}
    {% set _request_parameters = _request_parameters|merge({
        query: app.request.get('query')|default(''),
    }) %}
{% endif %}

{% set _request_parameters = _request_parameters|merge({ referer: path('easyadmin', _request_parameters)|url_encode }) %}
{% set _has_batch_actions = batch_form is defined and batch_form.vars.batch_actions|length > 0 %}
{% set _has_filters = _entity_config.list.filters|default(false) %}

{% block body_id 'easyadmin-list-' ~ _entity_config.name %}
{#{% block body_class 'list list-' ~ _entity_config.name|lower %}#}

{% block content_title %}
    {% apply spaceless %}
        {% if 'search' == app.request.get('action') %}
            {% set _default_title = 'search.page_title'|transchoice(paginator.nbResults, {}, 'EasyAdminBundle') %}
            {{ (_entity_config.search.title is defined ? _entity_config.search.title|transchoice(paginator.nbResults) : _default_title)|raw }}
        {% else %}
            {% set _default_title = 'list.page_title'|trans(_trans_parameters, 'EasyAdminBundle') %}
            {{ (_entity_config.list.title is defined ? _entity_config.list.title|trans(_trans_parameters) : _default_title)|raw }}
        {% endif %}
    {% endapply %}
{% endblock %}

{% block global_actions %}
    {#{% if easyadmin_action_is_enabled_for_list_view('new', _entity_config.name) %}
        {% set _action = easyadmin_get_action_for_list_view('new', _entity_config.name) %}
        {% block new_action %}
            <div class="button-action">
                <a class="{{ _action.css_class|default('') }}"
                   href="{{ path('easyadmin', _request_parameters|merge({ action: _action.name })) }}"
                   target="{{ _action.target }}">
                    {% if _action.icon %}<i class="fa fa-fw fa-{{ _action.icon }}"></i>{% endif %}
                    {{ _action.label is defined and not _action.label is empty ? _action.label|trans(_trans_parameters) }}
                </a>
            </div>
        {% endblock new_action %}
    {% endif %}#}
{% endblock global_actions %}

{% block batch_actions %}
    {% if _has_batch_actions %}
        <div class="batch-actions" style="display: none">
            {% form_theme batch_form with easyadmin_config('design.form_theme') only %}
            {{ form(batch_form) }}

            {{ include('@EasyAdmin/default/includes/_batch_action_modal.html.twig', {
                _translation_domain: _entity_config.translation_domain,
                _trans_parameters: _trans_parameters,
                _entity_config: _entity_config,
            }, with_context = false) }}
        </div>
    {% endif %}
{% endblock batch_actions %}

{% block content_header %}
    {{ parent() }}
    {{ block('batch_actions') }}
    {% if _has_filters %}
        {{ include('@EasyAdmin/default/includes/_filters_modal.html.twig') }}
    {% endif %}
{% endblock content_header %}

{% block main %}
    {% block main_append %}{% endblock %}

    {% set _fields_visible_by_user = fields|filter((metadata, field) => easyadmin_is_granted(metadata.permission)) %}
    {% set _number_of_hidden_results = 0 %}
    {% set _list_item_actions = easyadmin_get_actions_for_list_item(_entity_config.name) %}
    <div class="row">
        <div class="col-12">
            <div class="card card-outline card-primary">
                <div class="card-header">
                    {% block card_header %}

                        <h2 class="card-title text-lg ">
                            {% block paginator_nb_results %}
                                {#{{ "list.title"|trans({'%label%' : _entity_config['label']|lower }) }}#}
                                {% if paginator.nbResultsTotal !=  paginator.nbResults %}
                                    <span data-toggle="tooltip" title="{{ "list.nbResultsFiltered"|trans }}"
                                          class="badge badge-info">{{ paginator.nbResults }} <i
                                                class="fa fa-search"></i> </span>
                                    |
                                {% endif %}
                                <span data-toggle="tooltip" title="{{ "list.nbResults"|trans }}"
                                      class="badge badge-primary">{{ paginator.nbResultsTotal }} <i
                                            class="fa fa-bars"></i> </span>
                                {% if paginator.nbResultsOnline is defined %}<span data-toggle="tooltip"
                                                                                   title="{{ "list.nbResultsOnline"|trans }}"
                                                                                   class="badge badge-success">{{ paginator.nbResultsOnline }}
                                    <i class="fa fa-check"></i> </span>{% endif %}
                                {% if paginator.nbResultsOffline is defined %}<span data-toggle="tooltip"
                                                                                    title="{{ "list.nbResultsOffline"|trans }}"
                                                                                    class="badge badge-warning">{{ paginator.nbResultsOffline }}
                                    <i class="fa fa-pen"></i></span>{% endif %}
                                {% if is_granted('ROLE_SUPER_ADMIN') and paginator.nbResultsDeleted is defined %}<span
                                    data-toggle="tooltip" title="{{ "list.nbResultsDeleted"|trans }}"
                                    class="badge badge-danger">{{ paginator.nbResultsDeleted }} <i
                                        class="fa fa-trash"></i>
                                    </span>{% endif %}
                            {% endblock %}

                        </h2>

                        <div class="button-action">
                            {% if easyadmin_action_is_enabled_for_list_view('new', _entity_config.name) %}
                                {% set _action = easyadmin_get_action_for_list_view('new', _entity_config.name) %}
                                {% block new_action %}

                                    <a class="float-right {{ _action.css_class|default('') }}"
                                       href="{{ path('easyadmin', _request_parameters|merge({ action: _action.name })) }}"
                                       target="{{ _action.target }}">
                                        <i class="fa fa-fw fa-plus"></i>
                                        {{ _action.label is defined and not _action.label is empty ? _action.label|trans(_trans_parameters) }}
                                    </a>
                                {% endblock new_action %}
                            {% endif %}
                            {% if _entity_config['list']['btn_init_export_purchase_order'] is defined %}
                                <a class="float-right btn-sm btn-success action-confirm"
                                   href="{{ path('easyadmin', { entity: 'Supplier', action: 'initExportPurchaseOrder' }) }}">
                                    <i class="fa fa-undo"></i> Réinitialiser export bons de commande
                                </a>
                            {% endif %}

                            {% if _entity_config['list']['btn_download_purchase_order_archive'] is defined %}
                                <a class="float-right btn-sm btn-success"
                                   href="{{ path('easyadmin', { entity: 'Supplier', action: 'exportOrderPurchasesAsArchive' }) }}">
                                    <i class="fa fa-download"></i> Télécharger tous les bons de commande
                                </a>
                            {% endif %}

                            {% if _entity_config['list']['edit_position'] is defined %}
                                <a class="float-right btn-sm btn-success action-sort"
                                   href="{{ path('easyadmin', _request_parameters|merge({ action: 'sort' })) }}">
                                    <i class="fa fa-sort"></i> Modifier position
                                </a>
                            {% endif %}

                            {% if app.request.get('action') == 'listChildren' and app.request.get('entity') == 'ProductCategory' %}
                                <a class="float-right btn-sm btn-primary"
                                   href="{{ path('easyadmin', {action: 'list', entity: 'ProductCategory'}) }}">
                                    <i class="fa fa-chevron-left"></i> Retour à la catégorie parente
                                </a>
                            {% endif %}

                        </div>

                    {% endblock card_header %}

                </div>


                <div class="card-body p-0">
                    {% block table %}
                        <table class="table lc-table-list datagrid table-bordered table-hover table-striped ">
                            <thead>
                            {% block table_head %}
                                <tr>
                                    {% if _has_batch_actions %}
                                        <th width="1px"><span><input type="checkbox"
                                                                     class="form-batch-checkbox-all"></span>
                                        </th>
                                    {% endif %}

                                    {% for field, metadata in _fields_visible_by_user %}
                                        {% set isSortingField = (metadata.property == app.request.get('sortField')) or ('association' == metadata.type and app.request.get('sortField') starts with metadata.property ~ '.') %}
                                        {% set nextSortDirection = isSortingField ? (app.request.get('sortDirection') == 'DESC' ? 'ASC' : 'DESC') : 'DESC' %}
                                        {% set _column_label = metadata.label|trans(_trans_parameters) %}
                                        {% set _column_icon = isSortingField ? (nextSortDirection == 'DESC' ? 'fa-arrow-up' : 'fa-arrow-down') : 'fa-sort' %}

                                        <th class="{{ isSortingField ? 'sorted' }} {{ metadata.virtual ? 'virtual' }} {{ metadata.dataType|lower }} {{ metadata.css_class }}" {{ easyadmin_config('design.rtl') ? 'dir="rtl"' }}>
                                            {% if metadata.sortable %}
                                                <a href="{{ path('easyadmin', _request_parameters|merge({ page: 1, sortField: metadata.property, sortDirection: nextSortDirection })) }}">
                                                    {{ _column_label|raw }} <i class="fa fa-fw {{ _column_icon }}"></i>
                                                </a>
                                            {% else %}
                                                <span>{{ _column_label|raw }}</span>
                                            {% endif %}
                                        </th>
                                    {% endfor %}

                                    {% if _list_item_actions|length > 0 %}
                                        <th {% if _entity_config.list.collapse_actions %}width="10px"{% endif %} {{ easyadmin_config('design.rtl') ? 'dir="rtl"' }}>
                                            <span class="sr-only">{{ 'list.row_actions'|trans(_trans_parameters, 'EasyAdminBundle') }}</span>
                                        </th>
                                    {% endif %}
                                </tr>
                            {% endblock table_head %}
                            {% block table_filters %}
                                {% if filters_form is defined %}
                                    <tr class="table-filters-line">
                                        {% if _has_batch_actions %}
                                            <th></th>{% endif %}
                                        {% for field, metadata in _fields_visible_by_user %}
                                            <th>

                                                {% if filters_form[field] is defined %}
                                                    {% if metadata['dataType'] == 'datetime' or metadata['dataType'] == 'date' %}
                                                        <div class="input-group input-group-sm">
                                                            <input type="text"
                                                                   class="form-control input-sm float-right date-range">
                                                            <div class="hidden date-time-range-fields"
                                                                 style="display: none;">
                                                                {{ form_widget(filters_form[field]['dateStart'], {"attr" : {'class' : 'date-start', 'form': 'filters-form'}}) }}
                                                                {{ form_widget(filters_form[field]['dateEnd'], {"attr" : {'class' : 'date-end', 'form': 'filters-form'}}) }}
                                                            </div>
                                                        </div>
                                                    {% else %}
                                                        <div class="form-widget input-group-sm">
                                                            {% if metadata.dataType == 'integer' or  metadata.dataType== 'string' %}
                                                                {{ form_widget(filters_form[field], {'attr': {'autocomplete': 'off', 'data-lc-autocomplete-url' : path('easyadmin', {
                                                                    action: 'autocomplete',
                                                                    field: field,
                                                                    entity: _entity_config.name,
                                                                })|raw }}) }}
                                                            {% else %}
                                                                {{ form_widget(filters_form[field]) }}
                                                            {% endif %}
                                                        </div>
                                                    {% endif %}

                                                {% endif %}


                                            </th>
                                        {% endfor %}
                                        {% if _list_item_actions|length > 0 %}
                                            <th class="actions">
                                                <button type="submit" form="filters-form" class="btn btn-sm btn-info"
                                                        data-toggle="tooltip"
                                                        title="{{ "action.apply"|trans({}, 'lcshop') }}"
                                                        aria-label="{{ "action.apply"|trans({}, 'lcshop') }}">
                                                    <i class="fa fa-search"></i>
                                                </button>
                                                {% if filters_form.vars.submitted %}
                                                    <a href="{{ path('easyadmin', {action: app.request.get('action'), entity: _entity_config.name}) }}"
                                                       class="btn btn-sm btn-warning lc-reset-filters"
                                                       data-toggle="tooltip"
                                                       title="{{ "action.reset"|trans({}, 'lcshop') }}"
                                                       aria-label="{{ "action.reset"|trans({}, 'lcshop') }}">
                                                        <i class="fa fa-eraser"></i>
                                                    </a>
                                                {% endif %}


                                            </th>
                                        {% endif %}

                                    </tr>
                                {% endif %}

                            {% endblock table_filters %}
                            {% block table_search %}

                            {% endblock %}

                            </thead>

                            <tbody>
                            {% block table_body %}
                                {% for item in paginator.currentPageResults %}
                                    {% if not easyadmin_is_granted(_entity_config.list.item_permission, item) %}
                                        {% set _number_of_hidden_results = _number_of_hidden_results + 1 %}
                                    {% else %}
                                        {# the empty string concatenation is needed when the primary key is an object (e.g. an Uuid object) #}
                                        {% set _item_id = '' ~ attribute(item, _entity_config.primary_key_field_name) %}
                                        <tr data-id="{{ _item_id }}">
                                            {% if _has_batch_actions %}
                                                <td><input type="checkbox" class="form-batch-checkbox"
                                                           value="{{ _item_id }}"></td>
                                            {% endif %}

                                            {% for field, metadata in _fields_visible_by_user %}
                                                {% set isSortingField = metadata.property == app.request.get('sortField') %}
                                                {% set _column_label =  (metadata.label ?: field|humanize)|trans(_trans_parameters) %}


                                                <td class="{{ isSortingField ? 'sorted' }} {{ metadata.dataType|lower }} {{ metadata.css_class }}" {{ easyadmin_config('design.rtl') ? 'dir="rtl"' }}>
                                                    {% if (field == 'title' or field== 'id') and (metadata.dataType=="string" or metadata.dataType=="integer") %}
                                                        <a class="link-as-text"
                                                           href="{{ path('easyadmin', {'action':'edit', 'entity':_entity_config.name, 'id': item.id}) }}">
                                                            {{ easyadmin_render_field_for_list_view(_entity_config.name, item, metadata) }}
                                                        </a>
                                                    {% else %}
                                                        {{ easyadmin_render_field_for_list_view(_entity_config.name, item, metadata) }}
                                                    {% endif %}
                                                </td>
                                            {% endfor %}

                                            {% if _list_item_actions|length > 0 %}
                                                {% set _column_label =  'list.row_actions'|trans(_trans_parameters, 'EasyAdminBundle') %}
                                                <td class="actions">
                                                    {% block item_actions %}
                                                        {% set _actions_template = '@LcShop/backend/default/block/actions.html.twig' %}
                                                        {{ include(_actions_template, {
                                                            actions: _list_item_actions,
                                                            entity_config: _entity_config,
                                                            request_parameters: _request_parameters,
                                                            translation_domain: _entity_config.translation_domain,
                                                            trans_parameters: _trans_parameters,
                                                            item_id: _item_id,
                                                            item: item
                                                        }, with_context = false) }}
                                                    {% endblock item_actions %}
                                                </td>
                                            {% endif %}
                                        </tr>
                                    {% endif %}
                                {% else %}
                                    <tr>
                                        <td class="no-results" colspan="{{ _fields_visible_by_user|length + 1 }}">
                                            {{ 'search.no_results'|trans(_trans_parameters, 'EasyAdminBundle') }}
                                        </td>
                                    </tr>
                                {% endfor %}

                                {% if _number_of_hidden_results > 0 %}
                                    <tr class="datagrid-row-empty">
                                        <td class="text-center" colspan="{{ _fields_visible_by_user|length + 1 }}">
                                        <span class="datagrid-row-empty-message"><i
                                                    class="fa fa-lock mr-1"></i> {{ 'security.list.hidden_results'|trans({}, 'EasyAdminBundle') }}</span>
                                        </td>
                                    </tr>
                                {% endif %}
                            {% endblock table_body %}
                            </tbody>
                        </table>
                    {% endblock table %}

                    {% block filters_form %}
                        {% if filters_form is defined %}
                            {{ form_start(filters_form, {'attr' :{'id' : 'filters-form'}}) }}
                            {% form_theme filters_form '@LcShop/backend/form/custom_bootstrap_4.html.twig' %}

                            <input type="hidden" name="entity" value="{{ _entity_config.name }}">
                            <input type="hidden" name="menuIndex" value="{{ app.request.get('menuIndex') }}">
                            <input type="hidden" name="submenuIndex" value="{{ app.request.get('submenuIndex') }}">
                            <input type="hidden" name="sortField" value="{{ app.request.get('sortField', '') }}">
                            <input type="hidden" name="sortDirection"
                                   value="{{ app.request.get('sortDirection', 'DESC') }}">
                            <input type="hidden" name="action" value="{{ app.request.get('action') }}">
                            {{ form_end(filters_form) }}
                        {% endif %}
                    {% endblock filters_form %}


                    {% block delete_form %}
                        {% set referer = paginator.currentPage == paginator.nbPages and 1 != paginator.currentPage and 1 == paginator.currentPageResults|length
                            ? path('easyadmin', app.request.query|merge({ page: app.request.query.get('page') - 1 }))
                            : app.request.requestUri %}

                        {{ include('@EasyAdmin/default/includes/_delete_form.html.twig', {
                            view: 'list',
                            referer: referer,
                            delete_form: delete_form_template,
                            _translation_domain: _entity_config.translation_domain,
                            _trans_parameters: _trans_parameters,
                            _entity_config: _entity_config,
                        }, with_context = false) }}
                    {% endblock delete_form %}

                </div>

            </div>
        </div>
    </div>

{% endblock main %}

{% block content_footer %}
    <div class="container-fluid">
        {% block paginator %}
            {{ include(_entity_config.templates.paginator) }}
        {% endblock paginator %}
    </div>
{% endblock %}


{% block head_stylesheets %}
    {{ parent() }}
    <link rel="stylesheet"
          href="{{ asset('bundles/lcshop/css/backend/adminlte/plugins/daterange/daterangepicker.css') }}">
{% endblock %}

{% block plugin_javascript %}
    {{ parent() }}
    <script src="{{ asset('bundles/lcshop/js/backend/plugin/daterange/moment.min.js') }}"></script>
    <script src="{{ asset('bundles/lcshop/js/backend/plugin/daterange/daterangepicker.js') }}"></script>
    <script src="{{ asset('bundles/lcshop/js/backend/plugin/datatables/jquery.highlight.js') }}"></script>
    <script src="{{ asset('bundles/lcshop/js/backend/plugin/autocomplete/bootstrap-autocomplete.min.js') }}"></script>
    {#<script src="{{ asset('bundles/lcshop/js/backend/plugin/datatables/responsive.bootstrap4.min.js') }}"></script>#}
{% endblock %}

{% block script_javascript %}
    {{ parent() }}
    <script src="{{ asset('bundles/lcshop/js/backend/script/default/init-list.js') }}"></script>


    <script type="text/javascript">
        $(document).ready(function () {
            const toggles = document.querySelectorAll('.custom-switch input[type="checkbox"]');
            for (i = 0; i < toggles.length; i++) {
                toggles[i].addEventListener('change', function () {
                    const toggle = this;
                    const newValue = this.checked;
                    const oldValue = !newValue;
                    const propertyName = this.closest('.custom-switch').dataset.propertyname;
                    const toggleUrl = "{{ path('easyadmin', { action: 'edit', entity: _entity_config.name, view: 'list' })|raw }}"
                        + "&id=" + this.closest('tr').dataset.id
                        + "&property=" + propertyName
                        + "&newValue=" + newValue.toString();

                    let toggleRequest = $.ajax({type: "GET", url: toggleUrl, data: {}, dataType: 'json'});

                    toggleRequest.done(function (response) {
                        setFlashMessages(response.flashMessages);
                    });

                    toggleRequest.fail(function () {
                        // in case of error, restore the original value and disable the toggle
                        toggle.checked = oldValue;
                        toggle.disabled = true;
                        toggle.closest('.checkbox-switch').classList.add('disabled');
                    });
                });
            }
        });
    </script>
{% endblock %}
