{{ header }}{{ column_left }}
<div id="content">

  <div id="payment-mapping-container" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 99999;">
    <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: 600px;">
      <h5>{{ text_show_shipment_payment_mapping }}</h5>
      <div class="payment-mapping-table-container">
        <table id="shipping-methods-table" class="w-100">
          <thead>
            <tr>
              <th>{{ text_shipping_method }}</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <div class="text-end">
        <button type="button" class="btn btn-secondary ml-2 ok-modal" data-hide-on-click="payment-mapping-container">OK</button>
      </div>
    </div>
  </div>

  <div class="page-header">
    <div class="container-fluid">
      <div class="float-end">
        <button type="submit" form="form-shipping" data-bs-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i></button>
        <a href="{{ back }}" data-bs-toggle="tooltip" title="{{ button_back }}" class="btn btn-light"><i class="fa-solid fa-reply"></i></a>
      </div>
      <h1>{{ heading_title }}</h1>
      <ol class="breadcrumb">
        {% for breadcrumb in breadcrumbs %}
          <li class="breadcrumb-item"><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
        {% endfor %}
      </ol>
    </div>
  </div>
  {% include 'extension/alsendo/admin/view/template/partials/info_modal.twig' %}
  <style>
    #shipping-methods-tbody input.czechia-cb:disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }
  </style>
  <div class="container-fluid">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title"><i class="fa-solid fa-pencil"></i> {{ general_settings_header }}</h3>
      </div>
      <div class="card-body">
        <form id="form-shipping" action="{{ save }}" method="post" data-oc-toggle="ajax">
          <div class="row mb-3">
            <label for="input-tax-class" class="col-sm-2 col-form-label">{{ entry_tax_class }}</label>
            <div class="col-sm-10">
              <select name="shipping_alsendo_tax_class_id" id="input-tax-class" class="form-select">
                <option value="0">{{ text_none }}</option>
                {% for tax_class in tax_classes %}
                  <option value="{{ tax_class.tax_class_id }}"{% if tax_class.tax_class_id == shipping_alsendo_tax_class_id %} selected{% endif %}>{{ tax_class.title }}</option>
                {% endfor %}
              </select>
            </div>
          </div>

        </form>
      </div>
    </div>
  </div>

  <div class="container-fluid mt-4">
      <div class="card">
        <div class="card-header">
          <h3><i class="fas fa-shipping-fast"></i> {{ text_shipping_methods }}</h3>
          <p>{{ text_shipping_methods_subheader }}</p>
        </div>
        <div class="card-body">
          <div id="shipping-methods-container">
            <div class="table-responsive" id="shipping-methods-table-container" style="display: none;">
              <table class="table table-striped mb-0">
                <thead>
                <tr>
                  <th>{{ text_shipping_method_name }}</th>
                  <th>{{ text_courier_service }}</th>
                  <th>{{ text_price }}</th>
                  <th>{{ text_map }}</th>
                  {% if current_region == 'czechia' %}
                  <th>{{ text_ship_via_pickup_point }}</th>
                  <th>{{ text_pickup_request }}</th>
                  {% endif %}
                  <th></th>
                </tr>
                </thead>
                <tbody id="shipping-methods-tbody"></tbody>
              </table>
            </div>

            <div id="no-shipping-methods" style="display: none;">
              <p class="text-muted">{{ text_no_shipping_methods }}</p>
            </div>

            <div class="text-start" style="margin-top: 3px;">
              <button type="button" class="btn btn-link text-decoration-none add-new-shipping-method">{{ text_add_shipping_method }}</button>
            </div>

            <div class="mt-3 text-end">
              <button type="button" class="btn btn-outline-primary shipment-payment-map-btn">{{ text_show_shipment_payment_mapping }}</button>
              <button type="button" class="btn btn-outline-primary" onclick="showManageAvailableServices()">{{ text_enable_courier_services }}</button>
              <button type="button" class="btn btn-primary" style="margin-left: 1em;" onclick="saveAllShippingMethods()">{{ text_save_shipping_methods }}</button>
            </div>
          </div>

          <div id="add-shipping-method-modal" style="display: none;">
            <hr>
            <div class="row">
              <div class="col-12 col-md-6">
                <h5>{{ text_enable_courier_services }}</h5>
                <p>{{ text_enable_courier_services_subheader }}</p>
              </div>
              <div class="col-12 col-md-6 text-end">
                {{ text_last_update }}: <span id="alsendo_courier_service_refresh_date_value">
                  {% if alsendo_courier_service_refresh_date_value %}
                    {{ alsendo_courier_service_refresh_date_value }}
                  {% else %}
                    {{ text_never }}
                  {% endif %}
                </span>
                <buton type="button" class="btn btn-link text-decoration-none refresh-shipping-services"><i class="fas fa-sync-alt"></i> {{ text_refresh_courier_services }}</buton>
              </div>
            </div>
            <div id="services-loading" style="display: none;">
              <div class="text-center">
                <i class="fas fa-spinner fa-spin fa-2x"></i>
                <p>{{ text_loading_services }}</p>
              </div>
            </div>

            <div id="services-selection" style="display: none;">
              <div id="services-selection-top-buttons" class="mt-3 text-end mb-3" style="display: none;">
                <button type="button" class="btn btn-outline-secondary toggle-select-all-services-btn" onclick="toggleSelectAllServices()">
                  {{ text_unselect_all }}
                </button>
                <button type="button" class="btn btn-outline-primary" onclick="hideAddShippingMethodModal()">
                  {{ text_cancel }}
                </button>
                <button type="button" class="btn btn-primary" style="margin-left: 1em;" onclick="saveServiceSelection()">
                  {{ text_save_and_close }}
                </button>
              </div>
              <div class="table-responsive">
                <table class="table table-striped">
                  <thead>
                  <tr>
                    <th>{{ text_courier_service }}</th>
                    <th>{{ text_map }}</th>
                    <th>{{ text_active }}</th>
                  </tr>
                  </thead>
                  <tbody id="services-selection-tbody"></tbody>
                </table>
              </div>

              <div class="mt-3 text-end">
                <button type="button" class="btn btn-outline-secondary toggle-select-all-services-btn" onclick="toggleSelectAllServices()">
                  {{ text_unselect_all }}
                </button>
                <button type="button" class="btn btn-outline-primary" onclick="hideAddShippingMethodModal()">
                  {{ text_cancel }}
                </button>
                <button type="button" class="btn btn-primary" style="margin-left: 1em;" onclick="saveServiceSelection()">
                  {{ text_save_and_close }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
  </div>
</div>

<script>
  let selectedServices = [];
  const isCzechia = {{ current_region == 'czechia' ? 'true' : 'false' }};

  function loadShippingMethods() {
    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'get_shipping_methods',
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function(json) {
        if (json.success) {
          selectedServices = json.selected_services || [];
          displayShippingMethods(json.methods);
        } else {
          showInfoModal('{{ text_error_prefix|e('js') }}: ' + (json.error || '{{ text_unknown_error|e('js') }}'));
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_error_loading_shipping_methods|e('js') }}');
      }
    });
  }

  function displayShippingMethods(methods) {
    const tbody = document.getElementById('shipping-methods-tbody');
    const tableContainer = document.getElementById('shipping-methods-table-container');
    const noMethodsDiv = document.getElementById('no-shipping-methods');

    tbody.innerHTML = '';

    if (methods.length === 0) {
      tableContainer.style.display = 'none';
      noMethodsDiv.style.display = 'block';
      return;
    }

    noMethodsDiv.style.display = 'none';
    tableContainer.style.display = 'block';

    methods.forEach(function(method) {
      const row = tbody.insertRow();
      let colIdx = 0;

      const nameCell = row.insertCell(colIdx++);
      nameCell.innerHTML = '<input type="text" class="form-control shipping-method-name" data-method-id="' + method.id + '" value="' + (method.custom_name || '') + '">';

      const serviceCell = row.insertCell(colIdx++);
      let serviceDropdown = '<select class="form-control shipping-method-service" data-method-id="' + method.id + '">';
      serviceDropdown += '<option value="">{{ text_select_service|e('js') }}</option>';
      selectedServices.forEach(function(service) {
        const selected = method.service_id === service.id ? ' selected' : '';
        serviceDropdown += '<option value="' + service.id + '"' + selected + '>' + service.name + '</option>';
      });
      serviceDropdown += '</select>';
      serviceCell.innerHTML = serviceDropdown;

      const priceCell = row.insertCell(colIdx++);
      const priceValue = method.price || '';
      priceCell.innerHTML = '<div class="input-group"><input type="number" step="0.01" min="0" class="form-control shipping-method-price" data-method-id="' + method.id + '" value="' + priceValue + '"><span class="input-group-text">{{ current_store_currency|e('js') }}</span></div>';

      const mapCell = row.insertCell(colIdx++);
      const allowMapSelection = {{ allow_map_selection|json_encode }};
      mapCell.innerHTML = '<input type="checkbox" class="form-check-input has-map-checkbox" ' + (method.has_map ? 'checked' : '') + ((method.service_id && !allowMapSelection) ? ' disabled' : '' ) + ' data-method-id="'+method.id+'">';

      if (isCzechia) {
        const svc = method.service_id ? selectedServices.find(function(s) { return String(s.id) === String(method.service_id); }) : null;
        const anyService = !svc;
        const shipViaAllowed = anyService || (svc && (Number(svc.point_to_point) > 0 || Number(svc.point_to_door) > 0));
        const pickupReqAllowed = anyService || (svc && (Number(svc.door_to_point) > 0 || Number(svc.door_to_door) > 0));
        const chk = function(field, allowed, val) {
          const disabled = !allowed;
          const checked = !disabled && val;
          return '<input type="checkbox" class="form-check-input czechia-cb ' + field + '-cb" data-method-id="' + method.id + '" data-field="' + field + '"' + (checked ? ' checked' : '') + (disabled ? ' disabled' : '') + '>';
        };
        row.insertCell(colIdx++).innerHTML = chk('shipping_via_pickup_point', shipViaAllowed, method.shipping_via_pickup_point);
        row.insertCell(colIdx++).innerHTML = chk('pickup_request', pickupReqAllowed, method.pickup_request);
      }

      const actionCell = row.insertCell(colIdx++);
      actionCell.innerHTML = '<button type="button" class="btn btn-sm btn-danger" onclick="removeShippingMethod(' + method.id + ')" title="{{ text_remove_shipping_method|e('js') }}"><i class="fas fa-times"></i></button>';
    });

    document.querySelectorAll('select.shipping-method-service').forEach(sel => {
      sel.addEventListener('change', function(e) {
        const id = sel.dataset.methodId;
        const cb = document.querySelector('.has-map-checkbox[data-method-id="' + id + '"]');
        if (cb) cb.disabled = e.target.value !== '';
        if (isCzechia) {
          const row = e.target.closest('tr');
          if (row) updateCzechiaCheckboxesForRow(row, e.target.value);
        }
      });
    });

    if (isCzechia) {
      document.getElementById('shipping-methods-tbody').addEventListener('change', function(e) {
        if (!e.target.classList.contains('czechia-cb')) return;
        const field = e.target.dataset.field;
        const row = e.target.closest('tr');
        if (!row) return;
        if (field === 'shipping_via_pickup_point' && e.target.checked) uncheckInRow(row, 'pickup_request');
        if (field === 'pickup_request' && e.target.checked) uncheckInRow(row, 'shipping_via_pickup_point');
      });
    }
  }

  function uncheckInRow(row, field) {
    const cb = row.querySelector('.czechia-cb.' + field + '-cb');
    if (cb && !cb.disabled) { cb.checked = false; }
  }

  function updateCzechiaCheckboxesForRow(row, serviceId) {
    if (!row) return;
    const svc = serviceId ? selectedServices.find(function(s) { return String(s.id) === String(serviceId); }) : null;
    const anyService = !svc;
    const shipViaAllowed = anyService || (svc && (Number(svc.point_to_point) > 0 || Number(svc.point_to_door) > 0));
    const pickupReqAllowed = anyService || (svc && (Number(svc.door_to_point) > 0 || Number(svc.door_to_door) > 0));
    const shipViaCb = row.querySelector('.shipping_via_pickup_point-cb');
    const pickupReqCb = row.querySelector('.pickup_request-cb');
    if (shipViaCb) {
      shipViaCb.disabled = !shipViaAllowed;
      if (shipViaCb.disabled) shipViaCb.checked = false;
    }
    if (pickupReqCb) {
      pickupReqCb.disabled = !pickupReqAllowed;
      if (pickupReqCb.disabled) pickupReqCb.checked = false;
    }
  }

  function updateShippingMethod(methodId, id, customName, price) {
    const data = {
      action: 'update_shipping_method',
      method_id: methodId,
      user_token: '{{ user_token|e('js') }}'
    };

    if (id !== null) {
      data.service_id = id;
    }
    if (customName !== null) {
      data.custom_name = customName;
    }
    if (price !== null) {
      data.price = price;
    }

    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: data,
      dataType: 'json',
      success: function(json) {
        if (json.success) {
          showInfoModal('{{ success_shipping_method_updated|e('js') }}');
        } else {
          showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
          loadShippingMethods();
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_error_saving_shipping_methods|e('js') }}');
        loadShippingMethods();
      }
    });
  }

  function saveAllShippingMethods(suppressSuccessModal) {
    const nameInputs = document.querySelectorAll('.shipping-method-name');
    const methods = [];

    nameInputs.forEach(function(nameInput) {
      const methodId = nameInput.getAttribute('data-method-id');
      const customName = nameInput.value.trim();
      const serviceSelect = document.querySelector('.shipping-method-service[data-method-id="' + methodId + '"]');
      const serviceId = serviceSelect ? serviceSelect.value : '';
      const priceInput = document.querySelector('.shipping-method-price[data-method-id="' + methodId + '"]');
      const hasMap = document.querySelector('.has-map-checkbox[data-method-id="' + methodId + '"]');
      const hasMapValue = hasMap ? hasMap.checked : '0';
      const price = priceInput ? priceInput.value : '';

      if (methodId && customName) {
        let methodData = {
          method_id: methodId,
          id: serviceId,
          custom_name: customName,
          price: price,
        };

        methodData.has_map = hasMapValue;

        if (isCzechia) {
          const row = nameInput.closest('tr');
          const czechiaVal = function(field) {
            const cb = row ? row.querySelector('.' + field + '-cb') : null;
            if (!cb || cb.disabled) return null;
            return cb.checked ? 1 : 0;
          };
          methodData.shipping_via_pickup_point = czechiaVal('shipping_via_pickup_point');
          methodData.pickup_request = czechiaVal('pickup_request');
        }

        methods.push(methodData);
      }
    });

    if (methods.length === 0) {
      return;
    }

    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'save_all_shipping_methods',
        methods: methods,
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function(json) {
        if (json.success) {
          loadShippingMethods();
          if (!suppressSuccessModal) {
            showInfoModal('{{ success_shipping_methods_saved|e('js') }}');
          }
        } else {
          showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_error_saving_shipping_methods|e('js') }}');
      }
    });
  }

  function removeShippingMethod(methodId) {
    if (confirm('{{ text_confirm_remove_shipping_method|e('js') }}')) {
      $.ajax({
        url: window.location.href,
        type: 'POST',
        data: {
          action: 'remove_shipping_method',
          method_id: methodId,
          user_token: '{{ user_token|e('js') }}'
        },
        dataType: 'json',
        success: function(json) {
          if (json.success) {
            loadShippingMethods();
            showInfoModal('{{ success_shipping_method_removed|e('js') }}');
          } else {
            showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
          }
        },
        error: function(xhr, status, error) {
          showInfoModal('{{ text_error_saving_shipping_methods|e('js') }}');
        }
      });
    }
  }

  function addNewShippingMethod() {
    saveAllShippingMethods(true);
    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'add_new_shipping_method',
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function(json) {
        if (json.success) {
          loadShippingMethods();
        } else {
          showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_error_saving_shipping_methods|e('js') }}');
      }
    });
  }

  function showManageAvailableServices() {
    document.getElementById('add-shipping-method-modal').style.display = 'block';
    document.getElementById('services-loading').style.display = 'block';
    document.getElementById('services-selection').style.display = 'none';

    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'get_all_services_for_selection',
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function(json) {
        document.getElementById('services-loading').style.display = 'none';

        if (json.success) {
          displayServicesForSelection(json.services);
          document.getElementById('services-selection').style.display = 'block';
        } else {
          showInfoModal('{{ text_error_prefix|e('js') }}: ' + (json.error || '{{ text_unknown_error|e('js') }}'));
        }
      },
      error: function(xhr, status, error) {
        document.getElementById('services-loading').style.display = 'none';
        showInfoModal('{{ text_error_loading_services|e('js') }}');
      }
    });
  }

  function displayServicesForSelection(services) {
    const tbody = document.getElementById('services-selection-tbody');
    const topButtons = document.getElementById('services-selection-top-buttons');
    tbody.innerHTML = '';

    services.forEach(function(service) {
      const row = tbody.insertRow();

      const nameCell = row.insertCell(0);
      nameCell.innerHTML = service.name;

      const mapCell = row.insertCell(1);
      mapCell.innerHTML = '<input type="checkbox" class="form-check-input" ' + (service.has_map ? 'checked' : '') + ' disabled>';

      const activeCell = row.insertCell(2);
      activeCell.innerHTML = '<input type="checkbox" class="form-check-input service-checkbox" value="' + service.id + '" ' + (service.is_selected ? 'checked' : '') + '>';
    });

    if (topButtons) {
      topButtons.style.display = services.length > 0 ? '' : 'none';
    }

    updateToggleSelectAllButtonText();
    tbody.querySelectorAll('.service-checkbox').forEach(function(cb) {
      cb.addEventListener('change', updateToggleSelectAllButtonText);
    });
  }

  function updateToggleSelectAllButtonText() {
    var checked = document.querySelectorAll('#services-selection-tbody .service-checkbox:checked').length;
    var text = checked > 0 ? '{{ text_unselect_all|e('js') }}' : '{{ text_select_all|e('js') }}';
    document.querySelectorAll('.toggle-select-all-services-btn').forEach(function(btn) {
      btn.textContent = text;
    });
  }

  function toggleSelectAllServices() {
    var checkboxes = document.querySelectorAll('#services-selection-tbody .service-checkbox');
    var checkedCount = document.querySelectorAll('#services-selection-tbody .service-checkbox:checked').length;
    var shouldSelect = checkedCount === 0;
    checkboxes.forEach(function(cb) {
      cb.checked = shouldSelect;
    });
    updateToggleSelectAllButtonText();
  }

  function hideAddShippingMethodModal() {
    document.getElementById('add-shipping-method-modal').style.display = 'none';
  }

  function saveServiceSelection() {
    const checkboxes = document.querySelectorAll('.service-checkbox:checked');
    const selectedIds = Array.from(checkboxes).map(cb => cb.value);

    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'save_service_selection',
        selected_ids: selectedIds,
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function(json) {
        if (json.success) {
          hideAddShippingMethodModal();
          loadShippingMethods();
          showInfoModal('{{ success_service_selection_saved|e('js') }}');
        } else {
          showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_error_saving_settings|e('js') }}');
      }
    });
  }

  function refreshShippingServices() {
    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'get_shipping_services',
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function(json) {
        if (json.refresh_date) {
          try {
            sessionStorage.setItem('alsendo_services_refreshed_message', '{{ success_services_refreshed|e('js') }}');
          } catch (e) {}
          location.reload();
        } else if (json.error) {
          showInfoModal(json.error);
        }
      },
      error: function(xhr, status, error) {
        showInfoModal('{{ text_error_refreshing_services|e('js') }}');
      }
    });
  }

  const existingMappings = {{ payments_map|json_encode|raw }};

  function loadShippingMethodForPaymentMapping() {
    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        action: 'get_shipping_methods',
        user_token: '{{ user_token|e('js') }}'
      },
      dataType: 'json',
      success: function (json) {
        if (json.success && json.methods) {
          const tbody = $('#shipping-methods-table tbody');
          tbody.empty();

          const thead = $('#shipping-methods-table thead tr');
          thead.empty();

          thead.append('<th class="text-start" style="width:' + (100 / (1 + {{ payments|length }})) + '%">{{ text_shipping_method|e('js') }}</th>');
          {% for payment in payments %}
            thead.append('<th class="text-center" style="width:' + (100 / (1 + {{ payments|length }})) + '%">{{ payment.name|e('js') }}</th>');
          {% endfor %}

          $.each(json.methods, function (i, method) {
            let row = '<tr><td class="text-start">' + method.custom_name + '</td>';
            {% for payment in payments %}
            row += '<td class="text-center"><input class="payment-shipment-checkbox" data-shipment-method-id="'+method.id+'" data-payment-method-id="{{ payment.extension_id }}" type="checkbox" '
                    + ((existingMappings[method.id] && existingMappings[method.id].includes({{ payment.extension_id }})) ? 'checked' : '')
                    + '></td>';
            {% endfor %}

            row += '</tr>';
            tbody.append(row);
          });
        }
      }
    });
  }



  $(document).ready(function() {
    try {
      const msg = sessionStorage.getItem('alsendo_services_refreshed_message');
      if (msg) {
        sessionStorage.removeItem('alsendo_services_refreshed_message');
        showManageAvailableServices();
        showInfoModal(msg);
      }
    } catch (e) {}
    loadShippingMethods();

    document.querySelectorAll('.add-new-shipping-method').forEach(el => {
      el.addEventListener('click', addNewShippingMethod);
    });

    document.querySelectorAll('.refresh-shipping-services').forEach(el => {
      el.addEventListener('click', refreshShippingServices);
    });


    $(document).on('click', '.shipment-payment-map-btn', function () {
      $('#payment-mapping-container').fadeIn(50);
      loadShippingMethodForPaymentMapping();
    });

    $(document).on('click', '.ok-modal', function () {
      const result = {};

      $('.payment-shipment-checkbox:checked').each(function () {
        const shipmentId = $(this).data('shipment-method-id');
        const paymentId = $(this).data('payment-method-id');

        if (!result[shipmentId]) {
          result[shipmentId] = [];
        }

        result[shipmentId].push(paymentId);
      });

      $.ajax({
        url: window.location.href,
        type: 'POST',
        data: {
          action: 'save_payment_mapping',
          mappings: result,
          user_token: '{{ user_token|e('js') }}'
        },
        dataType: 'json',
        success: function(json) {
          if (json && json.success) {
            showInfoModal(json.message || '{{ success_payment_mapping_saved|e('js') }}');
            $('#payment-mapping-container').fadeOut(50);
            $('#hide-info-modal').one('click', function() {
              location.reload();
            });
          } else if (json && json.error) {
            showInfoModal('{{ text_error_prefix|e('js') }}: ' + json.error);
          }
        },
        error: function(xhr, status, error) {
          showInfoModal('{{ text_error_saving_settings|e('js') }}');
        }
      });
    });


    $(function() {
      if (new URLSearchParams(window.location.search).has('refresh_date')) showManageAvailableServices();
    });

  });
</script>

{{ footer }}