jQuery( function( $ ) {
	
	var url;
	
	$( '#doaction, #doaction2' ).on( 'click', function ( event ) {
		var actionselected = $( this ).attr( 'id' ).substr( 2 );
		var action         = $( 'select[name="' + actionselected + '"]' ).val();

		if ( action.startsWith( 'wpo_wcpdf_cloud_service_export_' ) ) {
			event.preventDefault();
			var checked = [];
			$( 'tbody th.check-column input[type="checkbox"]:checked' ).each(
				function() {
					checked.push( $( this ).val() );
				}
			);

			if ( ! checked.length ) {
				alert( wcpdf_pro_cloud_storage_export.select_orders );
				return;
			}

			var order_ids = checked.join( 'x' );

			var url_base  = 'edit.php?post_type=shop_order&action=' + action + '&order_ids=';
			var url_args  = '&TB_iframe=true&height=200&width=300';

			// XML Credit Notes need refund IDs instead of parent order IDs
			if ( action.indexOf( 'credit-note_xml' ) != -1 ) {
				$.ajax( {
					url:      wcpdf_pro_cloud_storage_export.ajaxurl,
					type:     'POST',
					dataType: 'json',
					data: {
						action:    'wpo_ips_get_refund_order_ids', // hook from the free plugin
						order_ids: checked,
						security:  wcpdf_pro_cloud_storage_export.nonce
					},
					success: function( response ) {
						if ( response && response.success && response.data && response.data.refund_ids && response.data.refund_ids.length ) {
							order_ids = response.data.refund_ids.join( 'x' );

							url = url_base + order_ids + url_args;

							// disable background scrolling
							$( 'body' ).css( { overflow: 'hidden' } );

							tb_show( '', url );
						} else {
							var msg = ( response && response.data && response.data.message ) ? response.data.message : wcpdf_pro_cloud_storage_export.error_no_refunds_found;
							alert( msg );
						}
					},
					error: function() {
						alert( wcpdf_pro_cloud_storage_export.error_fetching_refund_ids );
					}
				} );

				return;
			}

			url = url_base + order_ids + url_args;

			// disable background scrolling
			$( 'body' ).css( { overflow: 'hidden' } );

			tb_show( '', url );
		}
	} );

	$( window ).on( 'tb_unload', function() {
		// re-enable scrolling after closing thickbox
		// (not really needed since page is reloaded in the next step, but applied anyway)
		$( 'body' ).css( { overflow: 'inherit' } );

		// reload page
		// window.location.reload()
	} );
	
	// Handle XML Credit Note from the Order List actions
	$( document ).on( 'click', 'a.wpo_wcpdf.credit-note.xml', function( event ) {
		event.preventDefault();

		var $link = $( this );
		var href  = $link.attr( 'href' );

		// Example:
		// ...admin-ajax.php?action=generate_wpo_wcpdf&document_type=credit-note&order_ids=2253&access_key=...&output=xml

		var parts = href.split( '&order_ids=' );

		// Fallback to default behaviour if we cannot parse order_ids
		if ( parts.length < 2 ) {
			window.open( href, '_blank' );
			return;
		}

		var prefix  = parts[0]; // everything before &order_ids=
		var rest    = parts[1]; // "2253&access_key=...&output=xml"
		var suffix  = '';
		var amp_pos = rest.indexOf( '&' );

		if ( amp_pos !== -1 ) {
			suffix = rest.substring( amp_pos );    // "&access_key=...&output=xml"
			rest   = rest.substring( 0, amp_pos ); // "2253"
		}

		// Single parent order ID
		var parent_order_id = rest;

		// AJAX: resolve refund IDs from parent order ID
		$.ajax( {
			url:      wcpdf_pro_cloud_storage_export.ajaxurl,
			type:     'POST',
			dataType: 'json',
			data: {
				action:    'wpo_ips_get_refund_order_ids', // hook from the free plugin
				order_ids: [ parent_order_id ],
				security:  wcpdf_pro_cloud_storage_export.nonce
			},
			success: function( response ) {
				if ( response && response.success && response.data && response.data.refund_ids && response.data.refund_ids.length ) {

					// Open one XML per refund ID
					$.each( response.data.refund_ids, function( i, refund_id ) {
						if ( ! refund_id ) {
							return;
						}
						var url = prefix + '&order_ids=' + refund_id + suffix;
						window.open( url, '_blank' );
					} );
				} else {
					var msg = ( response && response.data && response.data.message ) ? response.data.message : wcpdf_pro_cloud_storage_export.error_no_refunds_found;
					alert( msg );
				}
			},
			error: function() {
				alert( wcpdf_pro_cloud_storage_export.error_fetching_refund_ids );
			}
		} );
	} );
	
} );
