/* global wawp_orders_list, jQuery */
jQuery( document ).ready(
	function ($) {
		$( document ).on(
			'click',
			'.wawp-resend-notif-btn',
			function (e) {
				e.preventDefault();
				e.stopPropagation();

				var $btn     = $( this );
				var orderId  = $btn.data( 'order-id' );
				var status   = $btn.data( 'order-status' );
				var $spinner = $btn.find( '.wawp-spinner' );
				var $icon    = $btn.find( '.wawp-btn-icon' );

				if ($btn.hasClass( 'wawp-loading' )) {
					return;
				}

				$btn.addClass( 'wawp-loading' ).attr( 'disabled', true );
				$icon.hide();
				$spinner.show();

				$.ajax(
					{
						url: wawp_orders_list.ajax_url,
						type: 'POST',
						data: {
							action: 'wawp_resend_order_notification',
							nonce: wawp_orders_list.nonce,
							order_id: orderId,
							status: status
						},
						success: function (response) {
							if (response.success) {
								$btn.addClass( 'wawp-sent' );
								$btn.attr( 'title', wawp_orders_list.sent );
								setTimeout(
									function () {
										$btn.removeClass( 'wawp-sent' );
									},
									3000
								);
							} else {
								$btn.addClass( 'wawp-error' );
								setTimeout(
									function () {
										$btn.removeClass( 'wawp-error' );
									},
									3000
								);
							}
						},
						error: function () {
							$btn.addClass( 'wawp-error' );
							setTimeout(
								function () {
									$btn.removeClass( 'wawp-error' );
								},
								3000
							);
						},
						complete: function () {
							$btn.removeClass( 'wawp-loading' ).removeAttr( 'disabled' );
							$icon.show();
							$spinner.hide();
						}
					}
				);
			}
		);
	}
);
