{#
 # ---------------------------------------------------------------------
 #
 # GLPI - Gestionnaire Libre de Parc Informatique
 #
 # http://glpi-project.org
 #
 # @copyright 2015-2025 Teclib' and contributors.
 # @licence   https://www.gnu.org/licenses/gpl-3.0.html
 #
 # ---------------------------------------------------------------------
 #
 # LICENSE
 #
 # This file is part of GLPI.
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
 #
 # ---------------------------------------------------------------------
 #}

{% if showmassiveactions and count > 0 %}
    <div class="massiveactions-control card-header search-header ps-3 animate__animated animate__faster d-none">
        {% do call('Html::showMassiveActions', [massiveactionparams]) %}
    </div>
{% endif %}

<div class="card-header search-header px-1 px-xl-3">
    {% if not original_params.hide_controls ?? false %}
        <div class="search-controls d-flex justify-content-between align-items-center">

            {% set mainform = mainform ?? true %}
            {% set showaction = showaction ?? true %}
            {% if mainform and showaction %}
                <form
                    name="searchform{{ normalized_itemtype }}"
                    class="search-form-container needs-validation"
                    novalidate
                    method="get"
                    action="{{ href }}"
                    {% if not user_pref('show_search_form') %}
                        {# If the split search form is displayed, it has the
                        responsability of sending the search request instead of
                        this form which will only be used for sorting operations.
                        This mean we only mark this form as the "search form"
                        if the split search form is not enabled #}
                        data-glpi-search-form
                    {% endif %}
                >
            {% endif %}
            {% if not original_params.hide_criteria ?? false %}
                <div class="primary-controls">
                <div class="btn-group me-1 me-xl-2">
                    {% set is_filter_active = false %}
                    {% if active_search_name|length %}
                        {% set is_filter_active = true %}
                    {% endif %}
                    {% set animation_cls = "animate__animated animate__zoomIn" %}

                    {% set active_savedsearch_class = active_savedsearch ? "btn-active-search" : "" %}
                    <button type="button" class="btn btn-icon btn-sm p-1 {{ active_savedsearch_class }} btn-ghost-secondary show-saved-searches"
                        data-itemtype="{{ itemtype }}"
                        title="{{ __('Show saved searches') }}"  data-bs-toggle="tooltip" data-bs-placement="top">
                        <i class="ti ti-bookmarks"></i>
                    </button>
                    {% if not user_pref('show_search_form') %}
                        {% set active_filter_class = is_filter_active ? "btn-active-search" : "btn-ghost-secondary" %}
                        <button class="btn btn-sm py-1 show-search-filters {{ active_filter_class }} btn-ghost-secondary dropdown-toggle" type="button"
                                data-bs-toggle="dropdown" data-bs-auto-close="outside">
                            <i class="ti ti-list-search"></i>
                            {% if active_search_name|length %}
                                <span class="d-none d-xl-inline-block text-truncate" style="max-width: 250px" title="{{ active_search_name }}" data-bs-toggle="tooltip" data-bs-placement="top">
                                    {{ active_search_name }}
                                </span>
                            {% else %}
                                <span class="d-none d-xl-inline-block">{{ __('Search') }}</span>
                            {% endif %}
                        </button>
                        <div class="dropdown-menu dropdown-menu-card {{ animation_cls }}" style="width: max-content; max-width: 100vw;">
                            {% do call('Glpi\\Search\\Input\\QueryBuilder::showGenericSearch', [itemtype, original_params]) %}
                        </div>
                    {% endif %}
                </div>

                {% if data['search']['as_map'] != 1 %}
                    {% set active_sort_class = active_sort ? "btn-active-sort" : "" %}
                    <button class="btn btn-sm py-1 show-search-sorts {{ active_sort_class }} btn-ghost-secondary dropdown-toggle me-1 me-xl-2" type="button"
                                data-bs-toggle="dropdown" data-bs-auto-close="outside">
                        <i class="ti ti-arrows-sort"></i>
                        {% set sort_names = (active_sort_name|length ? active_sort_name : __("Sort")) %}
                        <span class="d-none d-xl-inline-block text-truncate" style="max-width: 250px" title="{{ sort_names }}" data-bs-toggle="tooltip" data-bs-placement="top">
                            {{ sort_names }}
                        </span>
                    </button>
                    <div class="dropdown-menu dropdown-menu-card {{ animation_cls }}" style="width: max-content; max-width: 100vw;">
                        {% do call('Glpi\\Search\\Input\\QueryBuilder::showGenericSort', [itemtype, original_params]) %}
                    </div>
                {% endif %}
            </div>
            {% endif %}

            {% if mainform and showaction %}
                <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}">
                </form>
            {% endif %}

            <div class="middle-controls d-flex">
                {% do call([itemtype, 'showSearchStatusArea']) %}

                {% if user_pref('search_pagination_on_top') %}
                    {% if data['display_type'] != constant('Search::GLOBAL_SEARCH') and data['search']['as_map'] == 0 %}
                        <div class="search-footer flex-grow-1 mx-1 d-none d-xxl-block mb-n2" style="max-width: 650px;">
                            {% include('components/pager.html.twig') with {
                                'short_display': true
                            } %}
                        </div>
                    {% endif %}
                {% endif %}
            </div>

            {% set submit_search_form = "this.closest('[data-glpi-search-container]').querySelector('[data-glpi-search-form]').submit()" %}
            <div class="secondary-controls">
                {% if may_be_located %}
                    <div class="btn-group me-1 me-xl-2 shadow-none" role="group">
                        {% set table_class = (data['search']['as_map'] == 0 ? "btn-ghost-info" : "") %}
                        <input
                            type="radio"
                            class="btn-check"
                            name="as_map"
                            value="1"
                            autocomplete="off"
                            id="show_as_table"
                            onclick="toogle('as_map','','',''); {{ submit_search_form }};"
                            {{ data['search']['as_map'] == 0 ? 'checked' : '' }}
                        >
                            <label class="btn btn-icon btn-sm btn-pill px-2 py-1 {{ table_class }}" title="{{ __('Show as table') }}"
                                for="show_as_table"
                                data-bs-toggle="tooltip" data-bs-placement="top">
                                <i class="ti ti-table"></i>
                            </label >

                        {% set located_class = (data['search']['as_map'] == 1 ? "btn-ghost-info" : "") %}
                        <input
                            type="radio"
                            class="btn-check"
                            name="as_map"
                            value="1"
                            autocomplete="off"
                            id="show_as_map"
                            onclick="toogle('as_map','','',''); {{ submit_search_form }};"
                            {{ data['search']['as_map'] == 1 ? 'checked' : '' }}
                        >
                        <label class="btn btn-icon btn-sm btn-pill px-2 py-1 {{ located_class }}" title="{{ __('Show as map') }}"
                            for="show_as_map"
                            data-bs-toggle="tooltip" data-bs-placement="top">
                            <i class="ti ti-map-2"></i>
                        </label >
                    </div>
                {% endif %}

                {% if may_be_browsed %}
                    <button
                        class="btn btn-icon btn-sm {{ data['search']['browse'] == 1 ? "btn-secondary" : "btn-ghost-secondary" }} me-1 me-xl-2 px-1"
                        type="button"
                        title="{{ __('Toggle browse') }}"
                        data-bs-toggle="tooltip"
                        data-bs-placement="top"
                        onclick="toogle('browse','','',''); {{ submit_search_form }};"
                    >
                        <i class="ti {{ data['search']['browse'] == 1 ? "ti-checkbox" : "ti-square" }}"></i>
                        <span class="d-flex align-bottom">
                            <i class="ti ti-subtask"></i>
                        </span>
                    </button>
                {% endif %}

                {% if may_be_deleted %}
                    <button
                        class="btn btn-icon btn-sm {{ data['search']['is_deleted'] == 1 ? "btn-danger" : "btn-ghost-danger" }} me-1 me-xl-2 px-1"
                        type="button"
                        title="{{ __('Show the trashbin') }}"
                        data-bs-toggle="tooltip"
                        data-bs-placement="top"
                        onclick="toogle('is_deleted','','',''); {{ submit_search_form }};"
                    >
                        <i class="ti {{ data['search']['is_deleted'] == 1 ? "ti-checkbox" : "ti-square" }}"></i>
                        <span class="d-flex align-bottom">
                            <i class="ti ti-trash"></i>
                        </span>
                    </button>
                {% endif %}

                {% if may_be_unpublished %}
                    {% set show_unpublished = data['search']['unpublished'] == 1 %}
                    <button
                        class="btn btn-icon btn-sm {{ show_unpublished ? "btn-warning" : "btn-ghost-warning" }} me-1 me-xl-2 px-1"
                        type="button"
                        title="{{ __('Show unpublished') }}"
                        data-bs-toggle="tooltip"
                        data-bs-placement="top"
                        onclick="toogle('unpublished','','',''); {{ submit_search_form }};"
                    >
                        <i
                            class="ti {{ show_unpublished ? "ti-checkbox" : "ti-square" }}"
                            data-testid="unpublished-{{ show_unpublished ? "on" : "off" }}"
                        ></i>
                        <span class="d-flex align-bottom">
                            <i class="ti ti-eye-off"></i>
                        </span>
                    </button>
                {% endif %}


                {% if can_config %}
                    <button class="show_displaypreference_modal  btn btn-sm btn-ghost-secondary"
                        type="button"
                        title="{{ __('Select default items to show') }}"
                        data-bs-toggle="tooltip" data-bs-placement="top">
                        <i class="ti ti-table-row"></i>
                    </button>
                    <template id="displaypreference_modal_template{{ rand }}">
                        {{ include('components/search/displaypreference_modal.html.twig', {
                        rand: rand,
                        itemtype: itemtype,
                        }) }}
                    </template>
                {% endif %}

                {% if count > 0 %}
                    <button class="dropdown-toggle btn btn-sm btn-ghost-secondary" type="button" name="export" id="dropdown-export-{{ rand }}"
                            data-bs-toggle="dropdown" aria-expanded="false" data-bs-popper-config='{"strategy":"fixed"}'>
                        <span title="{{ __("Export") }}" data-bs-toggle="tooltip" data-bs-placement="top">
                            <i id="export_dropdown_icon" class="ti ti-download"></i>
                        </span>
                    </button>
                    {% set exporthref = path('/front/report.dynamic.php') ~ "?" ~ {
                        'item_type': itemtype,
                        'sort': sort,
                        'order': order,
                        'start': start,
                    }|url_encode ~ '&' ~ posthref %}
                    <div class="dropdown-menu" style="z-index: 10001" aria-labelledby="dropdown-export-{{ rand }}" role="menu">
                        <div role="separator"><h6 class="dropdown-header">{{ __("Current page") }}</h6></div>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=' ~ constant('Search::PDF_OUTPUT_LANDSCAPE') }}" role="menuitem">
                            <i class="ti ti-file-type-pdf"></i>
                            {{- __('Landscape PDF') -}}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=' ~ constant('Search::PDF_OUTPUT_PORTRAIT') }}" role="menuitem">
                            <i class="ti ti-file-type-pdf"></i>
                            {{ __('Portrait PDF') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=' ~ constant('Search::CSV_OUTPUT') }}" role="menuitem">
                            <i class="ti ti-file-type-csv"></i>
                            {{ __('CSV') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=' ~ constant('Search::ODS_OUTPUT') }}" role="menuitem">
                            <i class="ti ti-file-spreadsheet"></i>
                            {{ __('Spreadsheet (%s)')|format('ODS') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=' ~ constant('Search::XLSX_OUTPUT') }}" role="menuitem">
                            <i class="ti ti-file-spreadsheet"></i>
                            {{ __('Spreadsheet (%s)')|format('XLSX') }}
                        </a>
                        <hr class="dropdown-divider">
                        <div role="separator"><h6 class="dropdown-header">{{ __("All pages") }}</h6></div>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=-' ~ constant('Search::PDF_OUTPUT_LANDSCAPE') }}" role="menuitem">
                            <i class="ti ti-file-type-pdf"></i>
                            {{ __('Landscape PDF') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=-' ~ constant('Search::PDF_OUTPUT_PORTRAIT') }}" role="menuitem">
                            <i class="ti ti-file-type-pdf"></i>
                            {{ __('Portrait PDF') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=-' ~ constant('Search::CSV_OUTPUT') }}" role="menuitem">
                            <i class="ti ti-file-type-csv"></i>
                            {{ __('CSV') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=-' ~ constant('Search::ODS_OUTPUT') }}" role="menuitem">
                            <i class="ti ti-file-spreadsheet"></i>
                            {{ __('Spreadsheet (%s)')|format('ODS') }}
                        </a>
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=-' ~ constant('Search::XLSX_OUTPUT') }}" role="menuitem">
                            <i class="ti ti-file-spreadsheet"></i>
                            {{ __('Spreadsheet (%s)')|format('XLSX') }}
                        </a>
                        {% if itemtype != 'Stat' %}
                        <hr class="dropdown-divider">
                        <a class="dropdown-item" href="{{ exporthref ~ '&display_type=-' ~ constant('Search::NAMES_OUTPUT') }}"
                           id="copy_names_to_clipboard" role="menuitem">
                            <i class="ti ti-copy"></i>
                            {{ __('Copy names to clipboard') }}
                        </a>
                        {% endif %}
                    </div>
                    <script>
                        // Ugly trick to fix z-index context issue by placing our dropdown at the end of the body
                        $("#dropdown-export-{{ rand }}").on("show.bs.dropdown", function() {
                            $(document.body).append($("ul[aria-labelledby=dropdown-export-{{ rand }}]").detach());
                        });
                    </script>
                {% endif %}
            </div>
        </div>
    {% endif %}
</div>

<script type="text/javascript">
$(document).ready(function() {
   $('.show_displaypreference_modal').click(function(e) {
      e.preventDefault();

      // remove old modal
      $('#displayprefence_modal{{ rand }}').remove();

      // create new one
      $('body').append($('#displaypreference_modal_template{{ rand }}').html());
      const modal_el = $('#displaypreference_modal{{ rand }}');
      modal_el.modal('show');
   });

   $("body").on('hide.bs.modal', '#displaypreference_modal{{ rand }}', function() {
      // Try finding a fluid search instance
      const search_display = $('.ajax-container.search-display-data');
      try {
          if (search_display.length === 1 && search_display.data('js_class') !== undefined) {
              // Trigger a reload of just the results
              search_display.data('js_class').view.refreshResults();
          } else {
              // There is no (or multiple) search results, reload the page
              window.location.reload();
          }
      } catch (err) {
          window.location.reload();
      }
   });

   $('.default-filter').change(function(event) {
      const search_params = new URLSearchParams(window.location.search);
      if (!$(this).is(":checked")) {
          search_params.set('nodefault', '1');
      } else {
          search_params.delete('nodefault');
      }
      window.location.replace('?' + search_params.toString());
   });

   // Callbacks for copy success/failure
   function copy_success() {
      glpi_toast_info(__('Results copied to clipboard'));
      $('#export_dropdown_icon').removeClass('spinner-border spinner-border-sm');
      $('#export_dropdown_icon').addClass('ti-file-download');
   }
   function copy_error() {
      glpi_toast_error(__('Unexpected error'));
      $('#export_dropdown_icon').removeClass('spinner-border spinner-border-sm');
      $('#export_dropdown_icon').addClass('ti-file-download');
   }

   $('#copy_names_to_clipboard').click(function(e) {
      // Get target link
      const link = $(e.currentTarget).prop('href');

      // Show loading indicator
      $('#export_dropdown_icon').removeClass('ti-file-download');
      $('#export_dropdown_icon').addClass('spinner-border spinner-border-sm');

      // Prevent link from working
      e.preventDefault();

      // Get data using ajax
      $.get(link, function (data) {
         navigator.clipboard.writeText(data).then(copy_success, copy_error);
      }).fail(copy_error);
   });

    // show massive actions control when at least one checkbox is checked
    $('.massive_action_checkbox').change(function() {
        const nb_ma_checked = $('.massive_action_checkbox:checked').length;

        if (nb_ma_checked === 0) {
            $('.massiveactions-control')
                .removeClass('animate__slideInLeft')
                .addClass('animate__slideOutLeft')
        } else {
            $('.massiveactions-control')
                .removeClass('d-none')
                .removeClass('animate__slideOutLeft')
                .addClass('animate__slideInLeft');
        }
    });
    // also call it on page load
    $('.massive_action_checkbox').trigger('change');
});
</script>
