/**
 * Plugin Name:  Peptio – Warehouse Routing & Dispatch
 * Description:  Unified Mi0ps dispatch queue for all WooCommerce orders, with HQ/Europe labels, filters, routing health and Order Locator integration.
 * Version:      1.1.0
 * Author:       Peptio
 *
 * CODE SNIPPETS VERSION:
 * Paste into a PHP snippet without adding <?php.
 * Set the snippet to run everywhere.
 *
 * IMPORTANT:
 * - This module DOES NOT route, deduct or restore stock.
 * - Peptio – Frontend Warehouse Stock Routing handles storefront routing
 *   and warehouse-specific stock movements.
 * - This module only reads the saved fulfilment warehouse and displays
 *   every order in one unified dispatch queue.
 */

if (!defined('ABSPATH')) {
	exit;
}

if (defined('PEPTI_MW_ROUTING_DISPATCH_LOADED')) {
	return;
}

define('PEPTI_MW_ROUTING_DISPATCH_LOADED', true);
define('PEPTI_MWRD_VERSION', '1.1.0');
define('PEPTI_MWRD_NONCE_ACTION', 'pepti_mwrd_nonce_action');
define('PEPTI_MWRD_PER_PAGE', 50);
define('PEPTI_MWRD_HEALTH_CACHE_KEY', 'pepti_mwrd_dispatch_health_v110');

define('PEPTI_MWRD_META_WAREHOUSE', '_pepti_fulfilment_warehouse');
define('PEPTI_MWRD_META_WAREHOUSE_NAME', '_pepti_fulfilment_warehouse_name');
define('PEPTI_MWRD_META_COUNTRY', '_pepti_routing_country');
define('PEPTI_MWRD_META_FALLBACK', '_pepti_warehouse_fallback_used');
define('PEPTI_MWRD_META_ERROR', '_pepti_warehouse_routing_error');
define('PEPTI_MWRD_META_DEDUCTED', '_pepti_warehouse_stock_deducted');

/* ==========================================================================
 * CORE / ACCESS
 * ========================================================================== */

function pepti_mwrd_core_available() {
	return function_exists('pepti_mw_get_settings')
		&& function_exists('pepti_mw_get_warehouses');
}

function pepti_mwrd_is_enabled() {
	return pepti_mwrd_core_available()
		&& function_exists('pepti_mw_is_enabled')
		&& pepti_mw_is_enabled();
}

function pepti_mwrd_user_can_view_dispatch() {
	if (!is_user_logged_in()) {
		return false;
	}

	if (
		current_user_can('manage_options')
		|| current_user_can('manage_woocommerce')
		|| current_user_can('edit_shop_orders')
	) {
		return true;
	}

	if (function_exists('pepti_mws_user_can')) {
		return pepti_mws_user_can('view_dispatch');
	}

	return false;
}

function pepti_mwrd_authorise() {
	if (!pepti_mwrd_user_can_view_dispatch()) {
		wp_send_json_error(
			['message' => 'Permission denied.'],
			403
		);
	}

	check_ajax_referer(
		PEPTI_MWRD_NONCE_ACTION,
		'nonce'
	);
}

/* ==========================================================================
 * ORDER HELPERS
 * ========================================================================== */

function pepti_mwrd_normalise_country($country) {
	$country = strtoupper(
		sanitize_text_field((string) $country)
	);

	return preg_match('/^[A-Z]{2}$/', $country)
		? $country
		: '';
}

function pepti_mwrd_order_country($order) {
	if (!$order instanceof WC_Order) {
		return '';
	}

	$country = pepti_mwrd_normalise_country(
		$order->get_shipping_country()
	);

	if ($country !== '') {
		return $country;
	}

	return pepti_mwrd_normalise_country(
		$order->get_billing_country()
	);
}

function pepti_mwrd_warehouse_name($warehouse) {
	$warehouse = sanitize_key($warehouse);

	if (pepti_mwrd_core_available()) {
		$warehouses = pepti_mw_get_warehouses();

		if (
			is_array($warehouses)
			&& !empty($warehouses[$warehouse]['name'])
		) {
			return sanitize_text_field(
				$warehouses[$warehouse]['name']
			);
		}
	}

	if ($warehouse === 'eu') {
		return 'Europe Warehouse';
	}

	if ($warehouse === 'hq') {
		return 'HQ Warehouse';
	}

	return 'Unassigned';
}

function pepti_mwrd_order_edit_url($order) {
	if (!$order instanceof WC_Order) {
		return '';
	}

	if (method_exists($order, 'get_edit_order_url')) {
		return (string) $order->get_edit_order_url();
	}

	return admin_url(
		'post.php?post='
		. $order->get_id()
		. '&action=edit'
	);
}

function pepti_mwrd_order_items_summary($order) {
	if (!$order instanceof WC_Order) {
		return '';
	}

	$parts = [];

	foreach ($order->get_items('line_item') as $item) {
		if (!$item instanceof WC_Order_Item_Product) {
			continue;
		}

		$name = $item->get_name();
		$quantity = (float) $item->get_quantity();

		$product = $item->get_product();

		if ($product instanceof WC_Product) {
			$sku = $product->get_sku();

			if ($sku !== '') {
				$name .= ' — ' . $sku;
			}
		}

		$parts[] = $name . ' × ' . wc_format_decimal($quantity, 2);
	}

	return implode(' | ', $parts);
}

function pepti_mwrd_get_tracking_details($order) {
	$tracking_keys = [
		'_tracking_number',
		'_dhl_tracking_number',
		'_royal_mail_tracking_number',
		'_wc_shipment_tracking_items',
	];

	$tracking = '';

	foreach ($tracking_keys as $key) {
		$value = $order->get_meta($key, true);

		if (is_string($value) && trim($value) !== '') {
			$tracking = trim($value);
			break;
		}

		if (is_array($value) && $value) {
			$first = reset($value);

			if (is_array($first)) {
				$tracking = sanitize_text_field(
					$first['tracking_number']
						?? $first['tracking_id']
						?? ''
				);
			}

			if ($tracking !== '') {
				break;
			}
		}
	}

	$courier_keys = [
		'_tracking_provider',
		'_custom_tracking_provider',
		'_dhl_service',
		'_royal_mail_service',
	];

	$courier = '';

	foreach ($courier_keys as $key) {
		$value = $order->get_meta($key, true);

		if (is_string($value) && trim($value) !== '') {
			$courier = trim($value);
			break;
		}
	}

	return [
		'courier'  => $courier,
		'tracking' => $tracking,
	];
}

function pepti_mwrd_order_payload($order) {
	if (!$order instanceof WC_Order) {
		return [];
	}

	$warehouse = sanitize_key(
		$order->get_meta(
			PEPTI_MWRD_META_WAREHOUSE,
			true
		)
	);

	$warehouse_name = trim(
		(string) $order->get_meta(
			PEPTI_MWRD_META_WAREHOUSE_NAME,
			true
		)
	);

	if ($warehouse_name === '') {
		$warehouse_name = pepti_mwrd_warehouse_name(
			$warehouse
		);
	}

	$country = pepti_mwrd_order_country($order);
	$created = $order->get_date_created();
	$tracking = pepti_mwrd_get_tracking_details($order);

	$customer = trim(
		$order->get_formatted_billing_full_name()
	);

	if ($customer === '') {
		$customer = trim(
			$order->get_formatted_shipping_full_name()
		);
	}

	if ($customer === '') {
		$customer = 'Guest';
	}

	$error = trim(
		(string) $order->get_meta(
			PEPTI_MWRD_META_ERROR,
			true
		)
	);

	$fallback = $order->get_meta(
		PEPTI_MWRD_META_FALLBACK,
		true
	) === 'yes';

	$deducted = $order->get_meta(
		PEPTI_MWRD_META_DEDUCTED,
		true
	) === 'yes';

	$stock_state = 'WooCommerce stock';

	if ($warehouse === 'eu') {
		$stock_state = $deducted
			? 'EU stock deducted'
			: 'Awaiting EU deduction';
	} elseif ($warehouse === '') {
		$stock_state = 'Unassigned';
	}

	return [
		'id'             => $order->get_id(),
		'number'         => (string) $order->get_order_number(),
		'date'           => $created
			? $created->date_i18n('d M Y H:i')
			: '',
		'customer'       => $customer,
		'country'        => $country,
		'warehouse'      => $warehouse,
		'warehouse_name' => $warehouse_name,
		'status'         => $order->get_status(),
		'status_name'    => wc_get_order_status_name(
			$order->get_status()
		),
		'fallback'       => $fallback,
		'error'          => $error,
		'has_error'      => $error !== '',
		'unassigned'     => !in_array(
			$warehouse,
			['hq', 'eu'],
			true
		),
		'stock_state'    => $stock_state,
		'items'          => pepti_mwrd_order_items_summary($order),
		'courier'        => $tracking['courier'],
		'tracking'       => $tracking['tracking'],
		'total_html'     => wp_kses_post(
			$order->get_formatted_order_total()
		),
		'edit_url'       => pepti_mwrd_order_edit_url($order),
	];
}

/* ==========================================================================
 * ORDER QUERY
 * ========================================================================== */

function pepti_mwrd_all_order_statuses() {
	$statuses = array_keys(
		wc_get_order_statuses()
	);

	return array_map(
		static function($status) {
			return str_replace('wc-', '', $status);
		},
		$statuses
	);
}

add_action(
	'wp_ajax_pepti_mwrd_dispatch_page',
	function() {
		pepti_mwrd_authorise();

		if (!function_exists('wc_get_orders')) {
			wp_send_json_error([
				'message' => 'WooCommerce order querying is unavailable.',
			]);
		}

		$page = max(
			1,
			absint($_POST['page'] ?? 1)
		);

		$search = sanitize_text_field(
			wp_unslash($_POST['search'] ?? '')
		);

		$warehouse = sanitize_key(
			$_POST['warehouse'] ?? ''
		);

		$status = sanitize_key(
			$_POST['status'] ?? ''
		);

		$country = strtoupper(
			sanitize_text_field(
				wp_unslash($_POST['country'] ?? '')
			)
		);

		$args = [
			'limit'    => PEPTI_MWRD_PER_PAGE,
			'paged'    => $page,
			'paginate' => true,
			'orderby'  => 'date',
			'order'    => 'DESC',
			'return'   => 'objects',
			'status'   => $status !== ''
				? [$status]
				: pepti_mwrd_all_order_statuses(),
		];

		if ($search !== '') {
			if (ctype_digit($search)) {
				$args['include'] = [absint($search)];
			} else {
				$args['search'] = '*' . $search . '*';
			}
		}

		if ($country !== '') {
			$args['billing_country'] = $country;
		}

		if ($warehouse === 'hq' || $warehouse === 'eu') {
			$args['meta_query'] = [
				[
					'key'     => PEPTI_MWRD_META_WAREHOUSE,
					'value'   => $warehouse,
					'compare' => '=',
				],
			];
		} elseif ($warehouse === 'unassigned') {
			$args['meta_query'] = [
				'relation' => 'OR',
				[
					'key'     => PEPTI_MWRD_META_WAREHOUSE,
					'compare' => 'NOT EXISTS',
				],
				[
					'key'     => PEPTI_MWRD_META_WAREHOUSE,
					'value'   => '',
					'compare' => '=',
				],
			];
		} elseif ($warehouse === 'fallback') {
			$args['meta_query'] = [
				[
					'key'     => PEPTI_MWRD_META_FALLBACK,
					'value'   => 'yes',
					'compare' => '=',
				],
			];
		} elseif ($warehouse === 'error') {
			$args['meta_query'] = [
				[
					'key'     => PEPTI_MWRD_META_ERROR,
					'value'   => '',
					'compare' => '!=',
				],
			];
		}

		try {
			$results = wc_get_orders($args);

			$orders = is_object($results)
				&& isset($results->orders)
				&& is_array($results->orders)
					? $results->orders
					: [];

			$total = is_object($results)
				&& isset($results->total)
					? absint($results->total)
					: count($orders);

			$max_pages = is_object($results)
				&& isset($results->max_num_pages)
					? max(1, absint($results->max_num_pages))
					: 1;

			$rows = [];

			foreach ($orders as $order) {
				if ($order instanceof WC_Order) {
					$rows[] = pepti_mwrd_order_payload($order);
				}
			}

			wp_send_json_success([
				'rows'      => $rows,
				'page'      => $page,
				'per_page'  => PEPTI_MWRD_PER_PAGE,
				'total'     => $total,
				'max_pages' => $max_pages,
			]);
		} catch (Throwable $error) {
			wp_send_json_error(
				[
					'message' =>
						'Dispatch orders could not be loaded: '
						. $error->getMessage(),
				],
				500
			);
		}
	}
);

/* ==========================================================================
 * HEALTH COUNTS
 * ========================================================================== */

function pepti_mwrd_clear_health_cache() {
	delete_transient(
		PEPTI_MWRD_HEALTH_CACHE_KEY
	);
}

add_action(
	'woocommerce_update_order',
	'pepti_mwrd_clear_health_cache',
	30
);

add_action(
	'woocommerce_order_status_changed',
	'pepti_mwrd_clear_health_cache',
	30
);

function pepti_mwrd_count_meta($key, $value = '', $compare = '=') {
	$args = [
		'limit'      => 1,
		'paged'      => 1,
		'paginate'   => true,
		'return'     => 'ids',
		'status'     => pepti_mwrd_all_order_statuses(),
		'meta_query' => [
			[
				'key'     => $key,
				'compare' => $compare,
			],
		],
	];

	if ($compare !== 'NOT EXISTS') {
		$args['meta_query'][0]['value'] = $value;
	}

	$results = wc_get_orders($args);

	return is_object($results)
		&& isset($results->total)
			? absint($results->total)
			: 0;
}

function pepti_mwrd_health_counts($force = false) {
	if (!$force) {
		$cached = get_transient(
			PEPTI_MWRD_HEALTH_CACHE_KEY
		);

		if (is_array($cached)) {
			return $cached;
		}
	}

	$counts = [
		'hq'         => 0,
		'eu'         => 0,
		'fallback'   => 0,
		'errors'     => 0,
		'unassigned' => 0,
		'all'        => 0,
	];

	if (!function_exists('wc_get_orders')) {
		return $counts;
	}

	try {
		$all = wc_get_orders([
			'limit'    => 1,
			'paged'    => 1,
			'paginate' => true,
			'return'   => 'ids',
			'status'   => pepti_mwrd_all_order_statuses(),
		]);

		$counts['all'] = is_object($all)
			&& isset($all->total)
				? absint($all->total)
				: 0;

		$counts['hq'] = pepti_mwrd_count_meta(
			PEPTI_MWRD_META_WAREHOUSE,
			'hq'
		);

		$counts['eu'] = pepti_mwrd_count_meta(
			PEPTI_MWRD_META_WAREHOUSE,
			'eu'
		);

		$counts['fallback'] = pepti_mwrd_count_meta(
			PEPTI_MWRD_META_FALLBACK,
			'yes'
		);

		$counts['errors'] = pepti_mwrd_count_meta(
			PEPTI_MWRD_META_ERROR,
			'',
			'!='
		);

		$counts['unassigned'] = max(
			0,
			$counts['all'] - $counts['hq'] - $counts['eu']
		);
	} catch (Throwable $error) {
		/* Keep zero values when the order data store rejects a query. */
	}

	set_transient(
		PEPTI_MWRD_HEALTH_CACHE_KEY,
		$counts,
		5 * MINUTE_IN_SECONDS
	);

	return $counts;
}

add_action(
	'wp_ajax_pepti_mwrd_routing_health',
	function() {
		pepti_mwrd_authorise();

		wp_send_json_success([
			'counts' => pepti_mwrd_health_counts(),
		]);
	}
);

/*
 * Do not run an order query while the workspace initially renders.
 */
add_filter(
	'pepti_mw_workspace_tab_badge_dispatch',
	function($badge) {
		return 0;
	},
	10,
	1
);

/* ==========================================================================
 * OVERVIEW HEALTH PANEL
 * ========================================================================== */

add_action(
	'pepti_mw_workspace_tab_overview',
	function($context) {
		if (!pepti_mwrd_user_can_view_dispatch()) {
			return;
		}

		$nonce = wp_create_nonce(
			PEPTI_MWRD_NONCE_ACTION
		);
		?>
		<div
			id="peptiMwrdRoutingHealth"
			style="margin-top:14px;border:1px solid var(--pepti-border,#e5e7eb);border-radius:14px;padding:14px;"
		>
			<h3 style="margin:0 0 12px;">
				🚦 Unified order queue
			</h3>

			<div
				class="pepti-mw-notice"
				id="peptiMwrdHealthLoading"
				style="margin:0;"
			>
				Order counts will load when the Overview tab is opened.
			</div>

			<div
				id="peptiMwrdHealthGrid"
				style="display:none;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px;"
			>
				<?php
				$health_cards = [
					'all'        => 'All orders',
					'hq'         => 'HQ assigned',
					'eu'         => 'Europe assigned',
					'unassigned' => 'Unassigned',
					'errors'     => 'Routing errors',
				];

				foreach ($health_cards as $key => $label):
					?>
					<div class="pepti-mw-summary">
						<div class="pepti-mw-summary-label">
							<?php echo esc_html($label); ?>
						</div>

						<div
							class="pepti-mw-summary-value"
							data-health-value="<?php echo esc_attr($key); ?>"
						>
							0
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		</div>

		<script>
		(function(){
			const wrapper = document.getElementById(
				'peptiMwrdRoutingHealth'
			);

			if (!wrapper) return;

			const ajaxUrl =
				<?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;

			const nonce =
				<?php echo wp_json_encode($nonce); ?>;

			let loaded = false;
			let loading = false;

			async function loadHealth(){
				if (loaded || loading) return;

				loading = true;

				const loadingBox =
					document.getElementById(
						'peptiMwrdHealthLoading'
					);

				if (loadingBox) {
					loadingBox.textContent =
						'Loading order counts…';
				}

				const body = new FormData();
				body.append(
					'action',
					'pepti_mwrd_routing_health'
				);
				body.append('nonce', nonce);

				try {
					const response = await fetch(
						ajaxUrl,
						{
							method:'POST',
							credentials:'same-origin',
							body
						}
					);

					const json = await response.json();

					if (!json.success) {
						throw new Error(
							json?.data?.message
							|| 'Order counts could not be loaded.'
						);
					}

					const counts =
						json.data?.counts || {};

					wrapper.querySelectorAll(
						'[data-health-value]'
					).forEach(element => {
						const key =
							element.dataset.healthValue;

						element.textContent =
							String(Number(counts[key] || 0));

						if (
							(key === 'errors'
							|| key === 'unassigned')
							&& Number(counts[key] || 0) > 0
						) {
							element.style.color = '#dc2626';
						}
					});

					const grid =
						document.getElementById(
							'peptiMwrdHealthGrid'
						);

					if (grid) {
						grid.style.display = 'grid';
					}

					if (loadingBox) {
						loadingBox.style.display = 'none';
					}

					loaded = true;
				} catch (error) {
					if (loadingBox) {
						loadingBox.textContent =
							error.message;
					}
				} finally {
					loading = false;
				}
			}

			document.addEventListener(
				'pepti:warehouse-panel-opened',
				event => {
					if (
						event.detail?.panel
						=== 'overview'
					) {
						loadHealth();
					}
				}
			);

			setTimeout(() => {
				const panel = wrapper.closest(
					'.pepti-mw-panel'
				);

				if (
					panel?.classList.contains('active')
				) {
					loadHealth();
				}
			}, 250);
		})();
		</script>
		<?php
	},
	20,
	1
);

/* ==========================================================================
 * UNIFIED DISPATCH TAB
 * ========================================================================== */

add_action(
	'pepti_mw_workspace_tab_dispatch',
	function($context) {
		if (!pepti_mwrd_user_can_view_dispatch()) {
			echo '<div class="pepti-mw-notice warning">You do not have permission to view the dispatch queue.</div>';
			return;
		}

		$nonce = wp_create_nonce(
			PEPTI_MWRD_NONCE_ACTION
		);
		?>
		<div id="peptiMwrdDispatchApp">
			<style>
				#peptiMwrdDispatchApp .mwrd-toolbar{
					display:flex;
					justify-content:space-between;
					align-items:flex-end;
					gap:10px;
					flex-wrap:wrap;
					margin-bottom:12px;
				}

				#peptiMwrdDispatchApp .mwrd-filters{
					display:grid;
					grid-template-columns:minmax(220px,1.5fr) repeat(3,minmax(140px,.7fr)) auto;
					gap:8px;
					flex:1 1 800px;
				}

				#peptiMwrdDispatchApp .mwrd-pager{
					display:flex;
					align-items:center;
					gap:8px;
					flex-wrap:wrap;
				}

				#peptiMwrdDispatchApp .mwrd-pill{
					display:inline-flex;
					align-items:center;
					padding:4px 8px;
					border-radius:999px;
					font-size:10px;
					font-weight:900;
					border:1px solid #e5e7eb;
					background:#f8fafc;
					white-space:nowrap;
				}

				#peptiMwrdDispatchApp .mwrd-pill.hq{
					color:#075985;
					background:#f0f9ff;
					border-color:#bae6fd;
				}

				#peptiMwrdDispatchApp .mwrd-pill.eu{
					color:#166534;
					background:#f0fdf4;
					border-color:#bbf7d0;
				}

				#peptiMwrdDispatchApp .mwrd-pill.warning{
					color:#9a3412;
					background:#fff7ed;
					border-color:#fed7aa;
				}

				#peptiMwrdDispatchApp .mwrd-pill.error{
					color:#991b1b;
					background:#fef2f2;
					border-color:#fecaca;
				}

				#peptiMwrdDispatchApp .mwrd-loading{
					padding:30px 16px;
					text-align:center;
					color:var(--pepti-muted,#64748b);
				}

				#peptiMwrdDispatchApp .mwrd-items{
					max-width:360px;
					white-space:normal;
					line-height:1.45;
					font-size:11px;
				}

				@media(max-width:1000px){
					#peptiMwrdDispatchApp .mwrd-filters{
						grid-template-columns:1fr 1fr;
					}
				}

				@media(max-width:700px){
					#peptiMwrdDispatchApp .mwrd-filters{
						grid-template-columns:1fr;
						width:100%;
					}
				}
			</style>

			<div class="pepti-mw-notice">
				<strong>Unified dispatch queue</strong>
				<div style="margin-top:5px;">
					All staff with order access can see all WooCommerce orders.
					Warehouse labels are filters only and never hide orders by staff member.
				</div>
			</div>

			<div class="mwrd-toolbar">
				<div class="mwrd-filters">
					<input
						type="search"
						class="search-input"
						id="peptiMwrdSearch"
						placeholder="Order number, customer or email…"
					>

					<select
						class="filter-select"
						id="peptiMwrdWarehouse"
					>
						<option value="">All warehouses</option>
						<option value="hq">HQ</option>
						<option value="eu">Europe</option>
						<option value="unassigned">Unassigned</option>
						<option value="fallback">HQ fallbacks</option>
						<option value="error">Routing errors</option>
					</select>

					<select
						class="filter-select"
						id="peptiMwrdStatus"
					>
						<option value="">All statuses</option>
						<?php foreach (wc_get_order_statuses() as $status_key => $status_name): ?>
							<option value="<?php echo esc_attr(str_replace('wc-', '', $status_key)); ?>">
								<?php echo esc_html($status_name); ?>
							</option>
						<?php endforeach; ?>
					</select>

					<input
						type="text"
						class="search-input"
						id="peptiMwrdCountry"
						maxlength="2"
						placeholder="Country code"
					>

					<button
						type="button"
						class="btn"
						id="peptiMwrdApply"
					>
						Apply
					</button>
				</div>

				<div class="mwrd-pager">
					<button
						type="button"
						class="btn secondary small"
						id="peptiMwrdPrev"
						disabled
					>
						← Previous
					</button>

					<span
						class="pepti-subtle"
						id="peptiMwrdPageInfo"
					>
						Not loaded
					</span>

					<button
						type="button"
						class="btn secondary small"
						id="peptiMwrdNext"
						disabled
					>
						Next →
					</button>
				</div>
			</div>

			<div class="pepti-mw-table-wrap">
				<table class="pepti-mw-table">
					<thead>
						<tr>
							<th>Order</th>
							<th>Date</th>
							<th>Customer</th>
							<th>Country</th>
							<th>Warehouse</th>
							<th>Status</th>
							<th>Items</th>
							<th>Courier / tracking</th>
							<th>Stock</th>
							<th>Total</th>
							<th>Action</th>
						</tr>
					</thead>

					<tbody id="peptiMwrdBody">
						<tr>
							<td
								colspan="11"
								class="mwrd-loading"
							>
								Orders will load when this tab is opened.
							</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>

		<script>
		(function(){
			const app = document.getElementById(
				'peptiMwrdDispatchApp'
			);

			if (!app) return;

			const ajaxUrl =
				<?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;

			const nonce =
				<?php echo wp_json_encode($nonce); ?>;

			const body =
				document.getElementById('peptiMwrdBody');

			const state = {
				loaded:false,
				loading:false,
				page:1,
				maxPages:1,
				total:0
			};

			const get = id =>
				document.getElementById(id);

			function esc(value){
				return String(value ?? '')
					.replace(/&/g,'&amp;')
					.replace(/</g,'&lt;')
					.replace(/>/g,'&gt;')
					.replace(/"/g,'&quot;')
					.replace(/'/g,'&#039;');
			}

			function warehouseHtml(row){
				let output = '';

				if (row.unassigned) {
					output +=
						'<span class="mwrd-pill error">Unassigned</span>';
				} else if (row.warehouse === 'eu') {
					output +=
						'<span class="mwrd-pill eu">'
						+ esc(row.warehouse_name)
						+ '</span>';
				} else {
					output +=
						'<span class="mwrd-pill hq">'
						+ esc(row.warehouse_name)
						+ '</span>';
				}

				if (row.fallback) {
					output +=
						' <span class="mwrd-pill warning">HQ fallback</span>';
				}

				if (row.has_error) {
					output +=
						' <span class="mwrd-pill error" title="'
						+ esc(row.error)
						+ '">Routing error</span>';
				}

				return output;
			}

			function render(rows){
				if (!Array.isArray(rows) || !rows.length) {
					body.innerHTML =
						'<tr><td colspan="11" class="mwrd-loading">'
						+ 'No matching orders.'
						+ '</td></tr>';
					return;
				}

				body.innerHTML = rows.map(row => `
					<tr>
						<td><strong>#${esc(row.number)}</strong></td>
						<td>${esc(row.date || '—')}</td>
						<td>${esc(row.customer || 'Guest')}</td>
						<td>${esc(row.country || '—')}</td>
						<td>${warehouseHtml(row)}</td>
						<td>${esc(row.status_name || '—')}</td>
						<td><div class="mwrd-items">${esc(row.items || '—')}</div></td>
						<td>
							<div>${esc(row.courier || '—')}</div>
							<div class="pepti-subtle">${esc(row.tracking || '')}</div>
						</td>
						<td>${esc(row.stock_state || '—')}</td>
						<td>${String(row.total_html || '—')}</td>
						<td>
							<a
								class="btn secondary small"
								href="${esc(row.edit_url)}"
							>
								Open order
							</a>
							<button
								type="button"
								class="btn secondary small peptiMwrdLocator"
								data-order="${esc(row.number)}"
								style="margin-top:5px;"
							>
								Order Locator
							</button>
						</td>
					</tr>
				`).join('');
			}

			function updatePager(){
				get('peptiMwrdPageInfo').textContent =
					'Page '
					+ state.page
					+ ' of '
					+ state.maxPages
					+ ' · '
					+ state.total
					+ ' orders';

				get('peptiMwrdPrev').disabled =
					state.loading || state.page <= 1;

				get('peptiMwrdNext').disabled =
					state.loading || state.page >= state.maxPages;
			}

			async function loadPage(page = 1){
				if (state.loading) return;

				state.loading = true;
				body.innerHTML =
					'<tr><td colspan="11" class="mwrd-loading">'
					+ 'Loading all orders…'
					+ '</td></tr>';

				updatePager();

				const request = new FormData();
				request.append(
					'action',
					'pepti_mwrd_dispatch_page'
				);
				request.append('nonce', nonce);
				request.append('page', String(page));
				request.append(
					'search',
					get('peptiMwrdSearch').value
				);
				request.append(
					'warehouse',
					get('peptiMwrdWarehouse').value
				);
				request.append(
					'status',
					get('peptiMwrdStatus').value
				);
				request.append(
					'country',
					get('peptiMwrdCountry').value
				);

				try {
					const response = await fetch(
						ajaxUrl,
						{
							method:'POST',
							credentials:'same-origin',
							body:request
						}
					);

					const text = await response.text();
					let json;

					try {
						json = JSON.parse(text);
					} catch (error) {
						throw new Error(
							'Invalid server response: '
							+ text.slice(0,150)
						);
					}

					if (!json.success) {
						throw new Error(
							json?.data?.message
							|| 'Orders could not be loaded.'
						);
					}

					state.page =
						Number(json.data.page || page);

					state.maxPages =
						Math.max(
							1,
							Number(json.data.max_pages || 1)
						);

					state.total =
						Number(json.data.total || 0);

					state.loaded = true;

					render(json.data.rows || []);
				} catch (error) {
					body.innerHTML =
						'<tr><td colspan="11" class="mwrd-loading" style="color:#b91c1c;">'
						+ esc(error.message)
						+ '</td></tr>';
				} finally {
					state.loading = false;
					updatePager();
				}
			}

			function openLocator(orderNumber){
				const input =
					document.getElementById(
						'peptioOrderLocatorSearch'
					);

				const card =
					document.getElementById(
						'peptiStockOrderLocatorCard'
					);

				if (input) {
					input.value = orderNumber;
					input.dispatchEvent(
						new Event('input', {bubbles:true})
					);
					input.dispatchEvent(
						new KeyboardEvent(
							'keydown',
							{
								bubbles:true,
								key:'Enter',
								keyCode:13
							}
						)
					);
					input.focus();
				}

				if (card) {
					card.scrollIntoView({
						behavior:'smooth',
						block:'start'
					});
				}
			}

			app.addEventListener('click', event => {
				const locator =
					event.target.closest(
						'.peptiMwrdLocator'
					);

				if (locator) {
					openLocator(
						locator.dataset.order || ''
					);
				}
			});

			get('peptiMwrdApply')
				.addEventListener(
					'click',
					() => loadPage(1)
				);

			get('peptiMwrdSearch')
				.addEventListener(
					'keydown',
					event => {
						if (event.key === 'Enter') {
							loadPage(1);
						}
					}
				);

			get('peptiMwrdPrev')
				.addEventListener(
					'click',
					() => {
						if (state.page > 1) {
							loadPage(state.page - 1);
						}
					}
				);

			get('peptiMwrdNext')
				.addEventListener(
					'click',
					() => {
						if (state.page < state.maxPages) {
							loadPage(state.page + 1);
						}
					}
				);

			document.addEventListener(
				'pepti:warehouse-panel-opened',
				event => {
					if (
						event.detail?.panel === 'dispatch'
						&& !state.loaded
					) {
						loadPage(1);
					}
				}
			);

			setTimeout(() => {
				const panel = app.closest(
					'.pepti-mw-panel'
				);

				if (
					panel?.classList.contains('active')
					&& !state.loaded
				) {
					loadPage(1);
				}
			}, 250);
		})();
		</script>
		<?php
	},
	10,
	1
);

/* ==========================================================================
 * SETTINGS INFORMATION
 * ========================================================================== */

add_action(
	'pepti_mw_workspace_tab_settings',
	function($context) {
		?>
		<div
			class="pepti-mw-notice"
			style="margin-top:16px;"
		>
			<strong>Unified warehouse dispatch</strong>

			<div style="margin-top:7px;">
				Module:
				<strong>Active</strong>
			</div>

			<div style="margin-top:5px;">
				Multi-warehouse routing:
				<strong>
					<?php
					echo pepti_mwrd_is_enabled()
						? 'Enabled'
						: 'Disabled';
					?>
				</strong>
			</div>

			<div class="pepti-subtle" style="margin-top:8px;">
				This module displays all WooCommerce orders to authorised staff.
				It does not deduct, restore or reroute stock. Those actions are
				handled exclusively by Peptio – Frontend Warehouse Stock Routing.
			</div>
		</div>
		<?php
	},
	20,
	1
);
