<?php

declare(strict_types=1);

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

$inventory_id = isset( $inventory ) && $inventory ? (int) $inventory->id : 0;
?>
<div class="wrap rc-inventory-we">
	<h1 class="wp-heading-inline">
		<?php echo $inventory_id ? esc_html__( 'Restaurant Costing - Edit Inventory', 'restaurant-costing' ) : esc_html__( 'Restaurant Costing - New Inventory', 'restaurant-costing' ); ?>
	</h1>
	<div class="rc-version">v<?php echo esc_html( RC_VERSION ); ?></div>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-inventory' ) ); ?>" class="button rc-btn-edge"><?php esc_html_e( 'Back to Inventories', 'restaurant-costing' ); ?></a>
	<hr class="wp-header-end">

	<form id="rc-inventory-we-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<?php wp_nonce_field( 'rc_save_inventory' ); ?>
		<input type="hidden" name="action" value="rc_save_inventory" />
		<input type="hidden" name="inventory_id" value="<?php echo (int) $inventory_id; ?>" />

		<div class="rc-we-header">
		<span class="rc-fw-600"><?php echo $inventory_id ? esc_html( (string) ( $inventory->name ?? '' ) ) : esc_html__( 'Inventory ' . current_time( 'Y-m-d' ), 'restaurant-costing' ); ?></span>
			<label class="rc-ml-12 rc-fw-400">
			<input type="checkbox" id="rc-hide-subrecipes" />
			<?php esc_html_e( 'Inventory View / Prep List View', 'restaurant-costing' ); ?>
		</label>
	</div>
	<div id="rc-view-banner" class="rc-view-banner"><?php esc_html_e( 'Inventory List', 'restaurant-costing' ); ?></div>
	<div class="rc-inventory-we-header">
		<div class="rc-inventory-we-status"></div>
		<div id="rc-inventory-we-controls">
			<div class="rc-we-controls-inner">
				<label class="rc-ml-12 rc-fw-400">
				<input type="checkbox" id="rc-hide-empty-rows" />
				<?php esc_html_e( 'Hide Items/Rows with Zero Quantity', 'restaurant-costing' ); ?>
			</label>
			<span id="rc-tally" class="rc-tally"></span>
			<button type="button" class="button button-primary" id="rc-save-stay"><?php esc_html_e( 'Save', 'restaurant-costing' ); ?></button>
			<button type="submit" class="button button-primary rc-save-top"><?php esc_html_e( 'Save & Close', 'restaurant-costing' ); ?></button>
			<button type="button" class="button" id="rc-print-prep-list" style="display:none"><?php esc_html_e( 'Print Prep List', 'restaurant-costing' ); ?></button>
			<button type="button" class="button" id="rc-email-prep-list" style="display:none"><?php esc_html_e( 'Email Prep List', 'restaurant-costing' ); ?></button>
		</div>

		<div id="rc-inventory-we-loading" class="rc-loading"><?php esc_html_e( 'Loading ingredients...', 'restaurant-costing' ); ?></div>

		<div id="rc-inventory-we-table-wrap" class="rc-hidden">
			<table class="rc-we-table" id="rc-we-table">
				<thead>
					<tr>
						<th class="rc-col-ingredient"><?php esc_html_e( 'Ingredient', 'restaurant-costing' ); ?></th>
						<th class="rc-col-minlevel"><?php esc_html_e( 'Min', 'restaurant-costing' ); ?></th>
						<th class="rc-col-order"><?php esc_html_e( 'Order', 'restaurant-costing' ); ?></th>
					</tr>
				</thead>
				<tbody id="rc-we-tbody">
				</tbody>
			</table>

		<div class="rc-save-bottom-wrap">
			<button type="button" class="button button-primary rc-save-stay"><?php esc_html_e( 'Save', 'restaurant-costing' ); ?></button>
			<button type="button" id="rc-we-save-bottom" class="button button-primary rc-ml-4"><?php esc_html_e( 'Save & Close', 'restaurant-costing' ); ?></button>
		</div>
		<div id="rc-one-time-items" class="rc-mt-8 rc-hidden">
			<h3 class="rc-ott-heading"><?php esc_html_e( 'Add One-Time Item', 'restaurant-costing' ); ?>
				<button type="button" class="button rc-ml-8" id="rc-add-one-time-item"><?php esc_html_e( '+ Add', 'restaurant-costing' ); ?></button>
			</h3>
			<p class="rc-ott-desc"><?php esc_html_e( 'Temporary items not in your ingredient library.', 'restaurant-costing' ); ?></p>
			<table class="rc-we-table" id="rc-ott-table">
				<thead>
					<tr>
						<th class="rc-col-ingredient"><?php esc_html_e( 'Item Name', 'restaurant-costing' ); ?></th>
						<th class="rc-col-minlevel"></th>
						<th class="rc-col-order"><?php esc_html_e( 'Order', 'restaurant-costing' ); ?></th>
					</tr>
				</thead>
				<tbody id="rc-ott-tbody">
				</tbody>
			</table>
		</div>
		<div id="rc-no-supplier-items" class="rc-mt-8 rc-hidden">
			<h3 class="rc-ott-heading"><?php esc_html_e( 'Items Without Suppliers', 'restaurant-costing' ); ?></h3>
			<p class="rc-ott-desc"><?php esc_html_e( 'These items have no supplier assigned and are shown for reference.', 'restaurant-costing' ); ?></p>
			<table class="rc-we-table" id="rc-nosup-table">
				<thead>
					<tr>
						<th class="rc-col-ingredient"><?php esc_html_e( 'Ingredient', 'restaurant-costing' ); ?></th>
						<th class="rc-col-minlevel"><?php esc_html_e( 'Min', 'restaurant-costing' ); ?></th>
						<th class="rc-col-order"><?php esc_html_e( 'Order', 'restaurant-costing' ); ?></th>
					</tr>
				</thead>
				<tbody id="rc-nosup-tbody">
				</tbody>
			</table>
			<div class="rc-save-bottom-wrap rc-mt-12">
				<button type="button" class="button button-primary rc-save-stay"><?php esc_html_e( 'Save', 'restaurant-costing' ); ?></button>
				<button type="button" id="rc-we-save-nosup-bottom" class="button button-primary rc-ml-4"><?php esc_html_e( 'Save & Close', 'restaurant-costing' ); ?></button>
			</div>
		</div>
		</div>
	</form>
</div>

<script>
(function ($) {
	'use strict';

	var inventoryId = <?php echo (int) $inventory_id; ?>;

	function loadInventoryData() {
		$.getJSON(ajaxurl, {
			action: 'rc_get_inventory_data',
			nonce: '<?php echo wp_create_nonce( 'rc_inventory_ajax' ); ?>',
			inventory_id: inventoryId
		}).done(function (resp) {
			if (!resp || !resp.success) {
				$('#rc-inventory-we-loading').text('Failed to load ingredients.');
				return;
			}
			renderTable(resp.data);
		}).fail(function (jqXHR) {
			$('#rc-inventory-we-loading').text('Request failed. Status: ' + jqXHR.status + ' - ' + (jqXHR.responseText || 'no response'));
		});
	}

	function fmtNum(val) {
		var n = parseFloat(val);
		return isNaN(n) ? '' : String(n);
	}

	function renderTable(data) {
		var ingredients = data.ingredients || [];
		var oneTimeItems = data.saved_items || [];

		var groups = [];
		var currentArea = null;
		var currentGroup = null;
		$.each(ingredients, function (_, ing) {
			var areaName = ing.area_name || '';
			if (areaName !== currentArea) {
				currentArea = areaName;
				currentGroup = { area: areaName, rows: [] };
				groups.push(currentGroup);
			}
			currentGroup.rows.push(ing);
		});

		var html = '';
		$.each(groups, function (_, group) {
			var areaName = group.area || '<?php echo esc_js( __( 'Uncategorized', 'restaurant-costing' ) ); ?>';
			html += '<tr class="rc-area-header" data-area-idx="' + $.now() + '">';
			html += '<td colspan="3"><span class="rc-collapse-icon">&#9660;</span> <strong>' + $('<span>').text(areaName).html() + '</strong></td>';
			html += '</tr>';
			$.each(group.rows, function (_, ing) {
				var orderVal = ing.order_qty != null && ing.order_qty !== '' ? fmtNum(ing.order_qty) : '';
				var isRecipe = parseInt(ing.is_recipe) === 1 ? '1' : '0';
				html += '<tr class="rc-ingredient-row' + (isRecipe === '1' ? ' rc-subrecipe-row' : '') + '" data-is-recipe="' + isRecipe + '">';
				html += '<td class="rc-col-ingredient">' + $('<span>').text(ing.name).html() + '<input type="hidden" name="items[' + ing.id + '][ingredient_name]" value="' + $('<span>').text(ing.name).html() + '" /><input type="hidden" name="items[' + ing.id + '][supplier_name]" value="' + $('<span>').text(ing.supplier || '').html() + '" /><input type="hidden" name="items[' + ing.id + '][min_level]" value="' + (ing.min_level || 0) + '" /></td>';
				html += '<td class="rc-col-minlevel">' + (ing.min_level || 0) + '</td>';
				html += '<td class="rc-col-order"><input type="number" name="items[' + ing.id + '][order_qty]" step="0.01" min="0" value="' + orderVal + '" class="rc-order-input" /></td>';
				html += '</tr>';
			});
		});

		$('#rc-we-tbody').html(html);
		$('#rc-inventory-we-loading').hide();
		$('#rc-inventory-we-table-wrap').show();

		$('#rc-ott-tbody').empty();
		$('#rc-nosup-tbody').empty();
		$('#rc-one-time-items').hide();
		$('#rc-no-supplier-items').hide();

		var ottIdx = 0;
		$.each(oneTimeItems, function (_, item) {
			ottIdx++;
			$('#rc-no-supplier-items').show();
			var ohtml = '<tr class="rc-ott-row">';
			ohtml += '<td class="rc-col-ingredient">' + $('<span>').text(item.ingredient_name || '').html() + '<input type="hidden" name="no_supplier_items[' + ottIdx + '][name]" value="' + $('<span>').text(item.ingredient_name || '').html() + '" /><input type="hidden" name="no_supplier_items[' + ottIdx + '][min_level]" value="' + (item.min_level || 0) + '" /></td>';
			ohtml += '<td class="rc-col-minlevel">' + (item.min_level || 0) + '</td>';
			ohtml += '<td class="rc-col-order"><input type="number" name="no_supplier_items[' + ottIdx + '][order_qty]" step="0.01" min="0" value="' + fmtNum(item.order_qty) + '" class="rc-order-input" /> <button type=\"button\" class=\"button button-small rc-remove-ott rc-ml-4\">&times;</button></td>';
			ohtml += '</tr>';
			$('#rc-nosup-tbody').append(ohtml);
		});

		reconcileVisibility();
		checkLowStock();
	}

	function checkLowStock() {
		$('#rc-we-tbody .rc-ingredient-row').each(function () {
			var $row = $(this);
			var minLvl = parseFloat($row.find('.rc-col-minlevel').text()) || 0;
			var orderVal = parseFloat($row.find('.rc-order-input').val()) || 0;
			$row.toggleClass('rc-low-stock', minLvl > 0 && orderVal < minLvl);
		});
	}

	function reconcileVisibility() {
		$('#rc-we-tbody .rc-ingredient-row, #rc-nosup-tbody .rc-ott-row').show();
		$('#rc-we-tbody .rc-subrecipe-row').show();

		$('.rc-area-header.collapsed').each(function () {
			$(this).nextUntil('.rc-area-header', '.rc-ingredient-row, .rc-subrecipe-row').hide();
		});

		if ($('#rc-hide-subrecipes').is(':checked')) {
			$('#rc-we-tbody [data-is-recipe="0"]').hide();
			$('#rc-one-time-items').hide();
			$('#rc-no-supplier-items').hide();
			$('#rc-print-prep-list').show();
			$('#rc-email-prep-list').show();
		} else {
			$('#rc-we-tbody [data-is-recipe="1"]').hide();
			$('#rc-print-prep-list').hide();
			$('#rc-email-prep-list').hide();
		}

		if ($('#rc-hide-empty-rows').is(':checked')) {
			$('#rc-we-tbody .rc-ingredient-row, #rc-nosup-tbody .rc-ott-row').each(function () {
				var val = $(this).find('.rc-order-input').val();
				if (val === '' || val == null) {
					$(this).hide();
				}
			});
		}

		updateTally();
	}

	function updateTally() {
		var visible = 0;
		var ordering = 0;
		$('#rc-we-tbody .rc-ingredient-row:visible').each(function () {
			visible++;
			var val = parseFloat($(this).find('.rc-order-input').val());
			if (val > 0) {
				ordering++;
			}
		});
		$('#rc-nosup-tbody .rc-ott-row:visible').each(function () {
			visible++;
			var val = parseFloat($(this).find('.rc-order-input').val());
			if (val > 0) {
				ordering++;
			}
		});
		if (visible === 0) {
			$('#rc-tally').text('');
		} else {
			$('#rc-tally').text('Ordering ' + ordering + ' out of ' + visible);
		}
	}

	var ottCount = 0;
	$('#rc-add-one-time-item').on('click', function () {
		$('#rc-one-time-items').show();
		ottCount++;
		var html = '<tr class="rc-ott-row">';
		html += '<td class="rc-col-ingredient"><input type="text" name="one_time_items[' + ottCount + '][name]" class="rc-ott-input" placeholder="Item name" /></td>';
		html += '<td class="rc-col-minlevel"></td>';
		html += '<td class="rc-col-order"><input type="number" name="one_time_items[' + ottCount + '][order_qty]" step="0.01" min="0" class="rc-order-input" /> <button type=\"button\" class=\"button button-small rc-remove-ott rc-ml-4\">&times;</button></td>';
		html += '</tr>';
		$('#rc-ott-tbody').append(html);
		reconcileVisibility();
	});

	$(document).on('click', '.rc-remove-ott', function () {
		$(this).closest('tr').remove();
		reconcileVisibility();
	});

	$(document).on('click', '.rc-area-header', function () {
		$(this).toggleClass('collapsed');
		reconcileVisibility();
	});

	$(document).on('input change', '.rc-order-input', function () {
		reconcileVisibility();
		checkLowStock();
	});

	$('#rc-hide-subrecipes').on('change', function () {
		var banner = $('#rc-view-banner');
		if ($(this).is(':checked')) {
			banner.text('<?php echo esc_js( __( 'Prep List', 'restaurant-costing' ) ); ?>');
		} else {
			banner.text('<?php echo esc_js( __( 'Inventory List', 'restaurant-costing' ) ); ?>');
		}
		reconcileVisibility();
	});

	$('#rc-hide-empty-rows').on('change', function () {
		reconcileVisibility();
	});

	$('#rc-print-prep-list').on('click', function () {
		var url = ajaxurl.replace('admin-ajax.php', 'admin-post.php')
			+ '?action=rc_print_inventory&id=' + inventoryId
			+ '&_wpnonce=' + '<?php echo wp_create_nonce( 'rc_inventory_ajax' ); ?>'
			+ '&prep_list=1&hide_blank=' + ($('#rc-hide-empty-rows').is(':checked') ? '1' : '0');
		window.open(url, '_blank');
	});

	// Save (AJAX, stay on page)
	$(document).on('click', '.rc-save-stay', function () {
		var formData = $('#rc-inventory-we-form').serialize();
		formData += '&action=rc_save_inventory_ajax&nonce=<?php echo wp_create_nonce( 'rc_inventory_ajax' ); ?>';
		$.post(ajaxurl, formData, function (resp) {
			if (resp && resp.success) {
				// Reload the page to show updated data
				location.reload();
			} else {
				alert((resp && resp.data && resp.data.message) || 'Save failed.');
			}
		});
	});

	// Save & Close (submit form, redirects)
	$('#rc-we-save-bottom, #rc-we-save-nosup-bottom').on('click', function () {
		$('#rc-inventory-we-form').submit();
	});

	loadInventoryData();
})(jQuery);
</script>

<style>
.rc-we-header {
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	padding: 12px 16px;
	margin: 1em 0;
	display: flex;
	flex-wrap: wrap;
	gap: 12px;
	align-items: center;
}
.rc-we-table {
	width: 100%;
	border-collapse: collapse;
	background: #fff;
	border: 1px solid #c3c4c7;
	border-radius: 4px;
	overflow: hidden;
}
.rc-we-table th {
	background: #f0f0f1;
	padding: 8px 12px;
	text-align: left;
	font-weight: 600;
	border-bottom: 2px solid #c3c4c7;
	font-size: 12px;
	text-transform: uppercase;
}
.rc-we-table td {
	padding: 6px 12px;
	border-bottom: 1px solid #e5e5e5;
}
.rc-we-table .rc-col-ingredient { width: 60%; }
.rc-we-table .rc-col-minlevel { width: 15%; text-align: center; }
.rc-we-table .rc-col-order { width: 25%; }
.rc-we-table tr.rc-area-header td {
	background: #eef5ff;
	font-weight: 600;
	padding: 6px 12px;
	border-bottom: 1px solid #c3c4c7;
	cursor: pointer;
	user-select: none;
}
.rc-we-table tr.rc-area-header td:hover {
	background: #dce6f5;
}
.rc-collapse-icon {
	display: inline-block;
	font-size: 10px;
	margin-right: 4px;
	transition: transform 0.15s;
}
.rc-order-input {
	width: 80px;
	padding: 4px 8px;
	border: 1px solid #8c8f94;
	border-radius: 3px;
}
.rc-ott-input { width: 90%; }

@media (max-width: 782px) {
	.rc-we-table .rc-col-ingredient { width: 50%; font-size: 14px; }
	.rc-we-table .rc-col-minlevel { width: 20%; font-size: 14px; }
	.rc-we-table .rc-col-order { width: 30%; }
	.rc-order-input { width: 100%; max-width: 80px; font-size: 16px; }
	.rc-we-header { flex-direction: column; align-items: stretch; }
}
.rc-low-stock { background-color: #fff3cd !important; }
.rc-low-stock td { background-color: #fff3cd !important; }
</style>
