<div class="container-fluid" id="alsendo-order-section">
  <div class="card mb-3">
    <div class="card-header">
      <h6 class="card-title"><i class="fas fa-shipping-fast"></i> Alsendo Shipping</h6>
    </div>
    <div class="card-body">
      <div class="row">
          <fieldset>
            <legend>{{ column_shipment_text }}</legend>
            <div class="row mb-3">
              <div class="d-flex justify-content-between w-100">
                <p class="mb-0">Status: {{ dto.status }}</p>
                {% if dto.trackingPageUrl %}
                <a class="btn btn-link text-decoration-none" href="{{ dto.trackingPageUrl }}">{{ text_tracking_page_link }}</a>
                {% endif %}
              </div>
              <p class="mb-0">{{ text_shipping_method }}: {{ dto.shippingMethod }}</p>
              {% if dto.serviceName %}
                <p class="mb-0">{{ text_courier_service }}: {{ dto.serviceName }}</p>
              {% endif %}
              <div class="d-flex justify-content-between w-100">
                <p class="mb-0">{{ text_waybill_number }}: {{ dto.getWaybillNumbersAsString() }}</p>
                <button class="btn btn-link text-decoration-none copy-to-clipboard-clickable" style="cursor:pointer; color:#1874A6; position:relative" data-to-copy="{{ dto.getWaybillNumbersAsString() }}">Copy to clipboard</button>
              </div>
              <div class="d-flex justify-content-between w-100">
                <p class="mb-0">{{ text_shipment_documents_download }}</p>
                <button type="button" class="btn btn-link text-decoration-none download-waybill-button">{{ text_download }}</button>
              </div>
            </div>
          </fieldset>

          <fieldset>
            <legend>{{ text_shipment_details_header }}</legend>
            <div class="row mb-3">
              <p class="mb-0">{{ text_label_sender }}: {{ dto.senderSummary }}</p>
              <p class="mb-0">{{ text_label_recipient }}: {{ dto.recipientSummary }}</p>

              {% if dto.packages is not empty %}
                {% for singlePackage in dto.packages %}
                  <p class="mb-0">
                    {{ text_label_package }}{% if dto.packages|length > 1 %} {{ loop.index }}{% endif %}:
                    {% if singlePackage.templateName is not empty %}
                      {{ singlePackage.templateName }},
                    {% endif %}
                    {{ singlePackage.width }}x{{ singlePackage.length }}x{{ singlePackage.height }}cm,
                    {{ singlePackage.weight }}kg,
                    {{ singlePackage.packageType }}
                  </p>
                {% endfor %}
              {% endif %}

              {% if dto.pickupPointText %}
                <p class="mb-0">{{ text_pickup_point }}: {{ dto.pickupPointText }}</p>
              {% endif %}

              <div class="d-flex justify-content-end w-100">
                  <button type="button" class="btn btn-link text-decoration-none cancel-order-btn" style="cursor:pointer; color:#1874A6;">
                    {% if order_shipment.status != 'cancelled' %}
                      {{ text_button_cancel_order }}
                    {% else %}
                      Order was cancelled
                    {% endif %}
                  </button>
              </div>
            </div>
          </fieldset>



      </div>
    </div>
  </div>
  <input type="hidden" id="user-token" value="{{ user_token }}" form="none">
</div>

<div id="info-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 9999;">
  <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); min-width: 400px;">
    <p id="info-modal-paragraph"></p>
    <div class="text-end">
      <button type="button" class="btn btn-secondary ml-2" id="hide-info-modal">
        OK
      </button>
    </div>
  </div>
</div>

<div id="cancel-order-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 9999;">
  <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); min-width: 400px;">
    <h4>{{ text_cancel_order_header }}</h4>
    <p>{{ text_are_you_sure_cancel_question }}</p>
    <div class="text-end">
      <button type="button" class="btn btn-danger" id="confirm-cancel-btn">{{ text_yes }}</button>
      <button type="button" class="btn btn-secondary ml-2" id="cancel-modal-btn">{{ text_no }}</button>
    </div>
  </div>
</div>

<script>
  document.querySelectorAll('.copy-to-clipboard-clickable').forEach(el => {
    el.addEventListener('click', () => {
      navigator.clipboard.writeText(el.dataset.toCopy);

      const msg = document.createElement('span');
      msg.textContent = '{{ text_copied_exclamation|e('js') }}';
      msg.style.cssText = `
        position:absolute;
        top:-20px;
        left:0;
        background:#333;
        color:#fff;
        padding:2px 6px;
        border-radius:4px;
        font-size:12px;
        opacity:0;
        transition:opacity .3s;
      `;
      el.appendChild(msg);
      requestAnimationFrame(() => msg.style.opacity = 1);

      setTimeout(() => {
        msg.style.opacity = 0;
        setTimeout(() => msg.remove(), 300);
      }, 1000);
    });
  });

  document.querySelector('.cancel-order-btn').addEventListener('click', function() {
    document.getElementById('cancel-order-modal').style.display = 'block';
  });

  document.getElementById('cancel-modal-btn').addEventListener('click', function() {
    document.getElementById('cancel-order-modal').style.display = 'none';
  });

  document.getElementById('confirm-cancel-btn').addEventListener('click', function() {
    $.ajax({
      url: 'index.php?route=extension/alsendo/alsendo_order.cancel&user_token=' + '{{ user_token|e('js') }}',
      type: 'POST',
      data: {
        alsendo_order_id: '{{ order_id }}'
      },
      dataType: 'json',
      success: function(json) {
        if (json.success) {
          location.reload();
        } else {
          showInfoModal('{{ text_operation_not_successful|e('js') }}: ' + json.error);
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_operation_not_successful|e('js') }}: ' + error);
      }
    });
    document.getElementById('cancel-order-modal').style.display = 'none';
  });

  $('.download-waybill-button').on('click', function () {
    const alsendoOrderId = '{{ dto.orderShipmentId }}';
    const userToken = '{{ user_token|e('js') }}';
    const url = 'index.php?route=extension/alsendo/alsendo_order.downloadShipmentWaybill&user_token=' + userToken;

    $.ajax({
      url: url,
      type: 'POST',
      data: { alsendo_order_id: alsendoOrderId },
      dataType: 'json',
      success: function (json) {
        if (json.success === false) {
          showInfoModal(json.error || json.message || '{{ text_operation_not_successful|e('js') }}');
          return;
        }
        if (json.success && json.waybill && json.type === 'pdf') {
          const base64Data = json.waybill.replace(/^data:application\/pdf;base64,/, '');
          const binary = atob(base64Data);
          const bytes = new Uint8Array(binary.length);
          for (let i = 0; i < binary.length; i++) {
            bytes[i] = binary.charCodeAt(i);
          }
          const blob = new Blob([bytes], { type: 'application/pdf' });
          const link = document.createElement('a');
          const blobUrl = window.URL.createObjectURL(blob);
          link.href = blobUrl;
          link.download = 'waybill_' + alsendoOrderId + '.pdf';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(blobUrl);
        }
      },
      error: function (xhr, status, error) {
        let msg = '{{ text_operation_not_successful|e('js') }}: ' + error;
        if (xhr.responseText && xhr.responseText.indexOf('{') === 0) {
          try {
            const json = JSON.parse(xhr.responseText);
            if (json && (json.error || json.message)) {
              msg = json.error || json.message;
            }
          } catch (e) {}
        }
        showInfoModal(msg);
      }
    });
  });


  document.getElementById('hide-info-modal').addEventListener('click', function() {
    document.getElementById('info-modal').style.display = 'none';
  });

  function showInfoModal(text) {
    document.getElementById('info-modal-paragraph').innerHTML = text;
    document.getElementById('info-modal').style.display = 'block';
  }
</script>