/**
 * Sync settings script.
 *
 * @package flo-sync
 */

jQuery( document ).ready(
	function ( $ ) {
		const selector_prefix = northmill_sync_admin_settings.settings_id;

		let $sync_settings = {
			selectors: {
				other: {
					only_sync_stock: $( '#' + selector_prefix + '_sync_only_product_stock_amount' ),
					sync_prod_publish_status: $( '#' + selector_prefix + '_sync_products_publish_status' ),
					sync_prod_price: $( '#' + selector_prefix + '_sync_price' ),
					sync_prod_display_order: $( '#' + selector_prefix + '_sync_article_display_order' ),
					sync_prod_title: $( '#' + selector_prefix + '_sync_product_title' ),
					sync_prod_description: $( '#' + selector_prefix + '_sync_product_description' ),
					sync_prod_images: $( '#' + selector_prefix + '_sync_pictures' ),
					sync_prod_tax_class: $( '#' + selector_prefix + '_sync_product_tax_class' ),
				},
			}
		};

		toggle_article_sync_fields();
		$sync_settings.selectors.other.only_sync_stock.on( 'change', toggle_article_sync_fields );

		function toggle_article_sync_fields() {
			if ( $sync_settings.selectors.other.only_sync_stock.is( ':checked' ) ) {
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_publish_status );
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_price );
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_display_order );
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_title );
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_description );
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_images );
				disable_article_sync_field( $sync_settings.selectors.other.sync_prod_tax_class );
			} else {
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_publish_status );
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_price );
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_display_order );
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_title );
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_description );
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_images );
				enable_article_sync_field( $sync_settings.selectors.other.sync_prod_tax_class );
			}
		}

		function disable_article_sync_field( $field ) {
			$field.prop( 'disabled', true );
			$field.data( 'was-checked', $field.is( ':checked' ) );
			$field.prop( 'checked', false );
		}

		function enable_article_sync_field( $field ) {
			$field.prop( 'disabled', false );
			if ( $field.data( 'was-checked' ) ) {
				$field.prop( 'checked', true );
			}
		}
	}
);
