/**
 * WC Vendors Pro Order Tracking Script
 *
 * @version 1.8.7
 * @since   1.8.7
 */
jQuery(document).ready(function ($) {
  const formFields = $('#wcvendors_order_tracking_fields_meta_box').find(
    'input[type="text"], select'
  );
  const inputs = $('#wcvendors_order_tracking_fields_meta_box').find(
    'input[type="text"]'
  );

  let select2_args = {
    placeholderOption: 'first',
    width: '100%',
  };
  $('.wcv-select2').select2(select2_args);

  // validate select fields
  $('.wcv-select2').on('select2:select', function (e) {
    validateField($(e.target));
  });

  $(inputs).each(function () {
    $(this).on('change, blur', function (e) {
      validateField($(this));
    });
  });

  // Add button click handler
  $('#tracking_number_save_button').on('click', function (e) {
    e.preventDefault();

    // Get the order ID and tracking number
    let order_id = window.wcv_admin_order_tracking.order_id;
    let vendor_id = $('#wcv_tracking_vendor_id').val();
    let nonce = $('#wcv_add_tracking_number_nonce').val();

    let shipping_provider = $('#_wcv_shipping_provider_' + order_id).val();
    let tracking_number = $('#_wcv_tracking_number_' + order_id).val();
    let date_shipped = $('#_wcv_date_shipped_' + order_id).val();

    if (validateFields() == false) {
      return false;
    }

    const requestData = {
      action: 'add_order_vendor_tracking',
      _wcv_order_id: order_id,
      wcv_add_tracking_number_nonce: nonce,
      shipping_provider: shipping_provider,
      vendor_id: vendor_id,
      tracking_number: tracking_number,
      date_shipped: date_shipped,
    };

    let loadingText = window.wcv_admin_order_tracking.loading_message;
    let addButtonLabel = window.wcv_admin_order_tracking.default_button_label;

    let genericErrorMessage = window.wcv_admin_order_tracking.error_message;

    $(this).val(`${loadingText}`);

    // Send the AJAX request
    $.ajax({
      url: window.wcv_admin_order_tracking.ajax_url,
      type: 'POST',
      dataType: 'json',
      data: requestData,
      success: function (response) {
        if (response.success) {
          // Reload the page
          wcvShowNotice(response.data.message);
          $(this).val(`${addButtonLabel}`);
          setTimeout(function () {
            window.location.reload();
          }, 3000);
          return;
        } else {
          $('#wcv_add_tracking_number_nonce').val(response.data.nonce);
          $(this).val(`${addButtonLabel}`);
          alert(response.data.message);
          return;
        }
      },
      error: function (error) {
        $('#wcv_add_tracking_number_nonce').val(response.data.nonce);
        $(this).val(`${addButtonLabel}`);
        alert(genericErrorMessage);
        return;
      },
    });
  });

  function wcvShowNotice(message, type = 'success') {
    $(
      `<div class="notice notice-${type} is-dismissible">
				<p>${message}</p>
			</div>`
    ).insertAfter('.wp-header-end');
  }

  function validateFields() {
    let allValid = true;
    formFields.each(function () {
      const isFieldValid = validateField($(this));
      if (!isFieldValid) allValid = false;
    });

    return allValid;
  }

  function validateField(field) {
    let isValid = true;
    let fieldId = field.attr('id');
    let fieldValue = field.val();

    const errorMessage = window.wcv_admin_order_tracking.field_required_message;

    if (fieldValue == '') {
      isValid = false;
      field.addClass('error');
      $('#' + fieldId + '_error').remove();
      field.parent().append(
        `<span id="${fieldId}_error" class="error-message">
				${errorMessage}
				</span>`
      );
    } else {
      field.removeClass('error');
      $('#' + fieldId + '_error').remove();
    }

    return isValid;
  }
});
