<?php
/**
 * Maestro de caracteristicas por codigo para cierre de ordenes.
 *
 * @package Logistica
 */

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

$caracteristicas_rows = Logistica_Order_Closing_Characteristics::get_all();
$tipo_options         = Logistica_Order_Closing_Characteristics::tipo_options();
$edit_id              = isset( $_GET['edit_id'] ) ? (int) wp_unslash( $_GET['edit_id'] ) : 0;
$edit_row             = null;

if ( $edit_id > 0 ) {
	foreach ( $caracteristicas_rows as $caracteristica_row ) {
		if ( (int) ( $caracteristica_row['id'] ?? 0 ) === $edit_id ) {
			$edit_row = $caracteristica_row;
			break;
		}
	}
}

$save_action   = admin_url( 'admin-post.php' );
$redirect_base = logistica_tab_url( 'logistica-cierre-caracteristicas', is_admin() ? 'admin' : 'frontend' );
$total_rows    = count( $caracteristicas_rows );
$export_url    = wp_nonce_url(
	add_query_arg( 'action', 'logistica_export_cierre_caracteristicas', admin_url( 'admin-post.php' ) ),
	'logistica_export_cierre_caracteristicas'
);
$import_action = admin_url( 'admin-post.php' );

$filter_descripciones = array();
$filter_tipos         = array();

foreach ( $caracteristicas_rows as $caracteristica_row ) {
	$descripcion = trim( (string) ( $caracteristica_row['descripcion'] ?? '' ) );
	$tipo        = sanitize_key( $caracteristica_row['tipo'] ?? '' );

	if ( '' !== $descripcion ) {
		$filter_descripciones[ $descripcion ] = $descripcion;
	}

	if ( '' !== $tipo ) {
		$filter_tipos[ $tipo ] = $tipo_options[ $tipo ] ?? $tipo;
	}
}

natcasesort( $filter_descripciones );
natcasesort( $filter_tipos );

$form_tipo          = sanitize_key( $edit_row['tipo'] ?? 'cajas' );
$form_fields        = Logistica_Order_Closing_Characteristics::fields_for_tipo( $form_tipo );
$form_field_labels  = Logistica_Order_Closing_Characteristics::field_labels_for_tipo( $form_tipo );
$form_shows_largo   = in_array( 'largo', $form_fields, true );
$form_shows_ancho   = in_array( 'ancho', $form_fields, true );
$form_shows_alto    = in_array( 'alto', $form_fields, true );
$form_shows_clave   = in_array( 'clave', $form_fields, true );
$form_shows_calibre = in_array( 'calibre', $form_fields, true );
?>
<section class="logistica-cierre-caracteristicas-board" data-cierre-caracteristicas-board data-cierre-car-tipo-labels="<?php echo esc_attr( wp_json_encode( $tipo_options, JSON_UNESCAPED_UNICODE ) ); ?>" data-cierre-car-field-map="<?php
	$cierre_car_field_map  = array();
	$cierre_car_label_map  = array();
	foreach ( array_keys( $tipo_options ) as $cierre_car_tipo_key ) {
		$cierre_car_field_map[ $cierre_car_tipo_key ] = Logistica_Order_Closing_Characteristics::fields_for_tipo( $cierre_car_tipo_key );
		$cierre_car_label_map[ $cierre_car_tipo_key ] = Logistica_Order_Closing_Characteristics::field_labels_for_tipo( $cierre_car_tipo_key );
	}
	echo esc_attr( wp_json_encode( $cierre_car_field_map, JSON_UNESCAPED_UNICODE ) );
?>" data-cierre-car-label-map="<?php echo esc_attr( wp_json_encode( $cierre_car_label_map, JSON_UNESCAPED_UNICODE ) ); ?>">
	<?php if ( ! logistica_is_tabbed_shell() ) : ?>
		<?php logistica_tab_loading_overlay( logistica_tab_loading_message( 'logistica-cierre-caracteristicas' ) ); ?>
	<?php endif; ?>
	<div class="logistica-close-toolbar logistica-cierre-caracteristicas-toolbar">
		<div class="logistica-cierre-caracteristicas-toolbar__intro">
			<div class="logistica-cierre-caracteristicas-toolbar__badge" aria-hidden="true">
				<span class="dashicons dashicons-editor-table"></span>
			</div>
			<div>
				<h2><?php esc_html_e( 'Características por código', 'logistica' ); ?></h2>
				<p><?php esc_html_e( 'Asigna dimensiones, clave y tipo de base por código. Cierre de órdenes toma estos valores automáticamente cuando una base use el mismo código.', 'logistica' ); ?></p>
			</div>
		</div>
	</div>

	<div class="logistica-cierre-caracteristicas-stats">
		<div class="logistica-cierre-caracteristicas-stat">
			<span class="logistica-cierre-caracteristicas-stat__value" data-cierre-car-total><?php echo esc_html( (string) $total_rows ); ?></span>
			<span class="logistica-cierre-caracteristicas-stat__label"><?php esc_html_e( 'Códigos', 'logistica' ); ?></span>
		</div>
	</div>

	<form
		id="logistica-cierre-caracteristicas-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_caracteristicas">
		<input type="hidden" name="redirect_to" value="<?php echo esc_url( $redirect_base ); ?>">
		<?php wp_nonce_field( 'logistica_import_cierre_caracteristicas' ); ?>
	</form>

	<div class="logistica-tapas-excel-wrap logistica-cierre-caracteristicas-table-wrap" data-excel-zoom-root="cierre-caracteristicas">
		<?php
		logistica_table_excel_view_header(
			__( 'Consulta y filtra los códigos registrados. Pulsa editar en cada fila para actualizar dimensiones y clave.', 'logistica' )
		);
		logistica_excel_table_zoom_toolbar();
		?>
		<div class="logistica-tapas-filters" data-cierre-car-filters>
			<div class="logistica-tapas-filters__head">
				<?php logistica_table_filters_icon(); ?>
				<p class="logistica-tapas-filters__title"><?php esc_html_e( 'Filtrar tabla', 'logistica' ); ?></p>
				<span class="logistica-tapas-filters__badge" data-cierre-car-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-cierre-car-filter-search
						placeholder="<?php esc_attr_e( 'Código, descripción o clave...', 'logistica' ); ?>"
						autocomplete="off"
						spellcheck="false"
					>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Descripción', 'logistica' ); ?></span>
					<select data-cierre-car-filter-descripcion>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<?php foreach ( $filter_descripciones as $filter_descripcion ) : ?>
							<option value="<?php echo esc_attr( $filter_descripcion ); ?>"><?php echo esc_html( $filter_descripcion ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Base', 'logistica' ); ?></span>
					<select data-cierre-car-filter-tipo>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<?php foreach ( $filter_tipos as $filter_tipo => $filter_tipo_label ) : ?>
							<option value="<?php echo esc_attr( $filter_tipo ); ?>"><?php echo esc_html( $filter_tipo_label ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<div class="logistica-tapas-filters__actions">
					<button type="button" class="button logistica-tapas-filters__btn" data-action="clear-cierre-car-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-cierre-car-filter-meta hidden></p>
		</div>
		<?php
		logistica_table_excel_toolbar(
			array(
				'export_url'        => $export_url,
				'import_form_id'    => 'logistica-cierre-caracteristicas-excel-upload',
				'import_input_id'   => 'logistica-cierre-caracteristicas-excel-file',
				'import_input_name' => 'cierre_caracteristicas_file',
				'import_data_attr'  => 'cierre-car-import-file',
				'import_action'     => 'import-cierre-car-excel',
				'show_zoom'         => false,
			)
		);
		logistica_table_status_legend(
			array(
				array(
					'class' => 'is-car-legend-complete',
					'label' => __( 'Completo', 'logistica' ),
				),
				array(
					'class' => 'is-car-legend-incomplete',
					'label' => __( 'Faltan datos', 'logistica' ),
				),
			)
		);
		logistica_table_sheet_actions( __( 'Añadir referencia', 'logistica' ), 'cierre-car-focus-form' );
		?>

		<div
			class="logistica-cierre-caracteristicas-form-card"
			data-cierre-car-form-card
			<?php echo $edit_row ? '' : 'hidden'; ?>
		>
			<form class="logistica-cierre-caracteristicas__form" method="post" action="<?php echo esc_url( $save_action ); ?>" data-cierre-caracteristicas-form>
				<input type="hidden" name="action" value="logistica_save_cierre_caracteristica">
				<input type="hidden" name="row_id" value="<?php echo esc_attr( $edit_row ? (string) ( $edit_row['id'] ?? '' ) : '' ); ?>">
				<input type="hidden" name="redirect_to" value="<?php echo esc_url( $redirect_base ); ?>">
				<?php wp_nonce_field( 'logistica_save_cierre_caracteristica' ); ?>

				<div class="logistica-cierre-caracteristicas__grid">
					<label class="logistica-cierre-caracteristicas-filter">
						<span><?php esc_html_e( 'Código', 'logistica' ); ?></span>
						<input type="text" name="codigo" data-cierre-car-field required autocomplete="off" spellcheck="false" value="<?php echo esc_attr( $edit_row['codigo'] ?? '' ); ?>" <?php echo $edit_row ? 'readonly class="logistica-readonly-field"' : ''; ?>>
					</label>
					<label class="logistica-cierre-caracteristicas-filter">
						<span><?php esc_html_e( 'Descripción', 'logistica' ); ?></span>
						<input type="text" name="descripcion" data-cierre-car-field autocomplete="off" value="<?php echo esc_attr( $edit_row['descripcion'] ?? '' ); ?>">
					</label>
					<label class="logistica-cierre-caracteristicas-filter">
						<span><?php esc_html_e( 'Base', 'logistica' ); ?></span>
						<select name="tipo" data-cierre-car-field data-cierre-car-tipo>
							<?php foreach ( $tipo_options as $tipo_value => $tipo_label ) : ?>
								<option value="<?php echo esc_attr( $tipo_value ); ?>" <?php selected( $edit_row['tipo'] ?? 'cajas', $tipo_value ); ?>><?php echo esc_html( $tipo_label ); ?></option>
							<?php endforeach; ?>
						</select>
					</label>
					<label class="logistica-cierre-caracteristicas-filter<?php echo $form_shows_largo ? '' : ' is-base-field-hidden'; ?>" data-cierre-car-dim="largo" <?php echo $form_shows_largo ? '' : 'hidden'; ?>>
						<span data-cierre-car-dim-label="largo"><?php echo esc_html( $form_field_labels['largo'] ?? __( 'Largo (mm)', 'logistica' ) ); ?></span>
						<input type="number" step="0.01" name="largo" data-cierre-car-field inputmode="decimal" value="<?php echo esc_attr( $edit_row['largo'] ?? '' ); ?>">
					</label>
					<label class="logistica-cierre-caracteristicas-filter<?php echo $form_shows_ancho ? '' : ' is-base-field-hidden'; ?>" data-cierre-car-dim="ancho" <?php echo $form_shows_ancho ? '' : 'hidden'; ?>>
						<span data-cierre-car-dim-label="ancho"><?php echo esc_html( $form_field_labels['ancho'] ?? __( 'Ancho (mm)', 'logistica' ) ); ?></span>
						<input type="number" step="0.01" name="ancho" data-cierre-car-field inputmode="decimal" value="<?php echo esc_attr( $edit_row['ancho'] ?? '' ); ?>">
					</label>
					<label class="logistica-cierre-caracteristicas-filter<?php echo $form_shows_alto ? '' : ' is-base-field-hidden'; ?>" data-cierre-car-dim="alto" <?php echo $form_shows_alto ? '' : 'hidden'; ?>>
						<span data-cierre-car-dim-label="alto"><?php echo esc_html( $form_field_labels['alto'] ?? __( 'Alto (mm)', 'logistica' ) ); ?></span>
						<input type="number" step="0.01" name="alto" data-cierre-car-field inputmode="decimal" value="<?php echo esc_attr( $edit_row['alto'] ?? '' ); ?>">
					</label>
					<label class="logistica-cierre-caracteristicas-filter<?php echo $form_shows_clave ? '' : ' is-base-field-hidden'; ?>" data-cierre-car-dim="clave" <?php echo $form_shows_clave ? '' : 'hidden'; ?>>
						<span data-cierre-car-dim-label="clave"><?php echo esc_html( $form_field_labels['clave'] ?? __( 'Clave', 'logistica' ) ); ?></span>
						<input type="text" name="clave" data-cierre-car-field autocomplete="off" value="<?php echo esc_attr( $edit_row['clave'] ?? '' ); ?>">
					</label>
					<label class="logistica-cierre-caracteristicas-filter<?php echo $form_shows_calibre ? '' : ' is-base-field-hidden'; ?>" data-cierre-car-dim="calibre" <?php echo $form_shows_calibre ? '' : 'hidden'; ?>>
						<span data-cierre-car-dim-label="calibre"><?php echo esc_html( $form_field_labels['calibre'] ?? __( 'Calibre (mm)', 'logistica' ) ); ?></span>
						<input type="number" step="0.01" name="calibre" data-cierre-car-field inputmode="decimal" value="<?php echo esc_attr( $edit_row['calibre'] ?? '' ); ?>">
					</label>
				</div>

				<div class="logistica-cierre-caracteristicas__actions">
					<button type="submit" class="button button-primary logistica-cierre-caracteristicas-btn-save" data-cierre-car-submit data-label-add="<?php esc_attr_e( 'Agregar característica', 'logistica' ); ?>" data-label-edit="<?php esc_attr_e( 'Actualizar característica', 'logistica' ); ?>">
						<span class="dashicons dashicons-saved" aria-hidden="true"></span>
						<span data-cierre-car-submit-label><?php echo $edit_row ? esc_html__( 'Actualizar característica', 'logistica' ) : esc_html__( 'Agregar característica', 'logistica' ); ?></span>
					</button>
					<button type="button" class="button logistica-cierre-caracteristicas-btn-cancel" data-action="cierre-car-cancel-edit" <?php echo $edit_row ? '' : 'hidden'; ?>>
						<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
						<?php esc_html_e( 'Cancelar edición', 'logistica' ); ?>
					</button>
					<button type="button" class="button" data-action="cierre-car-close-form" <?php echo $edit_row ? 'hidden' : ''; ?>>
						<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
						<?php esc_html_e( 'Cancelar', 'logistica' ); ?>
					</button>
				</div>
				<p class="logistica-cierre-caracteristicas__status" data-cierre-car-status aria-live="polite"></p>
				<p class="logistica-cierre-caracteristicas__hint"><?php esc_html_e( 'Usa Enter o las flechas del teclado para moverte entre casillas. Al seleccionar una casilla, el contenido se marca automáticamente.', 'logistica' ); ?></p>
			</form>
		</div>

	<div class="logistica-cierre-caracteristicas-table-card">
		<div class="logistica-cierre-caracteristicas-scroll" data-cierre-car-excel-scroll tabindex="0">
			<table class="logistica-cierre-caracteristicas-table">
				<thead>
					<tr>
						<th class="is-codigo logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="codigo">
							<?php esc_html_e( 'Código', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="descripcion">
							<?php esc_html_e( 'Descripción', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="tipo">
							<?php esc_html_e( 'Base', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="is-numeric logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="largo">
							<?php esc_html_e( 'Largo', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="is-numeric logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="ancho">
							<?php esc_html_e( 'Ancho', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="is-numeric logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="alto">
							<?php esc_html_e( 'Alto', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="clave">
							<?php esc_html_e( 'Clave', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="is-numeric logistica-cierre-car-sortable" scope="col" data-cierre-car-sort="calibre">
							<?php esc_html_e( 'Calibre', 'logistica' ); ?>
							<span class="logistica-cierre-car-sort-indicator" aria-hidden="true"></span>
						</th>
						<th class="is-actions-head" scope="col"><?php esc_html_e( 'Acción', 'logistica' ); ?></th>
					</tr>
				</thead>
				<tbody data-cierre-car-rows>
					<?php if ( empty( $caracteristicas_rows ) ) : ?>
						<tr>
							<td colspan="9"><?php esc_html_e( 'Sin características registradas. Agrega el primer código arriba.', 'logistica' ); ?></td>
						</tr>
					<?php else : ?>
						<?php foreach ( $caracteristicas_rows as $caracteristica_row ) : ?>
							<?php
							$row_tipo      = sanitize_key( $caracteristica_row['tipo'] ?? 'cajas' );
							$row_complete  = Logistica_Order_Closing_Characteristics::row_is_complete( $caracteristica_row );
							$row_state_cls = $row_complete ? 'is-car-complete' : 'is-car-incomplete';
							$row_search    = strtolower(
								implode(
									' ',
									array(
										(string) ( $caracteristica_row['codigo'] ?? '' ),
										(string) ( $caracteristica_row['descripcion'] ?? '' ),
										(string) ( $tipo_options[ $row_tipo ] ?? $row_tipo ),
										(string) ( $caracteristica_row['clave'] ?? '' ),
										(string) ( $caracteristica_row['calibre'] ?? '' ),
									)
								)
							);
							?>
							<tr
								class="<?php echo esc_attr( $row_state_cls ); ?>"
								data-cierre-car-row
								data-row-id="<?php echo esc_attr( (string) ( $caracteristica_row['id'] ?? '' ) ); ?>"
								data-cierre-car-search="<?php echo esc_attr( $row_search ); ?>"
								data-cierre-car-descripcion="<?php echo esc_attr( strtolower( (string) ( $caracteristica_row['descripcion'] ?? '' ) ) ); ?>"
								data-cierre-car-tipo="<?php echo esc_attr( $row_tipo ); ?>"
								data-cierre-car-sort-codigo="<?php echo esc_attr( strtolower( (string) ( $caracteristica_row['codigo'] ?? '' ) ) ); ?>"
								data-cierre-car-sort-descripcion="<?php echo esc_attr( strtolower( (string) ( $caracteristica_row['descripcion'] ?? '' ) ) ); ?>"
								data-cierre-car-sort-tipo="<?php echo esc_attr( strtolower( (string) ( $tipo_options[ $row_tipo ] ?? $row_tipo ) ) ); ?>"
								data-cierre-car-sort-largo="<?php echo esc_attr( (string) (float) ( $caracteristica_row['largo'] ?? 0 ) ); ?>"
								data-cierre-car-sort-ancho="<?php echo esc_attr( (string) (float) ( $caracteristica_row['ancho'] ?? 0 ) ); ?>"
								data-cierre-car-sort-alto="<?php echo esc_attr( (string) (float) ( $caracteristica_row['alto'] ?? 0 ) ); ?>"
								data-cierre-car-sort-clave="<?php echo esc_attr( strtolower( (string) ( $caracteristica_row['clave'] ?? '' ) ) ); ?>"
								data-cierre-car-sort-calibre="<?php echo esc_attr( (string) (float) ( $caracteristica_row['calibre'] ?? 0 ) ); ?>"
							>
								<td class="is-codigo"><span class="logistica-cierre-caracteristicas-codigo"><?php echo esc_html( $caracteristica_row['codigo'] ?? '' ); ?></span></td>
								<td><?php echo esc_html( $caracteristica_row['descripcion'] ?? '' ); ?></td>
								<td><?php echo esc_html( $tipo_options[ $row_tipo ] ?? $row_tipo ); ?></td>
								<td class="is-numeric"><?php echo esc_html( $caracteristica_row['largo'] ?? '' ); ?></td>
								<td class="is-numeric"><?php echo esc_html( $caracteristica_row['ancho'] ?? '' ); ?></td>
								<td class="is-numeric"><?php echo esc_html( $caracteristica_row['alto'] ?? '' ); ?></td>
								<td><?php echo esc_html( $caracteristica_row['clave'] ?? '' ); ?></td>
								<td class="is-numeric"><?php echo esc_html( $caracteristica_row['calibre'] ?? '' ); ?></td>
								<td class="logistica-cierre-caracteristicas-actions-cell">
									<div class="logistica-cierre-caracteristicas-actions">
										<button type="button" class="button button-small logistica-table-icon-btn logistica-cierre-caracteristicas-btn-edit" data-action="cierre-car-edit" data-row-id="<?php echo esc_attr( (string) ( $caracteristica_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>
										<button type="button" class="button button-small logistica-table-icon-btn logistica-cierre-caracteristicas-btn-delete" data-action="cierre-car-delete" data-row-id="<?php echo esc_attr( (string) ( $caracteristica_row['id'] ?? '' ) ); ?>" 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>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
				</tbody>
			</table>
			<p class="logistica-cierre-caracteristicas-filter-empty" data-cierre-car-filter-empty hidden>
				<?php esc_html_e( 'No hay códigos que coincidan con los filtros seleccionados.', 'logistica' ); ?>
			</p>
		</div>
		<?php logistica_table_pagination( 'cierre-car' ); ?>
	</div>
	</div>
</section>
