{% include 'extension/alsendo/admin/view/template/partials/info_modal.twig' %}
<form id="form-order" method="post" enctype="application/x-www-form-urlencoded" data-load="{{ action }}">
    <div class="table-responsive" id="alsendo-bulk-package-templates">
        <table class="table table-bordered table-hover">
            <thead>
            <tr>
                <td class="text-start">{{ text_order_id }}</td>
                <td class="text-start">{{ text_sender_address }}</td>
                <td class="text-start">{{ text_shipping_address_details }}</td>
                <td class="text-start">{{ text_package_template_name }}</td>
                <td class="text-start">{{ text_shipping_method_and_courier_service_info }}</td>
                <td class="text-start td-order-shipment-status" style="max-width: 300px;">{{ text_bulk_operation_status }}</td>
                <td class="text-center">{{ column_actions_text }}</td>
            </tr>
            </thead>
            <tbody>
            {% if orders %}
                {% for order in orders %}
                    <tr class="bulk-order-table-row {% if order.has_shipment %}bulk-table-row-success{% endif %}" data-order-id="{{ order.order_id }}">
                        <td class="text-start">
                            <a href="{{ order.view }}" target="_blank" class="mb-0">{{ order.order_id }}</a>
                        </td>
                        <td class="text-start">
                            {% if order.full_order.orderDetails.sender %}
                                <p class="mb-0">{{ order.full_order.orderDetails.sender.getSummaryText() }}</p>
                                <div class="mt-1">
                                    <button type="button" class="btn btn-link btn-sm p-0 text-decoration-none alsendo-sender-change-toggle">{{ text_change }}</button>
                                    <div class="alsendo-sender-dropdown mt-2 d-flex align-items-center flex-wrap gap-2 d-none">
                                        <select class="form-select form-select-sm alsendo-sender-template-select" style="max-width:20em;">
                                            {% for t in sender_address_templates %}
                                                <option value="{{ t.id }}" {% if order.full_order.orderDetails.sender.senderTemplateId == t.id %}selected{% endif %}>{{ t.company_name }}</option>
                                            {% endfor %}
                                        </select>
                                        <button type="button" class="btn btn-primary btn-sm alsendo-sender-save">{{ text_save }}</button>
                                    </div>
                                </div>
                            {% endif %}
                        </td>
                        <td class="text-start">
                            <p class="mb-0">{{ order.full_order.openCartOrder.firstname }} {{ order.full_order.openCartOrder.lastname }}</p>
                            <p class="mb-0">
                                {{ order.full_order.openCartOrder.shipping_address_1 }}{{ order.full_order.openCartOrder.shipping_address_2 ? '/' ~ order.full_order.openCartOrder.shipping_address_2 : '' }}
                            </p>
                            <p class="mb-0">{{ order.full_order.openCartOrder.shipping_postcode }} {{ order.full_order.openCartOrder.shipping_city }}</p>
                            <p class="mb-0">{{ order.full_order.openCartOrder.shipping_country }}</p>
                            {% if order.full_order.orderPickupPoint %}
                                <p class="mb-0" style="font-size: 0.8em;">{{ text_pickup_point_code_text }}: <span style="font-weight:bold;">{{ order.full_order.orderPickupPoint.getCode }}</span></p>
                            {% endif %}
                        </td>
                        <td class="text-start">
                            {% if order.full_order.getLastNonCancelledShipment %}
                                {% if order.full_order.getLastNonCancelledShipment is not empty %}
                                    {% for singlePackage in order.full_order.getLastNonCancelledShipment.packages %}
                                        <p style="font-weight: bold;" class="mb-0">{{ singlePackage.templateName ?: text_no_template }}</p>
                                        <p class="m-0 p-0">{{ singlePackage.summaryString }}</p>
                                    {% endfor %}
                                {% endif %}
                            {% else %}
                                {% if order.full_order.orderDetails.packageDetails.packages is defined and order.full_order.orderDetails.packageDetails.packages is not empty %}
                                    {% for package in order.full_order.orderDetails.packageDetails.packages %}
                                        <div class="alsendo-package-row mb-2" data-order-id="{{ order.order_id }}" data-package-index="{{ loop.index0 }}">
                                            <p style="font-weight: bold;" class="mb-0">{{ package.templateName|default(text_no_template) }}</p>
                                            {% if package.packageWidth is defined and package.packageWidth != '' %}
                                                <p class="m-0 p-0">{{ package.packageWidth }}x{{ package.packageLength }}x{{ package.packageHeight }}cm, {{ package.packageWeight }}kg</p>
                                            {% endif %}
                                            <div class="mt-1">
                                                <button type="button" class="btn btn-link btn-sm p-0 text-decoration-none alsendo-package-change-toggle">{{ text_change }}</button>
                                                <div class="alsendo-package-dropdown mt-2 d-flex align-items-center flex-wrap gap-2 d-none">
                                                    <select class="form-select form-select-sm alsendo-package-template-select" style="max-width:20em;">
                                                        {% for t in shipping_settings_templates %}
                                                            <option value="{{ t.id }}" {% if package.templateId is defined and package.templateId == t.id %}selected{% endif %}>{{ t.name }}</option>
                                                        {% endfor %}
                                                    </select>
                                                    <button type="button" class="btn btn-primary btn-sm alsendo-package-save">{{ text_save }}</button>
                                                </div>
                                            </div>
                                        </div>
                                    {% endfor %}
                                {% else %}
                                    <p style="font-weight: bold;" class="mb-0">{{ order.full_order.orderDetails.packageDetails.templateName ?: text_no_template }}</p>
                                {% endif %}
                            {% endif %}
                        </td>
                        <td class="text-start">
                            <p class="mb-0">
                                {{ text_shipment_method_name }}: <span style="font-weight: bold;">{{ order.full_order.orderDetails.shipment.shippingMethodName }}</span>
                            </p>
                            <p class="mb-0">
                                {{ text_courier_service_name }}: <span style="font-weight: bold;">{{ order.full_order.orderDetails.shipment.shippingServiceName ?: any_service_text }}</span>
                            </p>
                        </td>
                        <td class="text-center">
                            <p class="order-bulk-send-operation-status {% if order.has_shipment %}operation-success{% endif %}" data-order-id="{{ order.order_id }}">{% if order.has_shipment %}{{ order.shipment_cell_html }}{% endif %}</p>
                            <p class="order-bulk-cancel-operation-status" data-order-id="{{ order.order_id }}"></p>
                        </td>
                        <td class="text-center" style="white-space: nowrap;">
                            <button {% if not order.has_shipment %}disabled{% endif%} data-order-id="{{ order.order_id }}" data-bs-toggle="tooltip" title="{{ text_cancel }}"  class="btn btn-danger d-inline-block cancel-submitted-order-button">
                                <i class="fa-solid fa-times-circle"></i>
                            </button>
                            <button disabled data-order-id="{{ order.order_id }}" data-bs-toggle="tooltip" title="{{ text_submit_order_shipment_again }}" class="btn btn-primary d-inline-block try-order-shipment-resubmit-button">
                                <i class="fa-solid fa-rotate-right"></i>
                            </button>
                            <a href="{{ order.view_full_form }}" target="_blank" data-bs-toggle="tooltip" title="{{ text_go_to_full_order_form }}" class="btn btn-primary d-inline-block">
                                <i class="fa-solid fa-file-lines"></i>
                            </a>
                            <button type="button" {% if not order.has_shipment %}disabled{% endif%} data-external-shipment-id="{{ order.external_shipment_id }}" data-bs-toggle="tooltip" title="{{ text_download_waybill }}" class="btn btn-primary d-inline-block download-waybill-single">
                                <i class="fa-solid fa-arrow-down"></i>
                            </button>
                        </td>
                    </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td class="text-center" colspan="7">{{ text_no_results }}</td>
                </tr>
            {% endif %}
            </tbody>
        </table>
    </div>
</form>
<script>
$(document).ready(function() {
  var postReloadMessage = sessionStorage.getItem('alsendo_template_message');
  if (postReloadMessage) {
    sessionStorage.removeItem('alsendo_template_message');
    showInfoModal(postReloadMessage);
  }
  var textChange = '{{ text_change|e('js') }}';
  var textCancel = '{{ text_cancel|e('js') }}';
  var textOperationNotSuccessful = '{{ text_operation_not_successful|e('js') }}';
  var urlSender = 'index.php?route=extension/alsendo/module/alsendo.applyOrderSenderTemplate&user_token={{ user_token|e('js') }}';
  var urlPackage = 'index.php?route=extension/alsendo/module/alsendo.applyOrderPackageTemplate&user_token={{ user_token|e('js') }}';
  var container = document.getElementById('alsendo-bulk-package-templates');
  if (container) {
    container.addEventListener('click', function(e) {
      var senderToggleBtn = e.target.closest('.alsendo-sender-change-toggle');
      if (senderToggleBtn) {
        e.preventDefault();
        var senderCell = senderToggleBtn.closest('td');
        var senderDropdown = senderCell ? senderCell.querySelector('.alsendo-sender-dropdown') : null;
        if (senderDropdown) {
          if (senderDropdown.classList.contains('d-none')) {
            senderDropdown.classList.remove('d-none');
            senderToggleBtn.textContent = textCancel;
          } else {
            senderDropdown.classList.add('d-none');
            senderToggleBtn.textContent = textChange;
          }
        }
        return;
      }
      var senderSaveBtn = e.target.closest('.alsendo-sender-save');
      if (senderSaveBtn) {
        e.preventDefault();
        var tr = senderSaveBtn.closest('tr.bulk-order-table-row');
        if (!tr) return;
        var senderTd = senderSaveBtn.closest('td');
        var senderDropdown = senderTd ? senderTd.querySelector('.alsendo-sender-dropdown') : null;
        var senderToggleBtnCurrent = senderTd ? senderTd.querySelector('.alsendo-sender-change-toggle') : null;
        var senderSelectEl = senderTd ? senderTd.querySelector('.alsendo-sender-template-select') : null;
        var senderTemplateId = senderSelectEl ? (parseInt(senderSelectEl.value, 10) || 0) : 0;
        var orderIdForSender = tr.getAttribute('data-order-id');
        var senderFormData = new FormData();
        senderFormData.append('order_id', orderIdForSender);
        senderFormData.append('template_id', senderTemplateId);
        fetch(urlSender, { method: 'POST', body: senderFormData }).then(function(r) { return r.json(); }).then(function(json) {
          if (senderDropdown) senderDropdown.classList.add('d-none');
          if (senderToggleBtnCurrent) senderToggleBtnCurrent.textContent = textChange;
          var msg = json.success ? (json.message || '') : (textOperationNotSuccessful + ': ' + (json.error || ''));
          sessionStorage.setItem('alsendo_template_message', msg);
          location.reload();
        }).catch(function() {
          if (senderDropdown) senderDropdown.classList.add('d-none');
          if (senderToggleBtnCurrent) senderToggleBtnCurrent.textContent = textChange;
          sessionStorage.setItem('alsendo_template_message', textOperationNotSuccessful);
          location.reload();
        });
        return;
      }
      var toggleBtn = e.target.closest('.alsendo-package-change-toggle');
      if (toggleBtn) {
        e.preventDefault();
        var row = toggleBtn.closest('.alsendo-package-row');
        var dropdown = row ? row.querySelector('.alsendo-package-dropdown') : null;
        if (dropdown) {
          if (dropdown.classList.contains('d-none')) {
            dropdown.classList.remove('d-none');
            toggleBtn.textContent = textCancel;
          } else {
            dropdown.classList.add('d-none');
            toggleBtn.textContent = textChange;
          }
        }
        return;
      }
      var saveBtn = e.target.closest('.alsendo-package-save');
      if (saveBtn) {
        e.preventDefault();
        var row = saveBtn.closest('.alsendo-package-row');
        if (!row) return;
        var dropdown = row.querySelector('.alsendo-package-dropdown');
        var toggleBtn = row.querySelector('.alsendo-package-change-toggle');
        var selectEl = row.querySelector('.alsendo-package-template-select');
        var templateId = selectEl ? (parseInt(selectEl.value, 10) || 0) : 0;
        var packageIndex = row.getAttribute('data-package-index');
        var orderIdVal = row.getAttribute('data-order-id');
        var formData = new FormData();
        formData.append('order_id', orderIdVal);
        formData.append('template_id', templateId);
        formData.append('package_index', packageIndex !== null && packageIndex !== '' ? packageIndex : '0');
        fetch(urlPackage, { method: 'POST', body: formData }).then(function(r) { return r.json(); }).then(function(json) {
          if (dropdown) dropdown.classList.add('d-none');
          if (toggleBtn) toggleBtn.textContent = textChange;
          var msg = json.success ? (json.message || '') : (textOperationNotSuccessful + ': ' + (json.error || ''));
          sessionStorage.setItem('alsendo_template_message', msg);
          location.reload();
        }).catch(function() {
          if (dropdown) dropdown.classList.add('d-none');
          if (toggleBtn) toggleBtn.textContent = textChange;
          sessionStorage.setItem('alsendo_template_message', textOperationNotSuccessful);
          location.reload();
        });
      }
    });
  }
});
</script>
