/**
 * Script for syncing in WP-admin.
 *
 * @package flo-sync
 */

/* global mf_sync_script_vars */
jQuery( document ).ready(
	function (jQuery) {

		jQuery( '#publish, .save-variation-changes' ).on(
			'click',
			function () {

				if ( 'product' === jQuery( '#post_type' ).val() ) {
					const $title = jQuery( '#title' ).val();

					const title = jQuery.trim( $title );

					if ( '' === title ) {
						alert( mf_sync_script_vars.title_required );
						$title.focus();
						return false;
					}

					const $regular_price = jQuery( '#_regular_price' );

					const regular_price = jQuery.trim( $regular_price.val() );
					const product_type  = jQuery( '#product-type' ).val();

					// Todo: Validate bookable product.
					// Todo: Validate the quick edit.
					if (
						( 'booking' !== product_type && 'variable' !== product_type ) &&
						( '' === regular_price || 0 === regular_price )
					) {
						alert( mf_sync_script_vars.regular_price_required );

						jQuery( '.general_tab > a' ).click();
						$regular_price.focus();
						return false;
					}

					const $sku = jQuery( '#_sku' );

					const sku = jQuery.trim( $sku.val() );

					if ('variable' !== product_type && ('' === sku || 0 === sku)  ) {
						alert( mf_sync_script_vars.sku_required );

						jQuery( '.inventory_tab > a' ).click();
						$sku.focus();
						return false;
					}

					if ('variable' === product_type) {

						let valid = true;

						const variants_sku = jQuery( "input[name*='variable_sku']" );
						if ( variants_sku.length ) {
							variants_sku.each(
								function () {
									if ( jQuery.trim( jQuery( this ).val() ) === '' ) {
										valid = false;
									}
								}
							);
						}

						const variants_price = jQuery( "input[name*='variable_regular_price']" );
						if ( variants_price.length ) {
							variants_price.each(
								function () {
									if ( jQuery.trim( jQuery( this ).val() ) === '' ) {
										valid = false;
									}
								}
							);
						}

						if ( ! valid) {
							alert( mf_sync_script_vars.variants_sku_price_required );
							jQuery( '.variations_tab > a' ).click();
						}

						return valid;
					}
				}
			}
		);
	}
);
