/* global jQuery, devikit_ifirma_admin_nip */
/**
 * Admin order edit – NIP field helper for ifirma integration.
 */
( function ( $ ) {
	'use strict';

	var config = window.devikit_ifirma_admin_nip || {};

	function setNip( nip ) {
		var $input = $( '#_billing_nip, #billing_nip' );
		if ( $input.length ) {
			$input.val( nip ).trigger( 'change' );
		}
	}

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

		$.post(
			config.ajax_url,
			{
				action: 'devikit_ifirma_get_customer_nip',
				user_id: userId,
				nonce: config.nonce,
			},
			function ( response ) {
				if ( response && response.success ) {
					setNip( response.data.nip || '' );
				}
			}
		);
	}

	$( document ).on( 'change', '#customer_user', function () {
		var userId = parseInt( $( this ).val(), 10 );
		if ( userId > 0 ) {
			setTimeout( function () {
				var current = $.trim( $( '#_billing_nip, #billing_nip' ).first().val() );
				if ( ! current ) {
					fetchAndSetNip( userId );
				}
			}, 400 );
		} else {
			setNip( '' );
		}
	} );

	$( function () {
		$( 'a.load_customer_billing' ).on( 'click', function () {
			var userId = parseInt( $( '#customer_user' ).val(), 10 );
			if ( userId > 0 ) {
				setTimeout( function () {
					fetchAndSetNip( 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 && response.billing.nip ) {
				setNip( response.billing.nip );
			}
		} catch ( _e ) {
			// Not valid JSON.
		}
	} );
}( jQuery ) );
