<?php
/**
 * Order closing module rebuilt from the CERRAR ORDENES workbook.
 *
 * @package Logistica
 */

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

/**
 * Celda de accion (eliminar) para bloques de calculo.
 *
 * @return void
 */
function logistica_close_matrix_action_cell() {
	?>
	<td class="logistica-warehouse-actions-cell">
		<div class="logistica-warehouse-actions">
			<button type="button" class="button button-small logistica-table-icon-btn logistica-warehouse-btn-delete" data-action="remove-close-block" aria-label="<?php esc_attr_e( 'Eliminar bloque', 'logistica' ); ?>" title="<?php esc_attr_e( 'Eliminar bloque', 'logistica' ); ?>">
				<span class="dashicons dashicons-trash" aria-hidden="true"></span>
			</button>
		</div>
	</td>
	<?php
}

$cierre_config = Logistica_Order_Closing::get_config();
$export_url    = wp_nonce_url(
	add_query_arg( 'action', 'logistica_export_cierre_excel', admin_url( 'admin-post.php' ) ),
	'logistica_export_cierre_excel'
);
$import_action = admin_url( 'admin-post.php' );
if ( is_admin() ) {
	$import_redirect_url = logistica_tab_url( 'logistica-cierre-ordenes', 'admin' );
} else {
	$import_redirect_url = logistica_tab_url( 'logistica-cierre-ordenes', 'frontend' );
}
$variant_options = Logistica_Order_Closing::standard_variant_options();
foreach ( $cierre_config['referencias'] as $variant_ref ) {
	if ( ! empty( $variant_ref['variante'] ) ) {
		$variant_options[] = $variant_ref['variante'];
	}
}
$variant_options = array_values( array_unique( $variant_options ) );
$product_type_options = Logistica_Order_Closing::standard_product_type_options();
foreach ( $cierre_config['referencias'] as $type_ref ) {
	if ( ! empty( $type_ref['tipo_producto'] ) ) {
		$product_type_options[] = $type_ref['tipo_producto'];
	}
}
$product_type_options = array_values( array_unique( $product_type_options ) );
$reference_name_options = Logistica_Order_Closing::standard_reference_name_options();
foreach ( $cierre_config['referencias'] as $name_ref ) {
	if ( ! empty( $name_ref['nombre'] ) ) {
		$reference_name_options[] = $name_ref['nombre'];
	}
}
$reference_name_options = array_values( array_unique( $reference_name_options ) );
natcasesort( $reference_name_options );
$reference_name_options = array_values( $reference_name_options );
$reference_filter_groups = Logistica_Order_Closing::reference_filter_groups( $cierre_config );
$closing_references      = $cierre_config['referencias'];
$closing_reference_seed  = false;

if ( empty( $closing_references ) ) {
	$closing_reference_seed = true;
	$closing_references     = array(
		array(
			'id'               => '',
			'nombre'           => '',
			'variante'         => 'Nacional',
			'tipo_producto'    => '',
			'unidad_empaque'   => '',
			'unidades'         => '',
			'formula_template' => '',
			'lineas'           => array(),
		),
	);
}
?>
<style id="logistica-base-navigator-layout">
	.logistica-close-layout {
		grid-template-areas: "left main" !important;
		grid-template-columns: minmax(0, 320px) minmax(0, 1fr) !important;
	}
	.logistica-close-left-column {
		grid-area: left !important;
		max-width: 320px !important;
	}
	.logistica-close-sidebar {
		flex: 0 0 auto !important;
		max-width: 100% !important;
		overflow-x: hidden !important;
		position: relative !important;
	}
	.logistica-close-bases-list {
		flex: 0 0 auto !important;
		min-height: auto !important;
	}
	.logistica-base-navigator {
		box-sizing: border-box !important;
		contain: inline-size;
		max-width: 100% !important;
		min-width: 0 !important;
		overflow: hidden !important;
		width: 100% !important;
	}
	.logistica-base-navigator label,
	.logistica-base-nav-grid {
		max-width: 100% !important;
		min-width: 0 !important;
	}
	.logistica-base-field-control {
		display: flex !important;
		max-width: 100% !important;
		min-width: 0 !important;
		overflow: hidden !important;
		width: 100% !important;
	}
	.logistica-base-field-control > input,
	.logistica-base-field-control > select {
		box-sizing: border-box !important;
		flex: 1 1 0 !important;
		max-width: 100% !important;
		min-width: 0 !important;
		width: 0 !important;
	}
	.logistica-base-count {
		display: flex !important;
		flex-direction: column !important;
		gap: 3px;
		max-width: 100% !important;
		min-width: 0 !important;
		width: 100% !important;
	}
	.logistica-base-count-summary,
	.logistica-base-count-meta,
	.logistica-base-count-hint,
	.logistica-base-count-line {
		display: block !important;
		max-width: 100% !important;
		min-width: 0 !important;
		overflow-wrap: anywhere !important;
		white-space: normal !important;
		width: 100% !important;
		word-break: break-word !important;
	}
	@media (max-width: 782px) {
		.logistica-close-layout {
			grid-template-columns: minmax(0, 1fr) !important;
			grid-template-areas:
				"left"
				"main" !important;
		}
		.logistica-close-left-column {
			grid-area: left !important;
			max-height: none !important;
			max-width: 100% !important;
			overflow: visible !important;
			position: static !important;
		}
		.logistica-close-main {
			grid-area: main !important;
		}
	}
</style>
<section class="logistica-close-workspace" data-close-workspace data-base-filter-mode="active">
	<div class="logistica-close-loading logistica-tab-loading" data-close-loading data-logistica-tab-loading role="status" aria-live="polite" aria-busy="true">
		<div class="logistica-close-loading-inner logistica-tab-loading__inner">
			<span class="logistica-close-loading-spinner logistica-tab-loading__spinner" aria-hidden="true"></span>
			<p data-logistica-tab-loading-message><?php esc_html_e( 'Cargando cierre de órdenes...', 'logistica' ); ?></p>
		</div>
	</div>
	<datalist id="logistica-close-variants">
		<?php foreach ( Logistica_Order_Closing::standard_variant_options() as $standard_variant ) : ?>
			<option value="<?php echo esc_attr( $standard_variant ); ?>">
		<?php endforeach; ?>
	</datalist>
	<datalist id="logistica-product-types">
		<?php foreach ( Logistica_Order_Closing::standard_product_type_options() as $standard_product_type ) : ?>
			<option value="<?php echo esc_attr( $standard_product_type ); ?>">
		<?php endforeach; ?>
	</datalist>
	<?php $close_line_template_label = Logistica_Order_Closing::formula_label( '' ); ?>
	<template id="logistica-close-line-template">
		<tr data-close-line="nuevo_bloque">
			<td class="is-editable"><input name="cierre[referencias][0][lineas][0][label]" data-field="label" value=""></td>
			<td class="is-editable"><input type="number" step="0.001" name="cierre[referencias][0][lineas][0][paquetes]" data-field="paquetes" value=""></td>
			<td class="is-editable"><input type="number" step="0.001" name="cierre[referencias][0][lineas][0][unidades_paquete]" data-field="unidades_paquete" value=""></td>
			<td class="is-auto"><span data-output="cantidad_total"></span><input type="hidden" name="cierre[referencias][0][lineas][0][cantidad]" data-field="cantidad" value=""></td>
			<td class="is-editable"><select name="cierre[referencias][0][lineas][0][base_tipo]" data-field="base_tipo">
				<option value=""><?php esc_html_e( 'Seleccionar tipo...', 'logistica' ); ?></option>
				<?php foreach ( Logistica_Order_Closing::base_type_options() as $base_type_value => $base_type_label ) : ?>
					<option value="<?php echo esc_attr( $base_type_value ); ?>"><?php echo esc_html( $base_type_label ); ?></option>
				<?php endforeach; ?>
			</select></td>
			<td class="is-auto">
				<span class="logistica-formula-auto"><?php echo esc_html( $close_line_template_label ); ?></span>
				<input type="hidden" name="cierre[referencias][0][lineas][0][formula]" data-field="formula" value="">
			</td>
			<td class="is-auto is-close-copy">
				<span class="logistica-close-copy-value" data-output="cod" tabindex="0" role="button" title="<?php esc_attr_e( 'Clic para copiar', 'logistica' ); ?>"></span>
			</td>
			<td class="is-auto is-close-copy">
				<span class="logistica-close-copy-value" data-output="lote" tabindex="0" role="button" title="<?php esc_attr_e( 'Clic para copiar', 'logistica' ); ?>"></span>
			</td>
			<td class="is-auto" data-output="unitkg"></td>
			<td class="is-auto is-close-copy">
				<span class="logistica-close-copy-value" data-output="ajustado" tabindex="0" role="button" title="<?php esc_attr_e( 'Clic para copiar', 'logistica' ); ?>"></span>
			</td>
			<td data-output="estado"></td>
			<?php logistica_close_matrix_action_cell(); ?>
			<input type="hidden" name="cierre[referencias][0][lineas][0][tipo]" data-field="tipo" value="nuevo_bloque">
			<input type="hidden" name="cierre[referencias][0][lineas][0][estado_formula]" data-field="estado_formula" value="">
			<input type="hidden" name="cierre[referencias][0][lineas][0][base_link_id]" data-field="base_link_id" value="">
		</tr>
	</template>
	<form
		id="logistica-cierre-excel-upload"
		class="logistica-excel-upload-form-source"
		method="post"
		action="<?php echo esc_url( $import_action ); ?>"
		enctype="multipart/form-data"
		hidden
	>
		<input type="hidden" name="action" value="logistica_import_cierre_excel">
		<input type="hidden" name="redirect_to" value="<?php echo esc_url( $import_redirect_url ); ?>">
		<?php wp_nonce_field( 'logistica_import_cierre_excel' ); ?>
	</form>
	<form id="logistica-cierre-save-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="logistica_save_cierre_ordenes">
		<input type="hidden" name="cierre_json" data-cierre-json value="">
		<?php wp_nonce_field( 'logistica_save_cierre_ordenes' ); ?>

		<div class="logistica-close-toolbar logistica-close-toolbar--ordenes">
			<div class="logistica-page-toolbar__intro">
				<?php logistica_page_toolbar_icon( 'dashicons-clipboard' ); ?>
				<div>
					<div class="logistica-close-toolbar-heading">
						<h2><?php esc_html_e( 'Cierre de órdenes', 'logistica' ); ?></h2>
						<span class="logistica-autosave-status" data-autosave-status aria-live="polite" title="<?php esc_attr_e( 'Los datos se guardan en la base de datos de WordPress. El navegador solo recuerda filtros y paneles abiertos.', 'logistica' ); ?>"><?php esc_html_e( 'Autoguardado en base de datos', 'logistica' ); ?></span>
					</div>
					<p><?php esc_html_e( 'Configura bases, referencias y bloques de cálculo para cerrar pedidos. Los cambios se autoguardan y puedes actualizarlos en masa con Excel.', 'logistica' ); ?></p>
				</div>
			</div>
			<div class="logistica-close-toolbar__actions">
				<div class="logistica-actions">
					<button type="button" class="button logistica-sheet-action-btn" data-action="add-close-ref"><?php esc_html_e( 'Añadir referencia', 'logistica' ); ?></button>
					<button type="button" class="button" data-action="refresh-close-bases"><?php esc_html_e( 'Actualizar bases', 'logistica' ); ?></button>
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Guardar configuración', 'logistica' ); ?></button>
				</div>
				<?php
				logistica_table_excel_toolbar(
					array(
						'export_url'        => $export_url,
						'import_form_id'    => 'logistica-cierre-excel-upload',
						'import_input_id'   => 'logistica-cierre-excel-file',
						'import_input_name' => 'cierre_excel_file',
						'import_data_attr'  => 'cierre-import-file',
						'import_action'     => 'import-cierre-excel',
						'show_zoom'         => false,
					)
				);
				?>
			</div>
			<p class="logistica-excel-bulk-help logistica-close-toolbar__help"><?php esc_html_e( 'Descarga la plantilla con los datos actuales, edita las celdas amarillas en Excel y sube el archivo para actualizar bases, referencias y bloques en masa.', 'logistica' ); ?></p>
		</div>

		<div class="logistica-close-legend">
			<span class="is-formula"><?php esc_html_e( 'Fórmulada', 'logistica' ); ?></span>
			<span class="is-pending"><?php esc_html_e( 'Sin fórmula', 'logistica' ); ?></span>
			<span class="is-editable"><?php esc_html_e( 'Editable', 'logistica' ); ?></span>
			<span class="is-auto"><?php esc_html_e( 'Fórmulada / bloqueada', 'logistica' ); ?></span>
			<span class="is-missing"><?php esc_html_e( 'Dato faltante', 'logistica' ); ?></span>
			<span class="is-error"><?php esc_html_e( 'Posible error', 'logistica' ); ?></span>
			<span class="logistica-variant-legend is-variant-nacional"><?php esc_html_e( 'Nacional', 'logistica' ); ?></span>
			<span class="logistica-variant-legend is-variant-exportacion"><?php esc_html_e( 'Exportación', 'logistica' ); ?></span>
			<span class="logistica-variant-legend is-variant-bionatura"><?php esc_html_e( 'Bionatura', 'logistica' ); ?></span>
			<span class="logistica-variant-legend is-variant-estandar"><?php esc_html_e( 'Estándar', 'logistica' ); ?></span>
		</div>

		<div class="logistica-close-layout">
			<div class="logistica-close-left-column">
			<aside class="logistica-close-sidebar">
				<h3 class="logistica-close-sidebar-title"><?php esc_html_e( 'Bases permanentes', 'logistica' ); ?></h3>
				<p><?php esc_html_e( 'Códigos, lotes, gramajes, anchos, calibres y ajustes usados por las referencias.', 'logistica' ); ?></p>
				<div class="logistica-base-navigator">
					<label><?php esc_html_e( 'Buscar base', 'logistica' ); ?><span class="logistica-base-field-control"><input type="search" data-base-search placeholder="<?php esc_attr_e( 'Referencia, código o lote', 'logistica' ); ?>"></span></label>
					<div class="logistica-base-nav-grid">
						<label><?php esc_html_e( 'Variante', 'logistica' ); ?><span class="logistica-base-field-control"><select data-base-variant-filter>
							<option value=""><?php esc_html_e( 'Todas las variantes', 'logistica' ); ?></option>
							<?php foreach ( $variant_options as $base_variant ) : ?>
								<option value="<?php echo esc_attr( $base_variant ); ?>"><?php echo esc_html( $base_variant ); ?></option>
							<?php endforeach; ?>
						</select></span></label>
						<label><?php esc_html_e( 'Tipo', 'logistica' ); ?><span class="logistica-base-field-control"><select data-base-type-filter>
							<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
							<?php foreach ( Logistica_Order_Closing::base_type_options() as $base_type_value => $base_type_label ) : ?>
								<option value="<?php echo esc_attr( $base_type_value ); ?>"><?php echo esc_html( $base_type_label ); ?></option>
							<?php endforeach; ?>
						</select></span></label>
						<label><?php esc_html_e( 'Referencia', 'logistica' ); ?><span class="logistica-base-field-control"><select data-base-reference-filter>
							<option value=""><?php esc_html_e( 'Todas las referencias visibles', 'logistica' ); ?></option>
							<?php foreach ( $reference_filter_groups as $group_label => $group_names ) : ?>
								<optgroup label="<?php echo esc_attr( $group_label ); ?>">
									<?php foreach ( $group_names as $ref_name ) : ?>
										<option value="<?php echo esc_attr( $ref_name ); ?>"><?php echo esc_html( $ref_name ); ?></option>
									<?php endforeach; ?>
								</optgroup>
							<?php endforeach; ?>
						</select></span></label>
					</div>
					<div class="logistica-base-count" data-base-count></div>
					<script>
					(function () {
						var workspace = document.querySelector('[data-close-workspace]');
						var scanScheduled = false;

						function applyBaseCountLines(element, lines) {
							var index;

							if (!element) {
								return;
							}

							while (element.firstChild) {
								element.removeChild(element.firstChild);
							}

							for (index = 0; index < lines.length; index += 1) {
								var lineNode;

								if (!lines[index] || !lines[index].text) {
									continue;
								}

								lineNode = document.createElement('span');
								lineNode.className = lines[index].className || 'logistica-base-count-line';
								lineNode.textContent = lines[index].text;
								element.appendChild(lineNode);
							}
						}

						function normalizeBaseCountText(element) {
							var raw;
							var body;
							var hint;
							var parts;
							var lines;

							if (!element || element.querySelector('.logistica-base-count-summary, .logistica-base-count-line')) {
								return;
							}

							raw = String(element.textContent || '').replace(/\s+/g, ' ').trim();
							if (!raw) {
								return;
							}

							body = raw;
							hint = '';
							parts = body.split(/\s*[—–]\s+/);
							if (parts.length > 1) {
								body = parts[0].trim();
								hint = parts.slice(1).join(' ').trim();
							}

							lines = [];
							parts = body.split(/\s*·\s*todas las variantes\s*/i);
							if (parts.length > 1 && !parts[1].trim()) {
								lines.push({ text: parts[0].trim(), className: 'logistica-base-count-summary' });
								lines.push({ text: 'Todas las variantes', className: 'logistica-base-count-meta' });
							} else {
								lines.push({ text: body, className: 'logistica-base-count-summary' });
							}

							if (hint) {
								lines.push({ text: hint, className: 'logistica-base-count-hint' });
							}

							applyBaseCountLines(element, lines);
						}

						function scanBaseCounts() {
							var scope = workspace || document;

							scope.querySelectorAll('[data-base-count]').forEach(normalizeBaseCountText);
						}

						function scheduleBaseCountScan() {
							if (scanScheduled) {
								return;
							}

							scanScheduled = true;
							window.requestAnimationFrame(function () {
								scanScheduled = false;
								scanBaseCounts();
							});
						}

						window.logisticaApplyBaseCountLines = applyBaseCountLines;
						window.logisticaNormalizeBaseCountText = normalizeBaseCountText;

						if (workspace && typeof window.MutationObserver === 'function') {
							new window.MutationObserver(scheduleBaseCountScan).observe(workspace, {
								childList: true,
								characterData: true,
								subtree: true
							});
						}

						if (document.readyState === 'loading') {
							document.addEventListener('DOMContentLoaded', scheduleBaseCountScan);
						}

						scheduleBaseCountScan();
					})();
					</script>
				</div>
			</aside>

			<div class="logistica-close-sustitucion-summary" data-close-sustitucion-summary hidden>
				<span class="dashicons dashicons-warning" aria-hidden="true"></span>
				<div>
					<strong><?php esc_html_e( 'Sustituciones temporales activas', 'logistica' ); ?></strong>
					<p data-close-sustitucion-summary-text></p>
				</div>
			</div>
			<div class="logistica-close-bases-list" data-close-bases>
					<?php foreach ( $cierre_config['bases'] as $base_index => $base ) : ?>
						<?php
						$base_tipo_current = $base['tipo'] ?? '';
						$base_is_main_cajas = 'cajas' === $base_tipo_current;
						$base_is_saldo_cajas = 'cajas_saldo' === $base_tipo_current;
						$base_is_bags       = 'bolsas' === $base_tipo_current;
						$base_show_length   = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'largo' );
						$base_show_width    = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'ancho' );
						$base_show_height   = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'alto' );
						$base_show_clave    = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'clave' );
						$base_show_gramaje  = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'gramaje' );
						$base_show_calibre  = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'calibre' );
						$base_show_consumo_cajas = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'consumo_cajas' );
						$base_show_consumo_bolsas = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'consumo_bolsas' );
						$base_show_consumo_rollos = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'consumo_rollos' );
						$base_show_und_molde = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'und_molde' );
						$base_show_peso_tamano = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'peso_tamano' );
						$base_show_consumo_plastico = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'consumo_plastico' );
						$base_show_consumo_acetato = Logistica_Order_Closing::base_type_shows_field( $base_tipo_current, 'consumo_acetato' );
						$base_is_acetato = 'acetato' === $base_tipo_current;
						$base_und_molde_label = $base_is_acetato
							? __( 'Cortes por lámina (despiece)', 'logistica' )
							: __( 'Und x molde (und)', 'logistica' );
						$base_lock_dims     = $base_is_main_cajas || $base_is_saldo_cajas || $base_is_bags;
						$base_variant_key = ! empty( $base['variante'] ) ? sanitize_title( strtolower( $base['variante'] ) ) : 'nacional';
						if ( ! $base_variant_key ) {
							$base_variant_key = 'sin-variante';
						}
						$base_type_options_map = Logistica_Order_Closing::base_type_options();
						$base_type_label       = $base_type_options_map[ $base_tipo_current ] ?? ucfirst( $base_tipo_current );
						$base_field_lock_icon  = '<span class="logistica-base-identity-lock" role="img" aria-hidden="true" title="' . esc_attr__( 'Campo bloqueado', 'logistica' ) . '"><svg viewBox="0 0 24 24" width="14" height="14" focusable="false"><path fill="currentColor" d="M17 9h-1V7a4 4 0 0 0-8 0v2H7a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2zm-3-2a2 2 0 0 1 4 0v2h-4V7zm5 12H7v-8h12v8z"/></svg></span>';
						$base_sustitucion_on   = '1' === (string) ( $base['sustitucion_activa'] ?? '0' );
						$base_cod_habitual     = (string) ( $base['cod_habitual'] ?? '' );
						$base_sust_desde       = (string) ( $base['sustitucion_desde'] ?? '' );
						$base_sust_hasta       = (string) ( $base['sustitucion_hasta'] ?? '' );
						?>
						<div class="logistica-base-card is-variant-<?php echo esc_attr( $base_variant_key ); ?> is-base-identity-locked<?php echo $base_sustitucion_on ? ' is-sustitucion-activa' : ''; ?>" data-close-base data-variant-theme="<?php echo esc_attr( $base_variant_key ); ?>" data-base-tipo="<?php echo esc_attr( $base_tipo_current ); ?>" data-base-identity-locked="1" data-sustitucion-activa="<?php echo $base_sustitucion_on ? '1' : '0'; ?>">
							<div class="logistica-base-card-head">
								<button type="button" class="logistica-base-toggle" data-action="toggle-close-base" aria-expanded="false">
									<span class="logistica-base-card-title" data-base-summary>
										<span class="logistica-base-card-headline">
											<span class="logistica-base-type-badge" data-base-type-badge data-base-tipo="<?php echo esc_attr( $base_tipo_current ); ?>"><?php echo esc_html( $base_type_label ); ?></span>
											<span class="logistica-base-variant-chip" data-base-variant-chip><?php echo esc_html( $base['variante'] ?? 'Nacional' ); ?></span>
										</span>
										<span class="logistica-base-card-subtitle">
											<span class="logistica-base-reference" data-base-reference><?php echo esc_html( $base['referencia'] ?? '' ); ?></span>
											<span class="logistica-base-sustitucion-chip" data-base-sustitucion-chip <?php echo $base_sustitucion_on ? '' : 'hidden'; ?>><?php esc_html_e( 'Temporal', 'logistica' ); ?></span>
											<span class="logistica-base-block-label" data-base-block-label hidden></span>
										</span>
									</span>
									<span class="logistica-base-chevron" aria-hidden="true"></span>
								</button>
								<button type="button" class="logistica-base-delete" data-action="remove-close-base" aria-label="<?php esc_attr_e( 'Eliminar base', 'logistica' ); ?>">X</button>
							</div>
							<div class="logistica-base-card-body" data-base-body hidden>
								<input type="hidden" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][id]" data-field="id" value="<?php echo esc_attr( $base['id'] ?? '' ); ?>">
								<div class="logistica-base-identity-group">
									<label class="logistica-base-identity-field">
										<span class="logistica-base-field-label-row"><?php esc_html_e( 'Variante base', 'logistica' ); ?></span>
										<span class="logistica-base-field-control">
											<input list="logistica-close-variants" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][variante]" data-field="variante" class="logistica-readonly-field" readonly tabindex="-1" value="<?php echo esc_attr( $base['variante'] ?? 'Nacional' ); ?>">
											<?php echo $base_field_lock_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static SVG markup. ?>
										</span>
									</label>
									<label class="logistica-base-identity-field">
										<span class="logistica-base-field-label-row"><?php esc_html_e( 'Tipo', 'logistica' ); ?></span>
										<span class="logistica-base-field-control">
											<select disabled tabindex="-1" aria-hidden="true">
												<?php foreach ( Logistica_Order_Closing::base_type_options() as $base_type_value => $base_type_option_label ) : ?>
													<option value="<?php echo esc_attr( $base_type_value ); ?>" <?php selected( $base['tipo'] ?? '', $base_type_value ); ?>><?php echo esc_html( $base_type_option_label ); ?></option>
												<?php endforeach; ?>
											</select>
											<input type="hidden" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][tipo]" data-field="tipo" value="<?php echo esc_attr( $base['tipo'] ?? '' ); ?>">
											<?php echo $base_field_lock_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static SVG markup. ?>
										</span>
									</label>
									<label class="logistica-base-identity-field">
										<span class="logistica-base-field-label-row"><?php esc_html_e( 'Referencia base', 'logistica' ); ?></span>
										<span class="logistica-base-field-control">
											<input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][referencia]" data-field="referencia" class="logistica-readonly-field" readonly tabindex="-1" value="<?php echo esc_attr( $base['referencia'] ?? '' ); ?>">
											<?php echo $base_field_lock_icon; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static SVG markup. ?>
										</span>
									</label>
								</div>
								<div class="logistica-base-grid">
									<label><?php esc_html_e( 'Cod', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][cod]" data-field="cod" value="<?php echo esc_attr( $base['cod'] ?? '' ); ?>"></label>
									<label class="logistica-base-catalog-field" title="<?php esc_attr_e( 'Tomado del inventario bodega (lote vigente)', 'logistica' ); ?>">
										<?php esc_html_e( 'Lote', 'logistica' ); ?>
										<input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][lote]" data-field="lote" class="logistica-readonly-field" readonly tabindex="-1" value="<?php echo esc_attr( $base['lote'] ?? '' ); ?>">
									</label>
									<label data-caja-saldo-field hidden><?php esc_html_e( 'Cod saldo', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][cod_saldo]" data-field="cod_saldo" value=""></label>
									<label data-caja-saldo-field hidden><?php esc_html_e( 'Lote saldo', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][lote_saldo]" data-field="lote_saldo" value=""></label>
									<label data-length-field data-base-field="largo" class="<?php echo $base_lock_dims ? 'logistica-base-catalog-field' : ''; ?><?php echo $base_show_length ? '' : ' is-base-field-hidden'; ?>" <?php echo $base_show_length ? '' : 'hidden'; ?>><span data-length-label><?php echo $base_is_acetato ? esc_html__( 'Largo lámina (cm)', 'logistica' ) : ( $base_is_bags ? esc_html__( 'Largo bolsa (pulg.)', 'logistica' ) : ( $base_is_saldo_cajas ? esc_html__( 'Largo cajas saldo (mm)', 'logistica' ) : esc_html__( 'Largo caja principal (mm)', 'logistica' ) ) ); ?></span><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][largo]" data-field="largo" value="<?php echo esc_attr( $base['largo'] ?? '' ); ?>" <?php echo $base_lock_dims ? 'class="logistica-readonly-field" readonly tabindex="-1"' : ''; ?>></label>
									<label data-width-field data-base-field="ancho" class="<?php echo $base_lock_dims ? 'logistica-base-catalog-field' : ''; ?><?php echo $base_show_width ? '' : ' is-base-field-hidden'; ?>" <?php echo $base_show_width ? '' : 'hidden'; ?>><span data-width-label><?php
										if ( $base_is_bags ) {
											esc_html_e( 'Ancho bolsa (pulg.)', 'logistica' );
										} elseif ( $base_is_saldo_cajas ) {
											esc_html_e( 'Ancho cajas saldo (mm)', 'logistica' );
										} elseif ( $base_is_main_cajas ) {
											esc_html_e( 'Ancho caja principal (mm)', 'logistica' );
										} elseif ( 'papel_bobinas' === $base_tipo_current ) {
											esc_html_e( 'Ancho bobina (mm)', 'logistica' );
										} elseif ( 'rollos' === $base_tipo_current ) {
											esc_html_e( 'Ancho rollo (mm)', 'logistica' );
										} else {
											esc_html_e( 'Ancho', 'logistica' );
										}
										?></span><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][ancho]" data-field="ancho" value="<?php echo esc_attr( $base['ancho'] ?? '' ); ?>" <?php echo $base_lock_dims ? 'class="logistica-readonly-field" readonly tabindex="-1"' : ''; ?>></label>
									<label data-height-field data-base-field="alto" class="<?php echo $base_lock_dims ? 'logistica-base-catalog-field' : ''; ?><?php echo $base_show_height ? '' : ' is-base-field-hidden'; ?>" <?php echo $base_show_height ? '' : 'hidden'; ?>><span data-height-label><?php echo $base_is_saldo_cajas ? esc_html__( 'Alto cajas saldo (mm)', 'logistica' ) : esc_html__( 'Alto caja principal (mm)', 'logistica' ); ?></span><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][alto]" data-field="alto" value="<?php echo esc_attr( $base['alto'] ?? '' ); ?>" <?php echo $base_lock_dims ? 'class="logistica-readonly-field" readonly tabindex="-1"' : ''; ?>></label>
									<label data-box-field data-base-field="clave" class="<?php echo $base_lock_dims ? 'logistica-base-catalog-field' : ''; ?><?php echo $base_show_clave ? '' : ' is-base-field-hidden'; ?>" <?php echo $base_show_clave ? '' : 'hidden'; ?>><span data-clave-label><?php echo $base_is_saldo_cajas ? esc_html__( 'Clave cajas saldo', 'logistica' ) : esc_html__( 'Clave caja principal', 'logistica' ); ?></span><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][clave]" data-field="clave" value="<?php echo esc_attr( $base['clave'] ?? '' ); ?>" <?php echo $base_lock_dims ? 'class="logistica-readonly-field" readonly tabindex="-1"' : ''; ?>></label>
									<label data-caja-saldo-field hidden><?php esc_html_e( 'Largo caja saldo (mm)', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][largo_saldo]" data-field="largo_saldo" value=""></label>
									<label data-caja-saldo-field hidden><?php esc_html_e( 'Ancho caja saldo (mm)', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][ancho_saldo]" data-field="ancho_saldo" value=""></label>
									<label data-caja-saldo-field hidden><?php esc_html_e( 'Alto caja saldo (mm)', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][alto_saldo]" data-field="alto_saldo" value=""></label>
									<label data-caja-saldo-field hidden><?php esc_html_e( 'Clave caja saldo', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][clave_saldo]" data-field="clave_saldo" value=""></label>
									<label class="logistica-calculated-field<?php echo $base_show_consumo_cajas ? '' : ' is-base-field-hidden'; ?>" data-box-consumption-field data-base-field="consumo_cajas" <?php echo $base_show_consumo_cajas ? '' : 'hidden'; ?>><?php esc_html_e( 'Consumo unidades', 'logistica' ); ?><span><?php esc_html_e( 'Unidades / empaque', 'logistica' ); ?></span></label>
									<label data-gramaje-field data-base-field="gramaje" class="<?php echo $base_show_gramaje ? '' : 'is-base-field-hidden'; ?>" <?php echo $base_show_gramaje ? '' : 'hidden'; ?>><?php esc_html_e( 'Gramaje (gr/m2)', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][gramaje]" data-field="gramaje" value="<?php echo esc_attr( $base['gramaje'] ?? '' ); ?>"></label>
									<label data-calibre-field data-base-field="calibre" class="<?php echo $base_is_bags ? 'logistica-base-catalog-field' : ''; ?><?php echo $base_show_calibre ? '' : ' is-base-field-hidden'; ?>" <?php echo $base_show_calibre ? '' : 'hidden'; ?>><?php esc_html_e( 'Calibre (mm)', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][calibre]" data-field="calibre" value="<?php echo esc_attr( $base['calibre'] ?? '' ); ?>" <?php echo $base_is_bags ? 'class="logistica-readonly-field" readonly tabindex="-1"' : ''; ?>></label>
									<label class="logistica-calculated-field<?php echo $base_show_calibre ? '' : ' is-base-field-hidden'; ?>" data-calibre-field data-base-field="calibre" <?php echo $base_show_calibre ? '' : 'hidden'; ?>><?php esc_html_e( 'Calibre (milésimas)', 'logistica' ); ?><span data-output="calibre_pulgadas">-</span></label>
									<label class="logistica-calculated-field<?php echo $base_show_consumo_bolsas ? '' : ' is-base-field-hidden'; ?>" data-bag-consumption-field data-base-field="consumo_bolsas" <?php echo $base_show_consumo_bolsas ? '' : 'hidden'; ?>><?php esc_html_e( 'Consumo unidad', 'logistica' ); ?><span><?php esc_html_e( '1 bolsa / unidad', 'logistica' ); ?></span></label>
									<label class="logistica-calculated-field<?php echo $base_show_consumo_rollos ? '' : ' is-base-field-hidden'; ?>" data-roll-consumption-field data-base-field="consumo_rollos" <?php echo $base_show_consumo_rollos ? '' : 'hidden'; ?>><?php esc_html_e( 'Consumo unidad', 'logistica' ); ?><input type="hidden" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][rendimiento]" data-field="rendimiento" value="<?php echo esc_attr( $base['rendimiento'] ?? '' ); ?>"><span data-output="rendimiento_formula">-</span></label>
									<label data-plastic-field data-base-field="und_molde" class="<?php echo $base_show_und_molde ? '' : 'is-base-field-hidden'; ?>" <?php echo $base_show_und_molde ? '' : 'hidden'; ?>><span data-und-molde-label><?php echo esc_html( $base_und_molde_label ); ?></span><input type="number" step="1" min="1" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][und_molde]" data-field="und_molde" value="<?php echo esc_attr( $base['und_molde'] ?? '' ); ?>"></label>
									<label data-plastic-field data-base-field="peso_tamano" class="<?php echo $base_show_peso_tamano ? '' : 'is-base-field-hidden'; ?>" <?php echo $base_show_peso_tamano ? '' : 'hidden'; ?>><?php esc_html_e( 'Peso tamaño (gr)', 'logistica' ); ?><input type="number" step="0.01" min="0" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][peso_tamano]" data-field="peso_tamano" value="<?php echo esc_attr( $base['peso_tamano'] ?? '' ); ?>"></label>
									<label class="logistica-calculated-field<?php echo $base_show_consumo_plastico ? '' : ' is-base-field-hidden'; ?>" data-plastic-consumption-field data-base-field="consumo_plastico" <?php echo $base_show_consumo_plastico ? '' : 'hidden'; ?>><?php esc_html_e( 'Consumo unidad (kg)', 'logistica' ); ?><span data-output="plastico_consumo_unidad">-</span></label>
									<label class="logistica-calculated-field<?php echo $base_show_consumo_acetato ? '' : ' is-base-field-hidden'; ?>" data-acetato-consumption-field data-base-field="consumo_acetato" <?php echo $base_show_consumo_acetato ? '' : 'hidden'; ?>><?php esc_html_e( 'Consumo (láminas)', 'logistica' ); ?><span data-output="acetato_consumo_unidad">-</span></label>
									<label><?php esc_html_e( 'Ajuste +/-', 'logistica' ); ?><input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][ajuste]" data-field="ajuste" value="<?php echo esc_attr( $base['ajuste'] ?? '' ); ?>"></label>
								</div>
								<div class="logistica-base-sustitucion" data-base-sustitucion>
									<label class="logistica-base-sustitucion-toggle">
										<input type="checkbox" data-sustitucion-toggle <?php checked( $base_sustitucion_on ); ?>>
										<span><?php esc_html_e( 'Aviso de sustitución temporal', 'logistica' ); ?></span>
									</label>
									<p class="logistica-base-sustitucion-hint" data-sustitucion-hint <?php echo $base_sustitucion_on ? 'hidden' : ''; ?>>
										<?php esc_html_e( 'Actívalo cuando uses otro código por falta de stock, para no olvidar volver al habitual.', 'logistica' ); ?>
									</p>
									<input type="hidden" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][sustitucion_activa]" data-field="sustitucion_activa" value="<?php echo $base_sustitucion_on ? '1' : '0'; ?>">
									<div class="logistica-base-sustitucion-body" data-sustitucion-fields <?php echo $base_sustitucion_on ? '' : 'hidden'; ?>>
										<div class="logistica-base-sustitucion-fields">
											<label>
												<span><?php esc_html_e( 'Código habitual', 'logistica' ); ?></span>
												<input name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][cod_habitual]" data-field="cod_habitual" value="<?php echo esc_attr( $base_cod_habitual ); ?>" placeholder="<?php esc_attr_e( 'Ej. 9', 'logistica' ); ?>" autocomplete="off">
												<small><?php esc_html_e( 'El que usas normalmente', 'logistica' ); ?></small>
											</label>
											<label>
												<span><?php esc_html_e( 'Desde', 'logistica' ); ?></span>
												<input type="date" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][sustitucion_desde]" data-field="sustitucion_desde" value="<?php echo esc_attr( $base_sust_desde ); ?>">
												<small><?php esc_html_e( 'Inicio del uso temporal', 'logistica' ); ?></small>
											</label>
											<label>
												<span><?php esc_html_e( 'Retomar el', 'logistica' ); ?></span>
												<input type="date" name="cierre[bases][<?php echo esc_attr( $base_index ); ?>][sustitucion_hasta]" data-field="sustitucion_hasta" value="<?php echo esc_attr( $base_sust_hasta ); ?>">
												<small><?php esc_html_e( 'Fecha esperada de retorno', 'logistica' ); ?></small>
											</label>
										</div>
										<div class="logistica-base-sustitucion-actions">
											<button type="button" class="button button-small logistica-base-sustitucion-restore" data-action="restore-closing-habitual-cod"><?php esc_html_e( 'Restaurar código habitual', 'logistica' ); ?></button>
										</div>
										<div class="logistica-base-sustitucion-alert" data-sustitucion-alert role="status">
											<span class="dashicons dashicons-warning" aria-hidden="true"></span>
											<div class="logistica-base-sustitucion-alert-copy">
												<strong data-sustitucion-alert-title></strong>
												<p data-sustitucion-alert-text></p>
											</div>
										</div>
									</div>
								</div>
								<a href="#close-ref-<?php echo esc_attr( sanitize_title( $base['referencia'] ?? 'base' ) ); ?>"><?php esc_html_e( 'Ir a referencias similares', 'logistica' ); ?></a>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</div>

			<div class="logistica-close-main" data-close-references>
				<div class="logistica-close-ref-empty logistica-close-filter-empty" data-close-filter-empty hidden>
					<p><?php esc_html_e( 'No hay referencias que coincidan con los filtros seleccionados.', 'logistica' ); ?></p>
				</div>
				<?php if ( $closing_reference_seed ) : ?>
					<div class="logistica-close-ref-empty is-visible" data-close-ref-empty>
						<p><?php esc_html_e( 'Sin referencias creadas', 'logistica' ); ?></p>
					</div>
				<?php endif; ?>
				<?php foreach ( $closing_references as $ref_index => $ref ) : ?>
					<?php
					$current_variant       = $ref['variante'] ?? '';
					$normalized_variants   = array_map( 'strtolower', $variant_options );
					$current_variant_known = in_array( strtolower( $current_variant ), $normalized_variants, true );
					$variant_theme_key     = $current_variant ? sanitize_title( strtolower( $current_variant ) ) : 'sin-variante';
					if ( ! $variant_theme_key ) {
						$variant_theme_key = 'sin-variante';
					}
					?>
					<article class="logistica-close-reference is-variant-<?php echo esc_attr( $variant_theme_key ); ?> is-ref-meta-locked" id="close-ref-<?php echo esc_attr( sanitize_title( $ref['unidad_empaque'] ?? $ref['nombre'] ?? 'ref' ) ); ?>" data-close-reference data-variant-theme="<?php echo esc_attr( $variant_theme_key ); ?>" data-ref-meta-locked="1"<?php echo $closing_reference_seed ? ' data-reference-seed hidden' : ''; ?>>
						<header>
							<label class="logistica-reference-pick" title="<?php esc_attr_e( 'Mostrar todas las bases permanentes de esta referencia en el panel izquierdo', 'logistica' ); ?>">
								<input type="radio" name="logistica_close_reference_pick" data-close-reference-pick aria-label="<?php esc_attr_e( 'Ver bases de esta referencia', 'logistica' ); ?>">
								<span><?php esc_html_e( 'Ver bases', 'logistica' ); ?></span>
							</label>
							<div class="logistica-ref-title">
								<?php
								$current_nombre       = trim( (string) ( $ref['nombre'] ?? '' ) );
								$normalized_nombres   = array_map( 'strtolower', $reference_name_options );
								$current_nombre_known = '' !== $current_nombre && in_array( strtolower( $current_nombre ), $normalized_nombres, true );
								?>
								<label><?php esc_html_e( 'Referencia', 'logistica' ); ?>
									<select data-field="nombre_selector">
										<option value=""><?php esc_html_e( 'Seleccionar…', 'logistica' ); ?></option>
										<?php foreach ( $reference_name_options as $reference_name ) : ?>
											<option value="<?php echo esc_attr( $reference_name ); ?>" <?php selected( strtolower( $current_nombre ), strtolower( $reference_name ) ); ?>><?php echo esc_html( $reference_name ); ?></option>
										<?php endforeach; ?>
									</select>
									<input class="logistica-reference-name-value" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][nombre]" data-field="nombre" value="<?php echo esc_attr( $current_nombre ); ?>" <?php echo $current_nombre_known || '' === $current_nombre ? 'hidden' : ''; ?> readonly>
								</label>
								<label><?php esc_html_e( 'Variante', 'logistica' ); ?>
									<select data-field="variante_selector">
										<option value=""><?php esc_html_e( 'Seleccionar…', 'logistica' ); ?></option>
										<?php foreach ( $variant_options as $variant ) : ?>
											<option value="<?php echo esc_attr( $variant ); ?>" <?php selected( strtolower( $current_variant ), strtolower( $variant ) ); ?>><?php echo esc_html( $variant ); ?></option>
										<?php endforeach; ?>
									</select>
									<input class="logistica-variant-value" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][variante]" data-field="variante" value="<?php echo esc_attr( $current_variant ); ?>" <?php echo $current_variant_known ? 'hidden' : ''; ?> readonly>
									<span class="logistica-variant-actions">
										<button type="button" class="button" data-action="edit-close-variant" aria-pressed="false"><?php esc_html_e( 'Editar', 'logistica' ); ?></button>
										<button type="button" class="button" data-action="delete-close-variant"><?php esc_html_e( 'Eliminar', 'logistica' ); ?></button>
									</span>
								</label>
								<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][id]" data-field="id" value="<?php echo esc_attr( $ref['id'] ?? '' ); ?>">
							</div>
							<div class="logistica-ref-meta">
								<?php
								$current_type       = $ref['tipo_producto'] ?? '';
								$normalized_types   = array_map( 'strtolower', $product_type_options );
								$current_type_known = in_array( strtolower( $current_type ), $normalized_types, true );
								?>
								<label><?php esc_html_e( 'Tipo producto', 'logistica' ); ?>
									<select data-field="tipo_producto_selector">
										<option value=""><?php esc_html_e( 'Seleccionar…', 'logistica' ); ?></option>
										<?php foreach ( $product_type_options as $product_type ) : ?>
											<option value="<?php echo esc_attr( $product_type ); ?>" <?php selected( strtolower( $current_type ), strtolower( $product_type ) ); ?>><?php echo esc_html( $product_type ); ?></option>
										<?php endforeach; ?>
									</select>
									<input class="logistica-product-type-value" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][tipo_producto]" data-field="tipo_producto" value="<?php echo esc_attr( $current_type ); ?>" <?php echo $current_type_known ? 'hidden' : ''; ?> readonly>
								</label>
								<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][unidad_empaque]" data-field="unidad_empaque" value="<?php echo esc_attr( $ref['unidad_empaque'] ?? '' ); ?>">
								<label><?php esc_html_e( 'Unidades producidas', 'logistica' ); ?><input type="text" inputmode="numeric" class="logistica-units-field" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][unidades]" data-field="unidades" value="<?php echo esc_attr( $ref['unidades'] ?? '' ); ?>"></label>
								<label><?php esc_html_e( 'Plantilla fórmula', 'logistica' ); ?><input name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][formula_template]" data-field="formula_template" value="<?php echo esc_attr( $ref['formula_template'] ?? '' ); ?>"></label>
							</div>
							<p class="logistica-ref-status" data-output="reference_status"></p>
						</header>

						<div class="logistica-close-ref-empty" data-close-ref-empty hidden>
							<p><?php esc_html_e( 'Sin referencias creadas', 'logistica' ); ?></p>
						</div>

						<div class="logistica-close-ref-body" data-close-ref-body>
							<div class="logistica-close-matrix-bar">
								<span class="logistica-close-matrix-bar-label"><?php esc_html_e( 'Bloques de cálculo', 'logistica' ); ?></span>
								<div class="logistica-close-matrix-bar-actions">
									<button type="button" class="button" data-action="add-close-block"><?php esc_html_e( 'Nuevo bloque de cálculo', 'logistica' ); ?></button>
									<button type="button" class="button logistica-close-saldo-btn" data-action="add-close-saldo-block" hidden>
										<span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
										<span><?php esc_html_e( 'Añadir cajas saldo', 'logistica' ); ?></span>
									</button>
								</div>
							</div>
							<div class="logistica-close-table-wrap">
							<table class="logistica-close-matrix">
								<thead>
									<tr>
										<th><?php esc_html_e( 'Consumo por referencia', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Num Paquetes', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Und x paquete', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Total de empaque (und)', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Base', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Fórmula', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Cod', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Lote', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Consumo unidad', 'logistica' ); ?></th>
										<th><?php esc_html_e( 'Ajustado Unid/kg', 'logistica' ); ?></th>
										<th class="is-status-head"><?php esc_html_e( 'Estado', 'logistica' ); ?></th>
										<th class="is-actions-head"><?php esc_html_e( 'Acción', 'logistica' ); ?></th>
									</tr>
								</thead>
								<tbody data-close-lines>
									<?php foreach ( Logistica_Order_Closing::sort_reference_lines( $ref['lineas'] ?? array() ) as $line_index => $line ) : ?>
										<?php if ( 'caja_mediana' === ( $line['tipo'] ?? '' ) ) : ?>
											<?php continue; ?>
										<?php endif; ?>
										<?php
										if ( 'caja_saldos' === ( $line['tipo'] ?? '' ) ) {
											$line['label'] = 'Cajas saldo';
										}
										if ( 'rollos' === ( $line['tipo'] ?? '' ) ) {
											$line['label'] = 'Rollo fondo';
										}
										$is_saldo_line = 'caja_saldos' === ( $line['tipo'] ?? '' );
										$is_plastic_line = 'plastico_kg' === ( $line['tipo'] ?? '' );
										$is_roll_line = 'rollos' === ( $line['tipo'] ?? '' );
										$formula_value = Logistica_Order_Closing::default_formula_for_line( $line['tipo'] ?? '', $line['base_tipo'] ?? '' );
										$formula_label = Logistica_Order_Closing::formula_label( $formula_value );
										?>
										<tr class="<?php echo $is_plastic_line ? 'is-plastic-only' : ''; ?>" data-close-line="<?php echo esc_attr( $line['tipo'] ?? '' ); ?>">
											<td class="is-editable"><input name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][label]" data-field="label" value="<?php echo esc_attr( $line['label'] ?? '' ); ?>"></td>
											<?php if ( $is_saldo_line ) : ?>
												<td class="is-auto">
													<input type="number" step="0.001" class="logistica-readonly-field" readonly tabindex="-1" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][paquetes]" data-field="paquetes" data-saldo-auto="paquetes" value="<?php echo esc_attr( $line['paquetes'] ?? '' ); ?>" aria-label="<?php esc_attr_e( 'Paquetes de saldo (automatico)', 'logistica' ); ?>">
												</td>
												<td class="is-editable">
													<input type="number" step="0.001" min="0" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][unidades_paquete]" data-field="unidades_paquete" data-saldo-input="und" value="<?php echo esc_attr( $line['unidades_paquete'] ?? '' ); ?>"<?php echo ( ! empty( $line['saldo_und_manual'] ) || '' !== trim( (string) ( $line['unidades_paquete'] ?? '' ) ) ) ? ' data-saldo-und-manual="1"' : ''; ?> aria-label="<?php esc_attr_e( 'Unidades por paquete de cajas saldo', 'logistica' ); ?>">
													<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][saldo_und_manual]" data-field="saldo_und_manual" value="<?php echo esc_attr( ! empty( $line['saldo_und_manual'] ) || '' !== trim( (string) ( $line['unidades_paquete'] ?? '' ) ) ? '1' : '' ); ?>">
												</td>
											<?php elseif ( $is_roll_line ) : ?>
												<td class="is-auto">
													<span data-output="roll_total">-</span>
													<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][paquetes]" data-field="paquetes" value="<?php echo esc_attr( $line['paquetes'] ?? '' ); ?>">
												</td>
												<td class="is-auto">
													<span>-</span>
													<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][unidades_paquete]" data-field="unidades_paquete" value="<?php echo esc_attr( $line['unidades_paquete'] ?? '' ); ?>">
												</td>
											<?php else : ?>
												<td class="is-editable"><input type="number" step="0.001" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][paquetes]" data-field="paquetes" value="<?php echo esc_attr( $line['paquetes'] ?? '' ); ?>"></td>
												<td class="is-editable"><input type="number" step="0.001" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][unidades_paquete]" data-field="unidades_paquete" value="<?php echo esc_attr( $line['unidades_paquete'] ?? '' ); ?>"></td>
											<?php endif; ?>
											<td class="is-auto"><span data-output="cantidad_total"></span><input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][cantidad]" data-field="cantidad" value="<?php echo esc_attr( $line['cantidad'] ?? '' ); ?>"></td>
											<td class="is-editable"><select name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][base_tipo]" data-field="base_tipo">
												<?php foreach ( Logistica_Order_Closing::base_type_options() as $base_type_value => $base_type_label ) : ?>
													<option value="<?php echo esc_attr( $base_type_value ); ?>" <?php selected( $line['base_tipo'] ?? '', $base_type_value ); ?>><?php echo esc_html( $base_type_label ); ?></option>
												<?php endforeach; ?>
											</select></td>
											<td class="is-auto">
												<span class="logistica-formula-auto"><?php echo esc_html( $formula_label ); ?></span>
												<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][formula]" data-field="formula" value="<?php echo esc_attr( $formula_value ); ?>">
											</td>
											<td class="is-auto is-close-copy">
												<span class="logistica-close-copy-value" data-output="cod" tabindex="0" role="button" title="<?php esc_attr_e( 'Clic para copiar', 'logistica' ); ?>"></span>
											</td>
											<td class="is-auto is-close-copy">
												<span class="logistica-close-copy-value" data-output="lote" tabindex="0" role="button" title="<?php esc_attr_e( 'Clic para copiar', 'logistica' ); ?>"></span>
											</td>
											<td class="is-auto" data-output="unitkg"></td>
											<td class="is-auto is-close-copy">
												<span class="logistica-close-copy-value" data-output="ajustado" tabindex="0" role="button" title="<?php esc_attr_e( 'Clic para copiar', 'logistica' ); ?>"></span>
											</td>
											<td data-output="estado"></td>
											<?php logistica_close_matrix_action_cell(); ?>
											<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][tipo]" data-field="tipo" value="<?php echo esc_attr( $line['tipo'] ?? '' ); ?>">
											<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][estado_formula]" data-field="estado_formula" value="<?php echo esc_attr( $line['estado_formula'] ?? '' ); ?>">
											<input type="hidden" name="cierre[referencias][<?php echo esc_attr( $ref_index ); ?>][lineas][<?php echo esc_attr( $line_index ); ?>][base_link_id]" data-field="base_link_id" value="<?php echo esc_attr( $line['base_link_id'] ?? '' ); ?>">
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>
							</div>
						</div>
					</article>
				<?php endforeach; ?>
			</div>
		</div>
	</form>
</section>
