{#
 # ---------------------------------------------------------------------
 #
 # 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/>.
 #
 # ---------------------------------------------------------------------
 #}

{% extends 'components/itilobject/timeline/form_timeline_item.html.twig' %}
{% import 'components/form/fields_macros.html.twig' as fields %}

{% set params = {'item': item}|merge(params|default({})) %}

{% set candedit = item.maySolve() %}
{% set can_read_kb = has_profile_right('knowbase', constant('READ')) or has_profile_right('knowbase', constant('KnowbaseItem::READFAQ')) %}
{% set can_update_kb = has_profile_right('knowbase', constant('UPDATE')) %}
{% set nokb = params['nokb'] is defined or (params['nokb'] ?? false) == true %}
{% set rand = random() %}
{% set is_default_pending = call('PendingReason::isDefaultPending') %}

{% set content_field_id = 'solution_content_' ~ rand %}

{% block timeline_card %}
   {% if form_mode == 'view' %}
      <div class="read-only-content">
         <div class="rich_text_container">
            {{ entry_i['content']|enhanced_html({
               'user_mentions': true,
               'images_gallery': true
            }) }}
         </div>

         <div class="timeline-badges">
            {% if entry_i['requesttypes_id'] %}
               <span class="badge bg-blue-lt" title="{{ __('Source of followup') }}">
                  <i class="ti ti-inbox me-1"></i>
                  {{ get_item_name('RequestType', entry_i['requesttypes_id']) }}
               </span>
            {% endif %}

            {% if entry_i['sourceitems_id'] %}
               <span class="badge bg-blue-lt">
                  <i class="ti ti-git-merge me-1"></i>
                  {% set merged_badge %}
                     <span class="badge">
                        {{ get_item_link('Ticket', entry_i['sourceitems_id']) }}
                     </span>
                  {% endset %}
                  {{ __('Merged from Ticket %1$s')|format(merged_badge)|raw }}
               </span>
            {% endif %}

            {% if entry_i['sourceof_items_id'] %}
               <span class="badge bg-blue-lt">
                  <i class="ti ti-git-merge me-1"></i>
                  {% set promoted_badge %}
                     <span class="badge">
                        {{ get_item_link('Ticket', entry_i['sourceof_items_id']) }}
                     </span>
                  {% endset %}
                  {{ __('Promoted to Ticket %1$s')|format(promoted_badge)|raw }}
               </span>
            {% endif %}

            {{ include('components/itilobject/timeline/pending_reasons_messages.html.twig') }}
         </div>
      </div>
   {% else %}
      <div class="itilfollowup">
         <form name="asset_form" style="width: 100%;" class="d-flex flex-column" method="post"
               action="{{ subitem.getFormURL() }}" enctype="multipart/form-data" data-track-changes="true" data-submit-once>
            <input type="hidden" name="itemtype" value="{{ item.getType() }}" />
            <input type="hidden" name="items_id" value="{{ item.fields['id'] }}" />
            {{ call_plugin_hook(constant('Glpi\\Plugin\\Hooks::PRE_ITEM_FORM'), {"item": subitem, 'options': params}) }}

            {% set add_reopen = (_get['_openfollowup'] ?? false) or item.needReopen() %}
            {% if add_reopen %}
               <input type="hidden" name="add_reopen" value="1" />
            {% endif %}

            <div class="row mx-n3 mx-xxl-auto">
               {% set col_md = get_current_interface() == 'central' ? 'col-xl-7 col-xxl-8' : 'col-xxl-12' %}
               <div class="col-12 {{ col_md }}">
                  {{ fields.textareaField(
                     'content',
                     subitem.fields['content'],
                     '',
                     {
                        'id': content_field_id,
                        'full_width': true,
                        'no_label': true,
                        'enable_richtext': true,
                        'enable_fileupload': true,
                        'mention_options': mention_options,
                        'entities_id': item.fields['entities_id'],
                        'rand': rand,
                        'required': add_reopen
                     }
                  ) }}
               </div>
               {% if get_current_interface() == 'central' %}
                  <div class="col-12 col-xl-5 col-xxl-4 order-first order-md-last pe-0 pe-xxl-auto">
                     <div class="row">

                        {{ include('components/itilobject/timeline/knowledge_item.html.twig') }}

                        {% set fup_template_lbl %}
                           <i class="{{ 'ITILFollowupTemplate'|itemtype_icon }} me-1"
                              title="{{ _n('Followup template', 'Followup templates', get_plural_number()) }}"></i>
                        {% endset %}
                        {{ fields.dropdownField(
                           'ITILFollowupTemplate',
                           'itilfollowuptemplates_id',
                           subitem.fields['itilfollowuptemplates_id'] ?? 0,
                           fup_template_lbl,
                           {
                              'full_width': true,
                              'icon_label': true,
                              'on_change': 'itilfollowuptemplate_update' ~ rand ~ '(this.value)',
                              'entity': item.fields['entities_id'],
                              'rand': rand,
                           }
                        ) }}

                        {% set fup_source_lbl %}
                           <i class="ti ti-inbox me-1" title="{{ __('Source of followup') }}"></i>
                        {% endset %}
                        {{ fields.dropdownField(
                           'RequestType',
                           'requesttypes_id',
                           subitem.fields['requesttypes_id'],
                           fup_source_lbl,
                           {
                              'full_width': true,
                              'icon_label': true,
                              'condition': {
                                 'is_active': 1,
                                 'is_itilfollowup': 1,
                              },
                              'rand': rand,
                           }
                        ) }}

                        {% set fup_private_lbl %}
                           <i class="ti ti-eye-off me-1" title="{{ __('Private') }}"></i>
                        {% endset %}
                        {{ fields.sliderField(
                           'is_private',
                           subitem.fields['is_private'],
                           fup_private_lbl,
                           {
                              'full_width': true,
                              'icon_label': true,
                              'rand': rand,
                              'additional_attributes': {
                                'onchange': 'toggleTimelinePrivate(this.checked, this)',
                              }
                           }
                        ) }}

                        {% if candedit and can_update_kb and not nokb %}
                           {% set fup_to_kb_lbl %}
                              <i class="ti ti-device-floppy me-1" title="{{ __('Save and add to the knowledge base') }}"
                                 data-bs-toggle="tooltip" data-bs-placement="top"></i>
                           {% endset %}
                           {{ fields.sliderField(
                              '_fup_to_kb',
                              0,
                              fup_to_kb_lbl,
                              {
                                 'full_width': true,
                                 'icon_label': true,
                                 'rand': rand,
                              }
                           ) }}
                        {% endif %}
                     </div>
                  </div>
               {% endif %}
            </div>

            {{ call_plugin_hook(constant('Glpi\\Plugin\\Hooks::POST_ITEM_FORM'), {"item": subitem, 'options': params}) }}
            {# Fixed min-height ensure no height increase when toggling the pending reason button, as select 2 dropdown are a bit higher than the default footer height #}
            <div class="d-flex card-footer mx-n3 mb-n3 flex-wrap" style="row-gap: 10px; min-height: 79px">
               {% set pending_reasons %}
                  {% set show_pending_reasons_actions = (item.fields['status'] == constant('CommonITILObject::WAITING') or is_default_pending) and not add_reopen %}
                  {% if get_current_interface() == 'central' and item.isAllowedStatus(item.fields['status'], constant('CommonITILObject::WAITING')) and call('PendingReason_Item::canDisplayPendingReasonForItem', [subitem]) %}
                     <span
                        class="input-group-text bg-yellow-lt py-0 pe-0 {{ show_pending_reasons_actions ? 'flex-fill' : '' }}"
                        id="pending-reasons-control-{{ rand }}"
                     >
                        <span class="d-inline-flex align-items-center" title="{{ __("Set the status to pending") }}"
                              data-bs-toggle="tooltip" data-bs-placement="top" role="button">
                           <i class="ti ti-player-pause-filled me-2"></i>
                           <label class="form-check form-switch mt-2">
                              <input type="hidden"   name="pending" value="0" />
                              <input type="checkbox" name="pending" value="1" class="form-check-input"
                                    id="enable-pending-reasons-{{ rand }}"
                                    role="button"
                                    {{ (item.fields['status'] == constant('CommonITILObject::WAITING') or is_default_pending) and not add_reopen ? 'checked' : '' }}
                                    data-bs-toggle="collapse" data-bs-target="#pending-reasons-setup-{{ rand }}" />
                           </label>
                        </span>

                        <div
                           class="collapse ps-2 py-1 flex-fill {{ show_pending_reasons_actions ? 'show' : '' }}"
                           aria-expanded="{{ show_pending_reasons_actions ? 'true' : 'false' }}"
                           id="pending-reasons-setup-{{ rand }}"
                        >
                           {{ include('components/itilobject/timeline/pending_reasons.html.twig') }}
                        </div>
                     </span>
                  {% endif %}
               {% endset %}

               {% if subitem.fields['id'] <= 0 %}
                  {# Do not enable flex wrapping when creating a new item as the pending form will be merged with the add button in an input group #}
                  <div class="input-group flex-nowrap">
                     <button class="btn btn-primary" type="submit" name="add">
                        <i class="ti ti-plus"></i>
                        <span>{{ _x('button', 'Add') }}</span>
                     </button>
                    {{ pending_reasons|raw }}

                  </div>
               {% else %}
                  <input type="hidden" name="id" value="{{ subitem.fields['id'] }}" />
                  <button class="btn btn-primary me-2" type="submit" name="update">
                     <i class="ti ti-device-floppy"></i>
                     <span>{{ _x('button', 'Save') }}</span>
                  </button>

                  {% if subitem.can(subitem.fields['id'], constant('PURGE')) %}
                     <button class="btn btn-outline-danger me-2" type="submit" name="purge"
                             onclick="return confirm('{{ __('Confirm the final deletion?')|e('js') }}');">
                        <i class="ti ti-trash"></i>
                        <span>{{ _x('button', 'Delete permanently') }}</span>
                     </button>
                  {% endif %}
                  {{ pending_reasons|raw }}
               {% endif %}
            </div>

            <input type="hidden" name="_glpi_csrf_token" value="{{ csrf_token() }}" />
         </form>
      </div>

      <script type="text/javascript">
         function itilfollowuptemplate_update{{ rand }}(value) {
            $.ajax({
               url: `${CFG_GLPI.root_doc}/ajax/itilfollowup.php`,
               type: 'POST',
               data: {
                  itilfollowuptemplates_id: value,
                  items_id: '{{ item.fields['id']|e('js') }}',
                  itemtype: '{{ item.getType()|e('js') }}'
               }
            }).done(function (data) {
               var requesttypes_id = isNaN(parseInt(data.requesttypes_id))
                  ? 0
                  : parseInt(data.requesttypes_id);

               // set textarea content
               setRichTextEditorContent("{{ content_field_id|e('js') }}", data.content);
               // set category
               //need to create new DOM option, because SELECT is remotely-sourced (AJAX)
               //see : https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2
               var newOption = new Option(data.requesttypes_name, requesttypes_id, true, true);
               $("#dropdown_requesttypes_id{{ rand }}").append(newOption).trigger('change');

               if (data.is_private !== undefined) {
                   // set is_private
                   $("#is_private_{{ rand }}")
                       .prop("checked", data.is_private == "0"
                         ? false
                         : true);
               }

               // set predefined pending reason
               $("#enable-pending-reasons-{{ rand }}")
                  .prop("checked", data.pendingreasons_id > 0);
               if (data.pendingreasons_id > 0) {
                  $("#pending-reasons-setup-{{ rand }}")
                     .collapse('show');

                  //need to create new DOM option, because SELECT is remotely-sourced (AJAX)
                  //see : https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2
                  var newOption = new Option(data.pendingreasons_name, data.pendingreasons_id, true, true);
                  $("#dropdown_pendingreasons_id{{ rand }}")
                     .append(newOption)
                     .trigger('change');
               } else if (
                  $("#dropdown_pendingreasons_id{{ rand }}").val() > 0
                     && $("#pending-reasons-setup-{{ rand }}").hasClass('show')
               ) {
                  $("#pending-reasons-setup-{{ rand }}")
                     .collapse('hide');

                  $("#dropdown_pendingreasons_id{{ rand }}")
                     .val(0)
                     .trigger('change');
               }
            });
         }
      </script>
   {% endif %}
{% endblock %}
