/* A1-WooBay - eBay Orders page (Pro)
 * Handles: "Check for New Sales" order import trigger + modal feedback.
 */
(function($){
	function openOrderModal(title) {
		$('#a1wb-order-modal-title').text(title);
		$('#a1wb-order-modal-body').html('<span style="color:#888;">Contacting eBay Fulfillment API…</span>');
		$('#a1wb-order-modal-close').prop('disabled', true);
		$('#a1wb-order-modal').css('display', 'flex');
	}

	$('#a1wb-check-sales-orders-btn').on('click', function(){
		openOrderModal(a1wbOrders.checkingText);

		$.post(ajaxurl, {
			action: 'a1woobay_import_orders',
			nonce:  a1wbOrders.importOrdersNonce
		}, function(r){
			if (r.success) {
				var res = r.data.result, html = '';
				$('#a1wb-order-modal-title').text('Import Complete');
				if (res.created > 0) html += '<div style="color:#2a9d2a;margin-bottom:6px;">✓ ' + res.created + ' new order(s) imported.</div>';
				if (res.skipped > 0) html += '<div style="color:#888;margin-bottom:6px;">→ ' + res.skipped + ' already imported, skipped.</div>';
				if (res.errors  > 0) html += '<div style="color:#dc3232;margin-bottom:6px;">✗ ' + res.errors + ' error(s).</div>';
				if (res.total === 0 && res.errors === 0) html += '<div style="color:#888;">No new eBay orders found.</div>';
				if (res.created > 0) html += '<div style="margin-top:10px;"><a href="" style="text-decoration:none;">↻ Reload page to see new orders</a></div>';
				$('#a1wb-order-modal-body').html(html);
			} else {
				$('#a1wb-order-modal-title').text('Import Failed');
				$('#a1wb-order-modal-body').html('<div style="color:#dc3232;">' + (r.data || 'Unknown error') + '</div>');
			}
			$('#a1wb-order-modal-close').prop('disabled', false);
		}).fail(function(){
			$('#a1wb-order-modal-title').text('Request Failed');
			$('#a1wb-order-modal-body').html('<div style="color:#dc3232;">Could not reach the server. Please try again.</div>');
			$('#a1wb-order-modal-close').prop('disabled', false);
		});
	});

	$('#a1wb-order-modal-close').on('click', function(){
		$('#a1wb-order-modal').hide();
	});
}(jQuery));
