{% include 'extension/alsendo/admin/view/template/partials/info_modal.twig' %}

<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> {{ text_alsendo_shipping_singular }}</h6>
    </div>
    <div class="card-body">
      <div class="row">
          <fieldset>
            <legend>{{ text_sender_address_header }}</legend>
            <div class="row mb-3">
              <p class="mb-0">{{ order_details.sender.getSummaryText() }}</p>
              <div class="mt-1">
                <button type="button" class="btn btn-link btn-sm p-0 text-decoration-none" id="alsendo-sender-change-toggle">{{ text_change }}</button>
                <div id="alsendo-sender-dropdown" class="mt-2 d-flex align-items-center flex-wrap gap-2 d-none">
                  <select class="form-select form-select-sm" id="alsendo-sender-template-select" style="max-width:20em;">
                    {% for t in sender_address_templates %}
                      <option value="{{ t.id }}" {% if order_details.sender.senderTemplateId == t.id %}selected{% endif %}>{{ t.company_name }}</option>
                    {% endfor %}
                  </select>
                  <button type="button" class="btn btn-primary btn-sm" id="alsendo-sender-save">{{ text_save }}</button>
                </div>
              </div>
            </div>
          </fieldset>

          <fieldset>
            <legend>{{ text_recipient_address_header }}</legend>
            <div class="row mb-3">
              <p class="mb-0">{{ order_details.shippingAddress.getSummaryText() }}</p>
              {% if order_details.shippingAddress.deliveryPoint %}
                <p class="mb-0 fw-semibold">{{ order_details.shippingAddress.getDeliveryPointText() }}</p>
              {% endif %}
            </div>
          </fieldset>

          <fieldset>
            <legend>{{ text_package }}</legend>

            {% for package in order_details.packageDetails.packages %}
            <div class="row mb-3 alsendo-package-row" data-order-id="{{ order_id }}" data-package-index="{{ loop.index0 }}">
              <p class="mb-0">{{ package.getSummaryText() }}</p>
              <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 == 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>
              <p class="mb-0">{{ order_details.packageDetails.packageContent }}</p>
              <p class="mb-0">{{ order_details.packageDetails.codValue.toString() }}, {{ order_details.packageDetails.declaredValue.toString() }}</p>
            </div>
            {% endfor %}
          </fieldset>

          <fieldset>
            <legend>{{ text_shipment_header }}</legend>
            <div class="row mb-3">
              <p class="mb-0">{{ text_pickup_type }}: {{ order_details.packageDetails.getPickupTypeLabel() }}</p>
              <p class="mb-0">{{ text_shipping_method }}: {{ order_details.shipment.shippingMethodName }}</p>
              {% if shipping_service_name %}
              <p class="mb-0">{{ text_courier_service }}: {{ order_details.shipment.shippingServiceName }}</p>
              {% endif %}
              <div id="get-a-quote-container" style="display:block;">
                <p class="d-inline" style="margin-right: 0.6em;">{{ text_price }}: </p>
                <button
                        style="all:unset; cursor:pointer; color: #1e91cf"
                        type="button"
                        id="get-quote-button"
                        data-quote-outside-form="true"
                >{{ text_get_a_quote }}</button>
              </div>

              <div class="row mb-2" id="courier-services-container" style="display: none;">
                <div>
                  <div id="courier-services-container-inner" style="display:flex;flex-wrap:wrap;gap:1em;">
                  </div>
                  <input type="hidden" id="shipment-selected-service" name="shipment_selected_service" value="{{ order_details.data.shipment.service_id }}">
                </div>

                {% if is_pickup == true %}
                  <input type="hidden" id="error-pickup-hour-range" value="{{ error_pickup_hour_range }}">
                  <input type="hidden" id="error-pickup-date-past" value="{{ error_choose_preferred_pickup_date_not_past }}">

                  <div class="row mb-4" id="shipment-preferred-pickup-date-container">
                    <div class="my-2">
                      <div class="row align-items-end">
                        <div class="col-md-6">
                          <label for="shipment-preferred-pickup-date" class="form-label">{{ text_choose_preferred_pickup_date }}</label>
                        </div>
                        <div class="col-md-6">
                          <label for="shipment-preferred-pickup-hour-from" class="form-label">{{ text_choose_preferred_pickup_hours }}</label>
                        </div>
                      </div>
                      <div class="row align-items-end">
                        <div class="col-md-6">
                          <input type="date" class="form-control" id="shipment-preferred-pickup-date" name="shipment_preferred_pickup_date" value="{{ order_details.shipment.preferredPickupDate ? order_details.shipment.preferredPickupDate|date('Y-m-d') : 'now'|date('Y-m-d') }}">
                        </div>
                        {% set hours = 8..17 %}

                        {% set preferredHourFrom = order_details.shipment.preferredPickupHourFrom ?: default_pickup_hour_from %}
                        {% set preferredHourTo = order_details.shipment.preferredPickupHourTo ?: default_pickup_hour_to %}

                        <div class="col-md-2">
                          <select id="shipment-preferred-pickup-hour-from" class="form-control">
                            {% for hour in hours %}
                              {% set formatted = '%02d:00'|format(hour) %}
                              <option value="{{ formatted }}" {% if formatted == preferredHourFrom %}selected{% endif %}>{{ formatted }}</option>
                            {% endfor %}
                          </select>
                        </div>
                        <div class="col-md-2">
                          <select id="shipment-preferred-pickup-hour-to" class="form-control">
                            {% for hour in hours %}
                              {% set formatted = '%02d:00'|format(hour) %}
                              <option value="{{ formatted }}" {% if formatted == preferredHourTo or ((preferredHourTo is not defined or preferredHourTo is empty) and loop.last) %}selected{% endif %}>{{ formatted }}</option>
                            {% endfor %}
                          </select>
                        </div>

                      </div>
                    </div>
                  </div>
                {% endif %}
              </div>

              <div class="text-end mt-4">
                <a class="btn btn-link text-decoration-none" href="{{ full_form_url }}">{{ text_go_to_full_order_form }}</a>
                <button type="button" class="btn btn-primary" id="alsendo-order-shipment-button">{{ button_order_shipment }}</button>
              </div>

            </div>


          </fieldset>


      </div>
    </div>
  </div>
  <input type="hidden" id="initial-service-id" value="{{ order_details.data.shipment.service_id }}" form="none">
  <input type="hidden" id="user-token" value="{{ user_token }}" form="none">
  <input type="hidden" id="order-id" value="{{ order_id }}" form="none">
</div>

<script>
window.ALSENDO_TEXT_NO_QUOTE_AVAILABLE = "{{ text_no_quote_available_for_order_parameters|e('js') }}";
$(document).ready(function() {
  var postReloadMessage = sessionStorage.getItem('alsendo_template_message');
  if (postReloadMessage) {
    sessionStorage.removeItem('alsendo_template_message');
    showInfoModal(postReloadMessage);
  }

  var orderShipmentButton = document.getElementById('alsendo-order-shipment-button');
  if (orderShipmentButton) {
    var dateContainer = document.getElementById('shipment-preferred-pickup-date-container');
    var hourFrom = document.getElementById('shipment-preferred-pickup-hour-from');
    var hourTo = document.getElementById('shipment-preferred-pickup-hour-to');
    var dateInput = document.getElementById('shipment-preferred-pickup-date');

    orderShipmentButton.addEventListener('click', function(e) {
      e.preventDefault();

      if (dateContainer && getComputedStyle(dateContainer).display !== 'none') {
        var fromVal = hourFrom && hourFrom.value ? parseInt(hourFrom.value.split(':')[0], 10) : 0;
        var toVal = hourTo && hourTo.value ? parseInt(hourTo.value.split(':')[0], 10) : 0;
        if (toVal - fromVal < 2 || toVal <= fromVal) {
          showInfoModal('{{ error_pickup_hour_range|e('js') }}');
          return;
        }

        var selectedDate = dateInput && dateInput.value ? new Date(dateInput.value) : null;
        var today = new Date();
        today.setHours(0, 0, 0, 0);

        if (!dateInput || !dateInput.value || !selectedDate || selectedDate < today) {
          showInfoModal('{{ error_choose_preferred_pickup_date_not_past|e('js') }}');
          return;
        }
      }

      orderShipmentButton.disabled = true;

      var payloadData = {
        order_id: {{ order_id }},
        by_order_id: true
      };

      var shipmentSelectedService = $('#shipment-selected-service');
      if (shipmentSelectedService.length) {
        payloadData.shipment_selected_service = shipmentSelectedService.val();
      }

      if (dateContainer && getComputedStyle(dateContainer).display !== 'none') {
        payloadData.shipment_preferred_pickup_hour_from = hourFrom ? hourFrom.value : '';
        payloadData.shipment_preferred_pickup_hour_to = hourTo ? hourTo.value : '';
        payloadData.shipment_preferred_pickup_date = dateInput ? dateInput.value : '';
      }

      $.ajax({
        url: 'index.php?route=extension/alsendo/alsendo_order.submitOrderShipment&user_token={{ user_token|e('js') }}',
        type: 'POST',
        data: payloadData,
        dataType: 'json',
        success: function (sendJson) {
          if (sendJson.success === true) {
            location.reload();
          } else {
            orderShipmentButton.disabled = false;
            if (sendJson.errors && typeof sendJson.errors === 'object' && Object.keys(sendJson.errors).length > 0) {
              var container = document.getElementById('alsendo-order-section');
              if (container) {
                container.querySelectorAll('.input-validation-error').forEach(function(input) { input.classList.remove('input-validation-error'); });
                container.querySelectorAll('small.validation-error-message').forEach(function(el) { el.remove(); });
                for (var field in sendJson.errors) {
                  if (!sendJson.errors.hasOwnProperty(field)) continue;
                  var message = sendJson.errors[field];
                  var msgText = Array.isArray(message) ? (message[0] || '') : message;
                  var input = container.querySelector('[name="' + field + '"]') || container.querySelector('[id="' + field.replace(/_/g, '-') + '"]');
                  if (input && container.contains(input)) {
                    input.classList.add('input-validation-error');
                    var errorEl = document.createElement('small');
                    errorEl.className = 'validation-error-message text-danger d-block';
                    errorEl.textContent = msgText;
                    input.insertAdjacentElement('afterend', errorEl);
                  }
                }
              }
              showInfoModal(sendJson.error || '');
            } else {
              showInfoModal(sendJson.error || '');
            }
          }
        },
        error: function (xhr, status, error) {
          console.log(error);
          showInfoModal(error);
          orderShipmentButton.disabled = false;
        }
      });
    });
  }

  var textChange = '{{ text_change|e('js') }}';
  var textCancel = '{{ text_cancel|e('js') }}';
  var textOperationNotSuccessful = '{{ text_operation_not_successful|e('js') }}';
  var orderId = {{ order_id }};
  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 senderToggle = document.getElementById('alsendo-sender-change-toggle');
  var senderDropdown = document.getElementById('alsendo-sender-dropdown');
  if (senderToggle && senderDropdown) {
    senderToggle.addEventListener('click', function() {
      if (senderDropdown.classList.contains('d-none')) {
        senderDropdown.classList.remove('d-none');
        senderToggle.textContent = textCancel;
      } else {
        senderDropdown.classList.add('d-none');
        senderToggle.textContent = textChange;
      }
    });
  }
  var senderSave = document.getElementById('alsendo-sender-save');
  var senderSelect = document.getElementById('alsendo-sender-template-select');
  if (senderSave && senderSelect) {
    senderSave.addEventListener('click', function() {
      var templateId = parseInt(senderSelect.value, 10) || 0;
      var formData = new FormData();
      formData.append('order_id', orderId);
      formData.append('template_id', templateId);
      fetch(urlSender, { method: 'POST', body: formData }).then(function(r) { return r.json(); }).then(function(json) {
        senderDropdown.classList.add('d-none');
        senderToggle.textContent = textChange;
        var msg = json.success ? (json.message || '') : (textOperationNotSuccessful + ': ' + (json.error || ''));
        sessionStorage.setItem('alsendo_template_message', msg);
        location.reload();
      }).catch(function() {
        senderDropdown.classList.add('d-none');
        senderToggle.textContent = textChange;
        sessionStorage.setItem('alsendo_template_message', textOperationNotSuccessful);
        location.reload();
      });
    });
  }

  var orderSection = document.getElementById('alsendo-order-section');
  if (orderSection) {
    orderSection.addEventListener('click', function(e) {
      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 || orderId);
        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>
