{#
 # ---------------------------------------------------------------------
 #
 # GLPI - Gestionnaire Libre de Parc Informatique
 #
 # http://glpi-project.org
 #
 # @copyright 2015-2026 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' %}

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

{% set candedit = item.isNewItem() or 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 formoptions  = params['formoptions'] ?? '' %}

{% block timeline_card %}
   {% if form_mode == 'view' %}
      <div class="read-only-content {{ entry_i['state'] is constant('Planning::DONE') ? 'done' : '' }}">
         <div class="rich_text_container text-content" data-bs-html="true" data-bs-custom-class="todo-list-tooltip"
              title="{{ entry_i['content']|html_to_text }}" data-bs-toggle="tooltip">
            {{ entry_i['content']|enhanced_html({
               'user_mentions': true,
               'images_gallery': true
            }) }}
         </div>

         <div class="timeline-badges">
            {% if entry_i['users_id_tech'] %}
               <span class="badge bg-orange-lt">
                  {% set is_current_tech = (entry_i['users_id_tech'] == session('glpiID')) %}
                  {% set anonym_tech = (get_current_interface() == 'helpdesk' and not is_current_tech and entity_config('anonymize_support_agents', session('glpiactive_entity')) != constant('Entity::ANONYMIZE_DISABLED')) %}
                  {{ include('components/user/link_with_tooltip.html.twig', {
                     'users_id': entry_i['users_id_tech'],
                     'enable_anonymization': anonym_tech
                  }, with_context = false) }}
               </span>
            {% endif %}

            {% if entry_i['groups_id_tech'] %}
               <span class="badge bg-orange-lt">
                  <i class="ti ti-users me-1"></i>
                  {{ get_item_link('Group', entry_i['groups_id_tech'], {'enable_anonymization': true}) }}
               </span>
            {% endif %}

            {% if entry_i['taskcategories_id'] %}
               <span class="badge bg-orange-lt">
                  {{ get_item_name('TaskCategory', entry_i['taskcategories_id']) }}
               </span>
            {% endif %}

            {% if entry_i['actiontime'] %}
               <span class="actiontime badge bg-orange-lt">
                  <i class="ti ti-stopwatch me-1"></i>
                  {{ entry_i['actiontime']|formatted_duration }}
               </span>
            {% endif %}

            {% if entry_i['begin'] %}
               <span class="planification badge bg-orange-lt">
                  <i class="ti ti-calendar me-1"></i>
                  {{ entry_i['begin']|formatted_datetime }}
                  &rArr;
                  {{ entry_i['end']|formatted_datetime }}
               </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>

      <script type="text/javascript">
         function change_task_state(tasks_id, target) {
            $.post(`${CFG_GLPI.root_doc}/ajax/timeline.php`,
               {'action':     'change_task_state',
                  'tasks_id':   tasks_id,
                  'parenttype': '{{ item.getType()|e('js') }}',
                  '{{ item.getForeignKeyField()|e('js') }}': {{ item.fields.id|json_encode|raw }}
               })
               .done(function(response) {
                  $(target).closest('.timeline-item').find('.state')
                     .removeClass('state_1 state_2')
                     .addClass('state_'+response.state)
                     .attr('title', response.label);

                  $(target).closest('.timeline-item').find('.read-only-content')
                     .toggleClass('done');

                  var todo_tasks   = $('.todo-list-state .state.state_1').length;
                  var done_tasks   = $('.todo-list-state .state.state_2').length;
                  var total_tasks  = todo_tasks + done_tasks;
                  var percent_done = Math.floor(100 * done_tasks / total_tasks);

                  $('.timeline-progress')
                     .css('width', percent_done + '%')
                     .attr('aria-valuenow', percent_done);
                  $('.task-progress-label').html(percent_done + '%');
               });
         }
      </script>
   {% else %}
      {% include('components/itilobject/timeline/form_task_main_form.html.twig') %}

      <script type="text/javascript">
         function itiltasktemplate_update{{ rand }}(value) {
            $.ajax({
               url: `${CFG_GLPI.root_doc}/ajax/task.php`,
               type: 'POST',
               data: {
                  tasktemplates_id: value,
                  items_id: '{{ item.fields['id']|e('js') }}',
                  itemtype: '{{ item.getType()|e('js') }}'
               }
            }).done(function (data) {
                // set textarea content ONLY if template defines content
                // If template has no content defined, preserve user's existing content
                if (data.content && data.content.trim() !== '') {
                    setRichTextEditorContent("content_{{ rand }}", data.content);
                }

                if (data.taskcategories_id !== undefined) {
                    // set category
                    const taskcategories_id = isNaN(parseInt(data.taskcategories_id))
                        ? 0
                        : parseInt(data.taskcategories_id);

                     //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.taskcategories_name, taskcategories_id, true, true);
                     $("#dropdown_taskcategories_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);
                }

                if (data.state !== undefined) {
                    // Set state
                    $("#dropdown_state{{ rand }}").trigger('setValue', data.state);
                }

                if (data.actiontime !== undefined) {
                    // Set duration
                    $("#dropdown_actiontime{{ rand }}").trigger('setValue', data.actiontime);
                }

                if (data.users_id_tech !== undefined) {
                    // Set user
                    $("#dropdown_users_id_tech{{ rand }}").trigger('setValue', data.users_id_tech);
                }

               if (data.groups_id_tech !== undefined) {
                   // Set group
                   $("#dropdown_groups_id_tech{{ rand }}").trigger('setValue', data.groups_id_tech);
               }

               // set predefined pending reason ONLY if template defines one
               // If template has no pending reason defined, preserve user's choices
               if (data.pendingreasons_id > 0) {
                  $("#enable-pending-reasons-{{ rand }}")
                     .prop("checked", true);
                  $("#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');
               }
               // If template has NO pending (data.pendingreasons_id is 0 or undefined),
               // DO NOTHING to preserve user's pending choices
            });
         }
      </script>
   {% endif %}
{% endblock %}
