jQuery( document ).ready( function() {

	var newOption = jQuery( '<option selected=\'selected\'></option>' )
		.val( elexMvProductVendorParams.store_id )
		.text( elexMvProductVendorParams.store_name );

	function displayCommission( vendorId ) {
		jQuery.ajax( {
			url: elex_mv_coupon_ajaxurl_object.ajax_url,
			type: 'GET',
			data: {
				action:    'elex_mv_update_product_commission',
				nonce:     elex_mv_coupon_ajaxurl_object.nonce,
				vendor_id: vendorId,
			},
			success: function( response ) {
				var commission = response.data;
				jQuery( '#commission_to_admin' ).val( commission );
			},
			error: function( xhr, status, error ) {
				console.error( 'Error fetching commission: ' + error );
			},
		} );
	}

	jQuery( '#elex_vendor_name' ).append( newOption ).trigger( 'change' );

	jQuery( '#elex_vendor_name' ).select2( {
		placeholder:        'Search Vendor',
		dataType:           'json',
		minimumInputLength: 2,
		ajax: {
			url:  elex_mv_coupon_ajaxurl_object.ajax_url,
			type: 'GET',
			data: function( params ) {
				return {
					vendor_search: params.term.replace( /\s+/g, ' ' ).trim(),
					action:        'elex_mv_api_endpoint_for_vendors',
					nonce:         elex_mv_coupon_ajaxurl_object.nonce,
				};
			},
			processResults: function( response ) {
				return {
					results: response.data.map( function( store ) {
						return {
							text: store.post_title,
							id:   store.ID,
						};
					} ),
				};
			},
		},
	} );

	jQuery( '#elex_vendor_name' ).on( 'change', function() {
		var selectedVendorId = jQuery( this ).val();
		displayCommission( selectedVendorId );
	} );

} );
