/**
 * ConvesioPay Admin: Fetch payment status button on edit order.
 */
(function($) {
	'use strict';

	function peachpayConvesiopayShowNotice(message, type) {
		$('.peachpay-convesiopay-fetch-status-notice').remove();
		var noticeClass = type === 'success' ? 'notice notice-success' : 'notice notice-error';
		var html = '<div class="peachpay-convesiopay-fetch-status-notice ' + noticeClass + ' is-dismissible" style="margin: 10px 0;">' +
			'<p><strong>' + (message || '') + '</strong></p>' +
			'<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>';
		var $anchor = $('.peachpay-convesiopay-fetch-status-btn').length ? $('.peachpay-convesiopay-fetch-status-btn') : $('.peachpay-convesiopay-fetch-status-loading');
		$anchor.after(html);
		$('.peachpay-convesiopay-fetch-status-notice .notice-dismiss').on('click', function() {
			$(this).closest('.peachpay-convesiopay-fetch-status-notice').fadeOut();
		});
		if (type === 'success') {
			setTimeout(function() {
				$('.peachpay-convesiopay-fetch-status-notice').fadeOut();
			}, 5000);
		}
	}

	$(function() {
		$(document).on('click', '.peachpay-convesiopay-fetch-status-btn', function(e) {
			e.preventDefault();
			e.stopPropagation();

			var $btn = $(this);
			var $loading = $('.peachpay-convesiopay-fetch-status-loading');
			var orderId = $btn.data('order-id');

			if (typeof peachpayConvesiopayFetchStatusManually === 'undefined') {
				peachpayConvesiopayShowNotice('Fetch payment status: script configuration missing.', 'error');
				return;
			}
			if (!orderId) {
				peachpayConvesiopayShowNotice('Fetch payment status: order ID missing.', 'error');
				return;
			}

			$btn.prop('disabled', true);
			$loading.show();

			$.ajax({
				url: peachpayConvesiopayFetchStatusManually.ajaxUrl,
				type: 'POST',
				data: {
					action: 'peachpay_convesiopay_fetch_payment_status',
					nonce: peachpayConvesiopayFetchStatusManually.nonce,
					order_id: orderId
				},
				success: function(response) {
					if (response.success) {
						var msg = (response.data && response.data.message) ? response.data.message : 'Payment status fetched.';
						peachpayConvesiopayShowNotice(msg, 'success');
						if (response.data && response.data.updated) {
							setTimeout(function() {
								location.reload();
							}, 2000);
						}
					} else {
						var errMsg = (response.data && response.data.message) ? response.data.message : 'Failed to fetch payment status.';
						peachpayConvesiopayShowNotice(errMsg, 'error');
						$btn.prop('disabled', false);
					}
				},
				error: function(xhr, status, err) {
					console.error('PeachPay ConvesioPay fetch status:', err);
					peachpayConvesiopayShowNotice('Network error while fetching payment status.', 'error');
					$btn.prop('disabled', false);
				},
				complete: function() {
					$loading.hide();
				}
			});
		});
	});
})(jQuery);
