/* global jQuery, devikit_sellsy_admin_fields */
/**
 * Admin order edit - SIRET and VAT field helper for Sellsy integration.
 */
( function ( $ ) {
	'use strict';

	var config = window.devikit_sellsy_admin_fields || {};

	function setFields( siret, vat ) {
		if ( siret !== undefined ) {
			$( '#_billing_siret, #billing_siret' ).val( siret ).trigger( 'change' );
		}
		if ( vat !== undefined ) {
			$( '#_billing_vat_id, #billing_vat_id' ).val( vat ).trigger( 'change' );
		}
	}

	function fetchAndSetFields( userId ) {
		if ( ! userId || ! config.ajax_url || ! config.nonce ) {
			return;
		}

		$.post(
			config.ajax_url,
			{
				action: 'devikit_sellsy_get_customer_fields',
				user_id: userId,
				nonce: config.nonce,
			},
			function ( response ) {
				if ( response && response.success ) {
					setFields( response.data.siret || '', response.data.vat_id || '' );
				}
			}
		);
	}

	$( document ).on( 'change', '#customer_user', function () {
		var userId = parseInt( $( this ).val(), 10 );
		if ( userId > 0 ) {
			setTimeout( function () {
				var siret = $.trim( $( '#_billing_siret, #billing_siret' ).first().val() );
				if ( ! siret ) {
					fetchAndSetFields( userId );
				}
			}, 400 );
		} else {
			setFields( '', '' );
		}
	} );

	$( function () {
		$( 'a.load_customer_billing' ).on( 'click', function () {
			var userId = parseInt( $( '#customer_user' ).val(), 10 );
			if ( userId > 0 ) {
				setTimeout( function () {
					fetchAndSetFields( userId );
				}, 700 );
			}
		} );
	} );

	$( document ).on( 'ajaxSuccess', function ( _event, xhr, settings ) {
		var isCustomerCall = false;

		if ( typeof settings.data === 'string' ) {
			isCustomerCall =
				settings.data.indexOf( 'action=woocommerce_get_customer_details' ) !== -1;
		} else if ( settings.data && typeof settings.data === 'object' ) {
			isCustomerCall =
				settings.data.action === 'woocommerce_get_customer_details';
		}

		if ( ! isCustomerCall ) {
			return;
		}

		try {
			var response = JSON.parse( xhr.responseText );
			if ( response && response.billing ) {
				if ( response.billing.siret ) {
					$( '#_billing_siret, #billing_siret' ).val( response.billing.siret );
				}
				if ( response.billing.vat_id ) {
					$( '#_billing_vat_id, #billing_vat_id' ).val( response.billing.vat_id );
				}
			}
		} catch ( _e ) {
			// Not valid JSON.
		}
	} );
}( jQuery ) );
