<?php
/**
 * Catálogo de códigos de producto para etiquetas EAN-13 e impresión de producción.
 *
 * @package Logistica
 */

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

require_once LOGISTICA_PLUGIN_DIR . 'admin/views/partials.php';

$show_etiqueta_catalog = ! logistica_is_etiqueta_settings_view();
$rows                  = $show_etiqueta_catalog ? Logistica_Label_Product_Catalog::get_all() : array();
$type_options          = Logistica_Label_Etiqueta_Tipos::get_option_labels();
$market_options        = Logistica_Label_Barcode::market_options();
$tamano_options        = Logistica_Label_Etiqueta_Tamanos::get_options();
$hidden_options_map    = Logistica_Label_Etiqueta_Option_Usage::hidden_options_client_map();
$print_settings        = Logistica_Label_Print::get_settings();
$save_action           = admin_url( 'admin-post.php' );
$redirect_base         = $show_etiqueta_catalog
	? logistica_tab_url( 'logistica-codigos-etiqueta', 'frontend' )
	: logistica_tab_url( 'logistica-codigos-etiqueta', logistica_is_config_panel() ? 'config' : 'admin' );
$export_url            = wp_nonce_url(
	add_query_arg( 'action', 'logistica_export_etiqueta_productos', admin_url( 'admin-post.php' ) ),
	'logistica_export_etiqueta_productos'
);
$status                = isset( $_GET['logistica_status'] ) ? sanitize_key( wp_unslash( $_GET['logistica_status'] ) ) : '';
$error_message         = $show_etiqueta_catalog ? get_transient( 'logistica_etiqueta_producto_error_' . get_current_user_id() ) : false;
$import_result         = $show_etiqueta_catalog && in_array( $status, array( 'imported', 'import_error' ), true )
	? get_transient( 'logistica_etiqueta_productos_import_' . get_current_user_id() )
	: false;
$filter_tipos          = array();
$filter_mercados       = array();
$filter_tamanos        = array();
$duplicate_report      = array(
	'has_duplicates' => false,
	'codigo_groups'  => 0,
	'ean_groups'     => 0,
	'row_ids'        => array(),
	'codigos'        => array(),
	'eans'           => array(),
);
$duplicate_row_ids     = array();

if ( $show_etiqueta_catalog ) {
	$duplicate_report  = Logistica_Label_Product_Catalog::get_duplicate_report( $rows );
	$duplicate_row_ids = array_fill_keys( array_map( 'intval', $duplicate_report['row_ids'] ?? array() ), true );

	foreach ( $rows as $row ) {
		if ( ! empty( $row['tipo_producto'] ) ) {
			$filter_tipos[ $row['tipo_producto'] ] = $type_options[ $row['tipo_producto'] ] ?? $row['tipo_producto'];
		}
		if ( ! empty( $row['mercado'] ) ) {
			$filter_mercados[ $row['mercado'] ] = $market_options[ $row['mercado'] ] ?? $row['mercado'];
		}
		if ( ! empty( $row['tamano'] ) ) {
			$filter_tamanos[ $row['tamano'] ] = $row['tamano'];
		}
	}

	if ( $filter_tipos ) {
		asort( $filter_tipos, SORT_NATURAL | SORT_FLAG_CASE );
	}
	if ( $filter_mercados ) {
		asort( $filter_mercados, SORT_NATURAL | SORT_FLAG_CASE );
	}
	if ( $filter_tamanos ) {
		asort( $filter_tamanos, SORT_NATURAL | SORT_FLAG_CASE );
	}
}

if ( $error_message ) {
	delete_transient( 'logistica_etiqueta_producto_error_' . get_current_user_id() );
}
if ( is_array( $import_result ) ) {
	delete_transient( 'logistica_etiqueta_productos_import_' . get_current_user_id() );
}
?>
<section class="logistica-etiqueta-catalog-board<?php echo $show_etiqueta_catalog ? '' : ' logistica-etiqueta-catalog-board--admin-settings'; ?>" data-etiqueta-catalog-board<?php echo $show_etiqueta_catalog ? '' : ' data-etiqueta-admin-settings-only="1"'; ?> data-etiqueta-post-url="<?php echo esc_url( $save_action ); ?>" data-etiqueta-redirect-base="<?php echo esc_url( $redirect_base ); ?>" data-etiqueta-delete-nonce="<?php echo esc_attr( wp_create_nonce( 'logistica_delete_etiqueta_producto' ) ); ?>" data-etiqueta-type-labels="<?php echo esc_attr( wp_json_encode( $type_options, JSON_UNESCAPED_UNICODE ) ); ?>" data-etiqueta-tipos="<?php echo esc_attr( wp_json_encode( $type_options, JSON_UNESCAPED_UNICODE ) ); ?>" data-etiqueta-mercados="<?php echo esc_attr( wp_json_encode( $market_options, JSON_UNESCAPED_UNICODE ) ); ?>" data-etiqueta-tamanos="<?php echo esc_attr( wp_json_encode( $tamano_options, JSON_UNESCAPED_UNICODE ) ); ?>" data-etiqueta-hidden-options="<?php echo esc_attr( wp_json_encode( $hidden_options_map, JSON_UNESCAPED_UNICODE ) ); ?>">
	<?php if ( ! logistica_is_tabbed_shell() ) : ?>
		<?php logistica_tab_loading_overlay( logistica_tab_loading_message( 'logistica-codigos-etiqueta' ), false ); ?>
	<?php endif; ?>

	<div class="logistica-close-toolbar logistica-etiqueta-catalog-toolbar">
		<div class="logistica-etiqueta-catalog-toolbar__intro">
			<div class="logistica-etiqueta-catalog-toolbar__badge" aria-hidden="true">
				<span class="dashicons dashicons-tag"></span>
			</div>
			<div>
				<h2><?php echo $show_etiqueta_catalog ? esc_html__( 'Códigos y etiquetas de producción', 'logistica' ) : esc_html__( 'Configuración de etiquetas de producción', 'logistica' ); ?></h2>
				<p>
					<?php
					if ( $show_etiqueta_catalog ) {
						esc_html_e( 'Configura el código EAN-13 de cada referencia e imprime las etiquetas antes de iniciar producción. Cantidad = paquetes × und por paquete.', 'logistica' );
					} else {
						esc_html_e( 'Opciones de administración para impresión de etiquetas y listas del catálogo (tipo, mercado y tamaño). El catálogo de códigos y la impresión operativa están en el panel público.', 'logistica' );
					}
					?>
				</p>
			</div>
		</div>
	</div>

	<?php if ( $show_etiqueta_catalog && 'saved' === $status ) : ?>
		<div class="notice notice-success"><p><?php esc_html_e( 'Registro guardado.', 'logistica' ); ?></p></div>
	<?php elseif ( $show_etiqueta_catalog && 'deleted' === $status ) : ?>
		<div class="notice notice-success"><p><?php esc_html_e( 'Registro eliminado.', 'logistica' ); ?></p></div>
	<?php elseif ( $show_etiqueta_catalog && 'error' === $status && $error_message ) : ?>
		<div class="notice notice-error"><p><?php echo esc_html( $error_message ); ?></p></div>
	<?php elseif ( $show_etiqueta_catalog && 'imported' === $status ) : ?>
		<div class="notice notice-success"><p><?php echo esc_html( is_array( $import_result ) && ! empty( $import_result['message'] ) ? $import_result['message'] : __( 'Datos importados desde Excel correctamente.', 'logistica' ) ); ?></p></div>
	<?php elseif ( $show_etiqueta_catalog && 'import_error' === $status ) : ?>
		<div class="notice notice-error"><p><?php echo esc_html( is_array( $import_result ) && ! empty( $import_result['message'] ) ? $import_result['message'] : __( 'No se pudo importar el archivo Excel.', 'logistica' ) ); ?></p></div>
	<?php endif; ?>

	<p class="logistica-etiqueta-catalog-status" data-etiqueta-catalog-status role="status" aria-live="polite"></p>

	<?php require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/label-print-settings.php'; ?>

	<?php if ( ! $show_etiqueta_catalog ) : ?>
		<?php require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/etiqueta-catalog-options.php'; ?>
	<?php endif; ?>

	<?php if ( $show_etiqueta_catalog ) : ?>
	<div class="logistica-etiqueta-catalog-layout">
		<div class="logistica-etiqueta-catalog-form-column">
		<form class="logistica-etiqueta-catalog-form" method="post" action="<?php echo esc_url( $save_action ); ?>" data-etiqueta-new-form>
			<input type="hidden" name="action" value="logistica_save_etiqueta_producto">
			<?php wp_nonce_field( 'logistica_save_etiqueta_producto' ); ?>
			<input type="hidden" name="redirect_to" value="<?php echo esc_url( $redirect_base ); ?>">
			<input type="hidden" name="id" value="0">

			<div class="logistica-etiqueta-catalog-section-head logistica-etiqueta-catalog-section-head--compact">
				<span class="logistica-etiqueta-catalog-section-head__icon" aria-hidden="true">
					<span class="dashicons dashicons-plus-alt2"></span>
				</span>
				<p class="logistica-etiqueta-catalog-section-head__title"><?php esc_html_e( 'Nuevo código', 'logistica' ); ?></p>
			</div>

			<label><?php esc_html_e( 'Referencia (REF)', 'logistica' ); ?>
				<input type="text" class="logistica-field-uppercase" name="referencia" data-etiqueta-referencia-field required value="" autocomplete="off" spellcheck="false" placeholder="<?php esc_attr_e( 'Ej. AGUARDILLA, VASO 8 OZ', 'logistica' ); ?>">
			</label>

			<?php
			$field_name  = 'tipo_producto';
			$field_value = '';
			$select_attr = 'data-etiqueta-tipo-select';
			$required    = true;
			require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/etiqueta-tipo-producto-field.php';
			?>

			<label><?php esc_html_e( 'Mercado', 'logistica' ); ?>
				<select name="mercado" data-etiqueta-mercado-select required>
					<?php foreach ( $market_options as $key => $label ) : ?>
						<option value="<?php echo esc_attr( $key ); ?>" <?php selected( 'NAC', $key ); ?>><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
			</label>

			<?php
			$field_name  = 'tamano';
			$field_value = '';
			$select_attr = 'data-etiqueta-tamano-select';
			$required    = true;
			require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/etiqueta-tamano-field.php';
			unset( $field_name, $field_value, $select_attr, $required );
			?>

			<label><?php esc_html_e( 'Código producto (6 dígitos)', 'logistica' ); ?>
				<input type="text" name="codigo_producto" inputmode="numeric" pattern="[0-9]{1,6}" maxlength="6" required value="" placeholder="002499">
			</label>

			<label><?php esc_html_e( 'Observaciones', 'logistica' ); ?>
				<textarea name="observaciones" rows="2"></textarea>
			</label>

			<p class="logistica-etiqueta-catalog-form__actions">
				<button type="submit" class="button button-primary" data-etiqueta-new-submit><?php esc_html_e( 'Guardar', 'logistica' ); ?></button>
			</p>
		</form>
		</div>

		<div class="logistica-etiqueta-catalog-table-wrap logistica-tapas-excel-wrap" data-excel-zoom-root="etiqueta-catalog">
			<form
				id="logistica-etiqueta-productos-excel-upload"
				class="logistica-excel-upload-form-source"
				method="post"
				action="<?php echo esc_url( $save_action ); ?>"
				enctype="multipart/form-data"
				hidden
			>
				<input type="hidden" name="action" value="logistica_import_etiqueta_productos">
				<input type="hidden" name="redirect_to" value="<?php echo esc_url( $redirect_base ); ?>">
				<?php wp_nonce_field( 'logistica_import_etiqueta_productos' ); ?>
			</form>

			<div class="logistica-etiqueta-catalog-table-wrap__head">
				<div class="logistica-etiqueta-catalog-section-head">
					<span class="logistica-etiqueta-catalog-section-head__icon" aria-hidden="true">
						<span class="dashicons dashicons-list-view"></span>
					</span>
					<div class="logistica-etiqueta-catalog-section-head__text">
						<p class="logistica-etiqueta-catalog-section-head__title"><?php esc_html_e( 'Registros', 'logistica' ); ?></p>
						<span class="logistica-etiqueta-catalog-section-head__count" data-etiqueta-catalog-total aria-label="<?php esc_attr_e( 'Total de registros', 'logistica' ); ?>"><?php echo esc_html( (string) count( $rows ) ); ?></span>
					</div>
				</div>
				<?php
				logistica_table_excel_toolbar(
					array(
						'export_url'        => $export_url,
						'import_form_id'    => 'logistica-etiqueta-productos-excel-upload',
						'import_input_id'   => 'logistica-etiqueta-productos-excel-file',
						'import_input_name' => 'etiqueta_productos_file',
						'import_data_attr'  => 'etiqueta-catalog-import-file',
						'import_action'     => 'import-etiqueta-catalog-excel',
						'show_zoom'         => true,
					)
				);
				?>
				<p class="logistica-empty-hint logistica-etiqueta-excel-hint"><?php esc_html_e( 'La plantilla Excel incluye listas desplegables en Tipo producto, Mercado y Tamaño, y valida el código de 6 dígitos. Los dígitos EAN-13 se calculan automáticamente. Vuelve a exportar tras agregar tipos o tamaños nuevos desde el backend.', 'logistica' ); ?></p>
			</div>
			<p class="logistica-empty-hint" data-etiqueta-catalog-empty-hint <?php echo empty( $rows ) ? '' : 'hidden'; ?>><?php esc_html_e( 'Aún no hay códigos registrados. Usa el formulario para agregar el primero.', 'logistica' ); ?></p>

			<div class="logistica-etiqueta-catalog-duplicate-alert" data-etiqueta-duplicate-alert <?php echo empty( $duplicate_report['has_duplicates'] ) ? 'hidden' : ''; ?>>
				<span class="dashicons dashicons-warning logistica-etiqueta-catalog-duplicate-alert__icon" aria-hidden="true"></span>
				<div>
					<strong><?php esc_html_e( 'Códigos duplicados detectados', 'logistica' ); ?></strong>
					<p data-etiqueta-duplicate-alert-text>
						<?php
						if ( ! empty( $duplicate_report['has_duplicates'] ) ) {
							$parts = array();
							if ( ! empty( $duplicate_report['codigo_groups'] ) ) {
								$parts[] = sprintf(
									/* translators: %d: number of duplicated product-code groups */
									_n( '%d código de producto repetido', '%d códigos de producto repetidos', (int) $duplicate_report['codigo_groups'], 'logistica' ),
									(int) $duplicate_report['codigo_groups']
								);
							}
							if ( ! empty( $duplicate_report['ean_groups'] ) ) {
								$parts[] = sprintf(
									/* translators: %d: number of duplicated EAN groups */
									_n( '%d EAN-13 repetido', '%d EAN-13 repetidos', (int) $duplicate_report['ean_groups'], 'logistica' ),
									(int) $duplicate_report['ean_groups']
								);
							}
							echo esc_html(
								sprintf(
									/* translators: %s: summary of duplicate types */
									__( 'Hay %s. Revise las filas resaltadas para evitar errores en los códigos de barras.', 'logistica' ),
									implode( ' y ', $parts )
								)
							);
							if ( ! empty( $duplicate_report['codigos'] ) ) {
								echo ' ';
								printf(
									/* translators: %s: comma-separated product codes */
									esc_html__( 'Códigos: %s.', 'logistica' ),
									esc_html( implode( ', ', $duplicate_report['codigos'] ) )
								);
							}
						}
						?>
					</p>
				</div>
			</div>

			<div class="logistica-tapas-filters logistica-etiqueta-catalog-filters" data-etiqueta-catalog-filters>
					<div class="logistica-tapas-filters__head">
						<?php logistica_table_filters_icon(); ?>
						<p class="logistica-tapas-filters__title"><?php esc_html_e( 'Buscar y filtrar', 'logistica' ); ?></p>
						<span class="logistica-tapas-filters__badge" data-etiqueta-catalog-filter-badge hidden><?php esc_html_e( 'Activo', 'logistica' ); ?></span>
					</div>
					<div class="logistica-tapas-filters__fields">
						<label class="logistica-tapas-filters__field logistica-tapas-filters__field--search">
							<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Buscar', 'logistica' ); ?></span>
							<input
								type="search"
								data-etiqueta-catalog-filter-search
								placeholder="<?php esc_attr_e( 'Referencia, EAN-13, código, observaciones…', 'logistica' ); ?>"
								autocomplete="off"
								spellcheck="false"
							>
						</label>
						<label class="logistica-tapas-filters__field">
							<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Tipo', 'logistica' ); ?></span>
							<select data-etiqueta-catalog-filter-tipo>
								<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
								<?php foreach ( $filter_tipos as $filter_tipo_key => $filter_tipo_label ) : ?>
									<option value="<?php echo esc_attr( $filter_tipo_key ); ?>"><?php echo esc_html( $filter_tipo_label ); ?></option>
								<?php endforeach; ?>
							</select>
						</label>
						<label class="logistica-tapas-filters__field">
							<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Mercado', 'logistica' ); ?></span>
							<select data-etiqueta-catalog-filter-mercado>
								<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
								<?php foreach ( $filter_mercados as $filter_mercado_key => $filter_mercado_label ) : ?>
									<option value="<?php echo esc_attr( $filter_mercado_key ); ?>"><?php echo esc_html( $filter_mercado_label ); ?></option>
								<?php endforeach; ?>
							</select>
						</label>
						<label class="logistica-tapas-filters__field">
							<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Tamaño', 'logistica' ); ?></span>
							<select data-etiqueta-catalog-filter-tamano>
								<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
								<?php foreach ( $filter_tamanos as $filter_tamano_value ) : ?>
									<option value="<?php echo esc_attr( $filter_tamano_value ); ?>"><?php echo esc_html( $filter_tamano_value ); ?></option>
								<?php endforeach; ?>
							</select>
						</label>
						<div class="logistica-tapas-filters__actions">
							<button type="button" class="button logistica-tapas-filters__btn" data-action="clear-etiqueta-catalog-filters" disabled>
								<?php logistica_table_filters_clear_icon(); ?>
								<?php esc_html_e( 'Limpiar filtros', 'logistica' ); ?>
							</button>
						</div>
					</div>
					<p class="logistica-tapas-filters__meta" data-etiqueta-catalog-filter-meta hidden></p>
				</div>

				<p class="logistica-etiqueta-catalog-filter-empty" data-etiqueta-catalog-filter-empty hidden>
					<?php esc_html_e( 'Ningún registro coincide con la búsqueda o los filtros.', 'logistica' ); ?>
				</p>

				<div class="logistica-etiqueta-catalog-table-card">
					<div class="logistica-etiqueta-catalog-scroll" data-etiqueta-catalog-scroll tabindex="0">
						<table class="widefat striped logistica-etiqueta-catalog-table">
							<thead>
								<tr>
									<th scope="col"><?php esc_html_e( 'Referencia', 'logistica' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Tipo', 'logistica' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Mercado', 'logistica' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Tamaño', 'logistica' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Cód. producto', 'logistica' ); ?></th>
									<th scope="col"><?php esc_html_e( 'EAN-13', 'logistica' ); ?></th>
									<th scope="col"><?php esc_html_e( 'Observaciones', 'logistica' ); ?></th>
									<th class="is-actions-head" scope="col"><?php esc_html_e( 'Acción', 'logistica' ); ?></th>
								</tr>
							</thead>
							<tbody data-etiqueta-catalog-rows>
						<?php foreach ( $rows as $row ) : ?>
							<?php
							$ean      = Logistica_Label_Barcode::build_ean13( $row['tipo_producto'], $row['mercado'], $row['codigo_producto'] );
							$ean_text = is_wp_error( $ean ) ? '—' : $ean;
							$tipo_label = $type_options[ $row['tipo_producto'] ] ?? $row['tipo_producto'];
							$producto_label = Logistica_Label_Product_Catalog::build_producto_label( $tipo_label, (string) $row['tamano'] );
							$observaciones_text = trim( (string) ( $row['observaciones'] ?? '' ) );
							$hidden_issues      = Logistica_Label_Etiqueta_Option_Usage::row_hidden_issues( $row );
							$hidden_hint        = Logistica_Label_Etiqueta_Option_Usage::row_hidden_hint_message( $hidden_issues );
							$tipo_hidden        = Logistica_Label_Etiqueta_Option_Usage::is_hidden_kind( 'tipo', (string) $row['tipo_producto'] );
							$mercado_hidden     = Logistica_Label_Etiqueta_Option_Usage::is_hidden_kind( 'mercado', (string) $row['mercado'] );
							$tamano_hidden      = Logistica_Label_Etiqueta_Option_Usage::is_hidden_kind( 'tamano', (string) $row['tamano'] );
							$is_duplicate       = isset( $duplicate_row_ids[ (int) $row['id'] ] );
							$mercado_label      = (string) ( $market_options[ $row['mercado'] ] ?? $row['mercado'] );
							$row_classes        = array_filter(
								array(
									! empty( $hidden_issues ) ? 'logistica-etiqueta-catalog-row--hidden-option' : '',
									$is_duplicate ? 'logistica-etiqueta-catalog-row--duplicate' : '',
								)
							);
							$row_title_parts    = array();
							if ( $is_duplicate ) {
								$row_title_parts[] = __( 'Código o EAN-13 duplicado. Revisa este registro para evitar errores en códigos de barras.', 'logistica' );
							}
							if ( $hidden_hint ) {
								$row_title_parts[] = $hidden_hint;
							}
							$row_title = implode( ' ', $row_title_parts );
							$row_search = strtolower(
								implode(
									' ',
									array_filter(
										array(
											$row['referencia'],
											$tipo_label,
											$producto_label,
											$row['mercado'],
											$market_options[ $row['mercado'] ] ?? '',
											$row['tamano'],
											$row['codigo_producto'],
											$ean_text,
											$observaciones_text,
										)
									)
								)
							);
							?>
							<tr
								class="<?php echo esc_attr( implode( ' ', $row_classes ) ); ?>"
								data-etiqueta-row
								data-catalog-id="<?php echo esc_attr( (string) (int) $row['id'] ); ?>"
								data-referencia="<?php echo esc_attr( $row['referencia'] ); ?>"
								data-tipo="<?php echo esc_attr( $row['tipo_producto'] ); ?>"
								data-tipo-label="<?php echo esc_attr( $tipo_label ); ?>"
								data-mercado="<?php echo esc_attr( $row['mercado'] ); ?>"
								data-tamano="<?php echo esc_attr( $row['tamano'] ); ?>"
								data-producto="<?php echo esc_attr( $producto_label ); ?>"
								data-barcode="<?php echo esc_attr( $ean_text ); ?>"
								data-codigo-producto="<?php echo esc_attr( $row['codigo_producto'] ); ?>"
								data-etiqueta-search="<?php echo esc_attr( $row_search ); ?>"
								data-has-hidden-options="<?php echo ! empty( $hidden_issues ) ? '1' : '0'; ?>"
								data-etiqueta-duplicate="<?php echo $is_duplicate ? '1' : '0'; ?>"
								<?php if ( $row_title ) : ?>
									title="<?php echo esc_attr( $row_title ); ?>"
								<?php endif; ?>
								<?php if ( $hidden_hint ) : ?>
									data-hidden-options-hint="<?php echo esc_attr( $hidden_hint ); ?>"
									tabindex="0"
								<?php endif; ?>
							>
								<td class="logistica-etiqueta-catalog-ref-cell">
									<?php echo esc_html( $row['referencia'] ); ?>
									<?php if ( $hidden_hint ) : ?>
										<span class="logistica-etiqueta-catalog-row-tooltip" role="tooltip"><?php echo esc_html( $hidden_hint ); ?></span>
									<?php endif; ?>
								</td>
								<td><?php echo $tipo_hidden ? '<span class="logistica-etiqueta-catalog-cell--hidden" title="' . esc_attr__( 'Tipo oculto del catálogo', 'logistica' ) . '">' . esc_html( $tipo_label ) . '</span>' : esc_html( $tipo_label ); ?></td>
								<td><?php echo $mercado_hidden ? '<span class="logistica-etiqueta-catalog-cell--hidden" title="' . esc_attr__( 'Mercado oculto del catálogo', 'logistica' ) . '">' . esc_html( $mercado_label ) . '</span>' : esc_html( $mercado_label ); ?></td>
								<td><?php echo $tamano_hidden ? '<span class="logistica-etiqueta-catalog-cell--hidden" title="' . esc_attr__( 'Tamaño oculto del catálogo', 'logistica' ) . '">' . esc_html( $row['tamano'] ?: '—' ) . '</span>' : esc_html( $row['tamano'] ?: '—' ); ?></td>
								<td><code><?php echo esc_html( $row['codigo_producto'] ); ?></code></td>
								<td><code><?php echo esc_html( $ean_text ); ?></code></td>
								<td class="logistica-etiqueta-catalog-observaciones-cell"<?php echo '' !== $observaciones_text ? ' title="' . esc_attr( $observaciones_text ) . '"' : ''; ?>><?php echo esc_html( '' !== $observaciones_text ? $observaciones_text : '—' ); ?></td>
								<td class="logistica-etiqueta-catalog-actions-cell">
									<div class="logistica-etiqueta-catalog-actions">
										<button type="button" class="button button-small logistica-table-icon-btn logistica-etiqueta-catalog-btn-print logistica-label-print-btn" data-action="print-production-label" aria-label="<?php esc_attr_e( 'Imprimir etiqueta', 'logistica' ); ?>" title="<?php esc_attr_e( 'Imprimir etiqueta', 'logistica' ); ?>">
											<span class="dashicons dashicons-printer" aria-hidden="true"></span>
										</button>
										<button type="button" class="button button-small logistica-table-icon-btn logistica-etiqueta-catalog-btn-edit" data-action="edit-etiqueta-catalog" data-catalog-id="<?php echo esc_attr( (string) (int) $row['id'] ); ?>" aria-label="<?php esc_attr_e( 'Editar', 'logistica' ); ?>" title="<?php esc_attr_e( 'Editar', 'logistica' ); ?>">
											<span class="dashicons dashicons-edit" aria-hidden="true"></span>
										</button>
										<form method="post" action="<?php echo esc_url( $save_action ); ?>" class="logistica-inline-delete-form" onsubmit="return confirm('<?php echo esc_js( __( '¿Eliminar este código?', 'logistica' ) ); ?>');">
											<input type="hidden" name="action" value="logistica_delete_etiqueta_producto">
											<?php wp_nonce_field( 'logistica_delete_etiqueta_producto' ); ?>
											<input type="hidden" name="redirect_to" value="<?php echo esc_url( $redirect_base ); ?>">
											<input type="hidden" name="id" value="<?php echo esc_attr( (string) (int) $row['id'] ); ?>">
											<button type="submit" class="button button-small logistica-table-icon-btn logistica-etiqueta-catalog-btn-delete" aria-label="<?php esc_attr_e( 'Eliminar', 'logistica' ); ?>" title="<?php esc_attr_e( 'Eliminar', 'logistica' ); ?>">
												<span class="dashicons dashicons-trash" aria-hidden="true"></span>
											</button>
										</form>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
							</tbody>
						</table>
					</div>
					<?php logistica_table_pagination( 'etiqueta-catalog' ); ?>
				</div>
		</div>
	</div>

	<div class="logistica-label-print-modal logistica-etiqueta-edit-modal" data-etiqueta-edit-modal hidden aria-hidden="true">
		<div class="logistica-label-print-modal__backdrop" data-etiqueta-edit-close></div>
		<div class="logistica-label-print-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="logistica-etiqueta-edit-title">
			<header class="logistica-label-print-modal__head">
				<h3 id="logistica-etiqueta-edit-title"><?php esc_html_e( 'Editar código', 'logistica' ); ?></h3>
				<button type="button" class="logistica-label-print-modal__close" data-etiqueta-edit-close aria-label="<?php esc_attr_e( 'Cerrar', 'logistica' ); ?>">&times;</button>
			</header>
			<form class="logistica-label-print-modal__body logistica-etiqueta-edit-form" data-etiqueta-edit-form>
				<div class="logistica-label-print-modal__scroll">
					<input type="hidden" name="id" data-etiqueta-edit-field="id" value="">

					<div class="logistica-etiqueta-hidden-options-alert" data-etiqueta-hidden-options-alert hidden>
						<p class="logistica-etiqueta-hidden-options-alert__title"><?php esc_html_e( 'Opciones ocultas en este código', 'logistica' ); ?></p>
						<p class="logistica-etiqueta-hidden-options-alert__hint"><?php esc_html_e( 'Estos valores ya no están en las listas del catálogo. Restáuralos o cámbialos por una opción disponible antes de guardar.', 'logistica' ); ?></p>
						<ul class="logistica-etiqueta-hidden-options-alert__list" data-etiqueta-hidden-options-list></ul>
					</div>

					<div class="logistica-label-print-modal__grid logistica-etiqueta-edit-form__grid">
						<label><?php esc_html_e( 'Referencia (REF)', 'logistica' ); ?>
							<input type="text" class="logistica-field-uppercase" name="referencia" data-etiqueta-edit-field="referencia" data-etiqueta-referencia-field required autocomplete="off" spellcheck="false" placeholder="<?php esc_attr_e( 'Ej. AGUARDILLA, VASO 8 OZ', 'logistica' ); ?>">
						</label>

						<?php
						$field_name  = 'tipo_producto';
						$field_value = '';
						$select_attr = 'data-etiqueta-tipo-select data-etiqueta-edit-field="tipo_producto"';
						$required    = true;
						require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/etiqueta-tipo-producto-field.php';
						?>

						<label><?php esc_html_e( 'Mercado', 'logistica' ); ?>
							<select name="mercado" data-etiqueta-mercado-select data-etiqueta-edit-field="mercado" required>
								<?php foreach ( $market_options as $key => $label ) : ?>
									<option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $label ); ?></option>
								<?php endforeach; ?>
							</select>
						</label>

						<?php
						$field_name  = 'tamano';
						$field_value = '';
						$select_attr = 'data-etiqueta-tamano-select data-etiqueta-edit-field="tamano"';
						$required    = true;
						require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/etiqueta-tamano-field.php';
						?>

						<label><?php esc_html_e( 'Código producto (6 dígitos)', 'logistica' ); ?>
							<input type="text" name="codigo_producto" data-etiqueta-edit-field="codigo_producto" inputmode="numeric" pattern="[0-9]{1,6}" maxlength="6" required placeholder="002499">
						</label>
					</div>

					<label class="logistica-etiqueta-edit-form__obs"><?php esc_html_e( 'Observaciones', 'logistica' ); ?>
						<textarea name="observaciones" data-etiqueta-edit-field="observaciones" rows="2"></textarea>
					</label>

					<p class="logistica-etiqueta-preview" data-etiqueta-edit-ean-preview hidden>
						<strong><?php esc_html_e( 'Vista previa EAN-13:', 'logistica' ); ?></strong>
						<code data-etiqueta-edit-ean-value></code>
					</p>

					<p class="logistica-label-print-modal__status" data-etiqueta-edit-status role="status"></p>
				</div>
				<footer class="logistica-label-print-modal__foot">
					<button type="button" class="button" data-etiqueta-edit-close><?php esc_html_e( 'Cancelar', 'logistica' ); ?></button>
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Guardar cambios', 'logistica' ); ?></button>
				</footer>
			</form>
		</div>
	</div>

	<div class="logistica-label-print-modal logistica-etiqueta-print-modal" data-label-print-modal hidden aria-hidden="true">
		<div class="logistica-label-print-modal__backdrop" data-label-print-close></div>
		<div class="logistica-label-print-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="logistica-label-print-title">
			<header class="logistica-label-print-modal__head">
				<div>
					<h3 id="logistica-label-print-title"><?php esc_html_e( 'Imprimir etiqueta de producción', 'logistica' ); ?></h3>
					<p class="logistica-label-print-modal__ref" data-label-print-ref-summary></p>
				</div>
				<button type="button" class="logistica-label-print-modal__close" data-label-print-close aria-label="<?php esc_attr_e( 'Cerrar', 'logistica' ); ?>">&times;</button>
			</header>
			<form class="logistica-label-print-modal__body" data-label-print-form>
				<div class="logistica-label-print-modal__scroll">
					<input type="hidden" data-label-field="catalog_id" value="">

					<div class="logistica-prod-label-preview-wrap logistica-etiqueta-label-preview-wrap" data-label-visual-preview>
						<div data-label-visual-preview-mount></div>
					</div>

					<div class="logistica-label-print-modal__barcode" data-label-barcode-preview>
						<strong><?php esc_html_e( 'Código EAN-13', 'logistica' ); ?></strong>
						<span class="logistica-label-print-modal__segments" data-label-barcode-segments></span>
					</div>

					<fieldset class="logistica-label-print-modal__section">
						<legend><?php esc_html_e( 'Logo de etiqueta', 'logistica' ); ?></legend>
						<p class="logistica-label-print-modal__hint"><?php esc_html_e( 'Usa imagen o texto en la esquina superior izquierda de la etiqueta.', 'logistica' ); ?></p>
						<div class="logistica-label-logo-settings__mode logistica-label-print-modal__logo-mode">
							<label class="logistica-label-logo-settings__radio">
								<input type="radio" name="logo_mode" value="text" data-label-field="logo_mode">
								<?php esc_html_e( 'Texto', 'logistica' ); ?>
							</label>
							<label class="logistica-label-logo-settings__radio">
								<input type="radio" name="logo_mode" value="image" data-label-field="logo_mode" checked>
								<?php esc_html_e( 'Imagen', 'logistica' ); ?>
							</label>
						</div>
						<div class="logistica-label-print-modal__grid logistica-label-logo-settings__panel" data-label-logo-panel="text" hidden>
							<label><?php esc_html_e( 'Línea principal', 'logistica' ); ?><input type="text" data-label-field="logo_text_line1" placeholder="<?php esc_attr_e( 'Ej. nombre de marca', 'logistica' ); ?>"></label>
							<label><?php esc_html_e( 'Línea secundaria', 'logistica' ); ?><input type="text" data-label-field="logo_text_line2" placeholder="<?php esc_attr_e( 'Ej. subtítulo o lema', 'logistica' ); ?>"></label>
							<div class="logistica-label-logo-history" data-label-logo-history="text" hidden>
								<p class="logistica-label-logo-history__title"><?php esc_html_e( 'Historial de textos usados (guardado al imprimir)', 'logistica' ); ?></p>
								<div class="logistica-label-logo-history__list" data-label-logo-history-list="text" role="list"></div>
							</div>
						</div>
						<div class="logistica-label-logo-settings__panel" data-label-logo-panel="image">
							<label><?php esc_html_e( 'URL imagen', 'logistica' ); ?>
								<span class="logistica-label-logo-settings__url-row">
									<input type="url" data-label-field="logo_url" value="<?php echo esc_attr( Logistica_Label_Print::default_logo_url() ); ?>" placeholder="https://.../logo.svg">
									<button type="button" class="button" data-label-logo-media><?php esc_html_e( 'Biblioteca', 'logistica' ); ?></button>
								</span>
							</label>
							<div class="logistica-label-logo-settings__preview" data-label-logo-preview></div>
							<div class="logistica-label-logo-history" data-label-logo-history="image" hidden>
								<p class="logistica-label-logo-history__title"><?php esc_html_e( 'Historial de imágenes usadas (guardado al imprimir)', 'logistica' ); ?></p>
								<div class="logistica-label-logo-history__list" data-label-logo-history-list="image" role="list"></div>
							</div>
						</div>
					</fieldset>

					<fieldset class="logistica-label-print-modal__section">
						<legend><?php esc_html_e( 'Datos de la orden', 'logistica' ); ?></legend>
						<div class="logistica-label-print-modal__grid">
							<label><?php esc_html_e( 'Cliente', 'logistica' ); ?><input type="text" name="cliente" data-label-field="cliente"></label>
							<label><?php esc_html_e( 'Producto', 'logistica' ); ?><input type="text" name="producto" data-label-field="producto"></label>
							<label><?php esc_html_e( 'Referencia (REF)', 'logistica' ); ?><input type="text" name="ref" data-label-field="ref" readonly class="logistica-readonly-field"></label>
							<label><?php esc_html_e( 'OP', 'logistica' ); ?><input type="text" name="op" data-label-field="op"></label>
							<label class="logistica-label-print-modal__date"><?php esc_html_e( 'Fecha', 'logistica' ); ?>
								<span class="logistica-label-print-modal__date-wrap">
									<input type="text" name="fecha" data-label-field="fecha" placeholder="dd.mm.aa" maxlength="8" inputmode="numeric" autocomplete="off">
									<input type="date" data-label-fecha-native tabindex="-1" aria-hidden="true">
									<button type="button" class="logistica-label-print-modal__date-btn" data-label-fecha-picker aria-label="<?php esc_attr_e( 'Abrir calendario', 'logistica' ); ?>">
										<span class="dashicons dashicons-calendar-alt" aria-hidden="true"></span>
									</button>
								</span>
							</label>
							<label><?php esc_html_e( 'Operario', 'logistica' ); ?><input type="text" name="operario" data-label-field="operario" maxlength="8"></label>
						</div>
					</fieldset>

					<fieldset class="logistica-label-print-modal__section">
						<legend><?php esc_html_e( 'Etiquetas por caja', 'logistica' ); ?></legend>
						<p class="logistica-label-print-modal__hint"><?php esc_html_e( 'Cantidad = paquetes × und por paquete. Ejemplo: 10 paquetes × 50 und = 500 und.', 'logistica' ); ?></p>
						<div class="logistica-label-print-modal__grid">
							<label><?php esc_html_e( 'Paquetes por caja', 'logistica' ); ?><input type="text" name="paquetes" inputmode="numeric" data-label-field="paquetes" required></label>
							<label><?php esc_html_e( 'Und por paquete', 'logistica' ); ?><input type="text" name="und_por_paquete" inputmode="numeric" data-label-field="und_por_paquete" required></label>
							<label><?php esc_html_e( 'Cantidad (calculada)', 'logistica' ); ?><input type="text" data-label-field="cantidad_calculada" readonly class="logistica-readonly-field" tabindex="-1"></label>
							<label><?php esc_html_e( 'Nº de cajas a etiquetar', 'logistica' ); ?><input type="number" name="num_cajas" min="0" step="1" data-label-field="num_cajas" value="1"></label>
							<label><?php esc_html_e( 'Caja inicial Nº', 'logistica' ); ?><input type="number" name="caja_inicio" min="1" step="1" data-label-field="caja_inicio" value="1"></label>
						</div>
						<div class="logistica-label-pack-history" data-label-pack-history hidden>
							<p class="logistica-label-pack-history__title"><?php esc_html_e( 'Historial reciente (guardado al imprimir)', 'logistica' ); ?></p>
							<div class="logistica-label-pack-history__list" data-label-pack-history-list role="list"></div>
						</div>
					</fieldset>

					<fieldset class="logistica-label-print-modal__section">
						<legend><?php esc_html_e( 'Etiqueta saldo (fin de producción)', 'logistica' ); ?></legend>
						<p class="logistica-label-print-modal__hint"><?php esc_html_e( 'Reserva una etiqueta con los paquetes restantes al cerrar la producción. Usa las mismas unidades por paquete.', 'logistica' ); ?></p>
						<label class="logistica-label-print-modal__check">
							<input type="checkbox" name="include_saldo" data-label-field="include_saldo" value="1">
							<?php esc_html_e( 'Incluir etiqueta saldo', 'logistica' ); ?>
						</label>
						<label class="logistica-label-print-modal__check">
							<input type="checkbox" name="saldo_sin_cantidad" data-label-field="saldo_sin_cantidad" value="1" disabled>
							<?php esc_html_e( 'Saldo sin cantidad (dejar en blanco para llenar a mano)', 'logistica' ); ?>
						</label>
						<div class="logistica-label-print-modal__grid logistica-label-print-modal__saldo-grid" data-label-saldo-cantidad-wrap>
							<label><?php esc_html_e( 'Paquetes saldo', 'logistica' ); ?><input type="text" name="paquetes_saldo" inputmode="numeric" data-label-field="paquetes_saldo" disabled></label>
							<label><?php esc_html_e( 'Cantidad saldo (calculada)', 'logistica' ); ?><input type="text" data-label-field="cantidad_saldo_calculada" readonly class="logistica-readonly-field" tabindex="-1"></label>
						</div>
					</fieldset>

					<div class="logistica-label-print-modal__total-produccion" data-label-total-produccion-wrap>
						<div class="logistica-label-print-modal__total-produccion__copy">
							<strong><?php esc_html_e( 'Total producción', 'logistica' ); ?></strong>
							<span class="logistica-label-print-modal__hint" data-label-total-produccion-detail></span>
						</div>
						<div class="logistica-label-print-modal__total-produccion__value" data-label-field="total_produccion">—</div>
					</div>

				</div>
				<footer class="logistica-label-print-modal__foot">
					<p class="logistica-label-print-modal__status" data-label-print-status role="status"></p>
					<div class="logistica-label-print-modal__foot-actions">
						<button type="button" class="button" data-label-print-preview-label><?php esc_html_e( 'Vista previa', 'logistica' ); ?></button>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Imprimir', 'logistica' ); ?></button>
					</div>
				</footer>
			</form>
		</div>
	</div>
	<?php endif; ?>
</section>
