<?php
/**
 * Inventario de bodega (Kardex vs fisico) por codigo unico.
 *
 * @package Logistica
 */

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

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

$stats            = Logistica_Warehouse_Inventory::get_stats();
$filter_options   = Logistica_Warehouse_Inventory::get_filter_options();
$export_url       = wp_nonce_url(
	add_query_arg( 'action', 'logistica_export_inventario_bodega', admin_url( 'admin-post.php' ) ),
	'logistica_export_inventario_bodega'
);
$import_action    = admin_url( 'admin-post.php' );
$import_redirect  = logistica_tab_url( 'logistica-inventario-bodega', is_admin() ? 'admin' : 'frontend' );
$edit_fields      = Logistica_Warehouse_Inventory::form_edit_fields();
$total_rows       = (int) ( $stats['total'] ?? 0 );
$alert_count      = (int) ( $stats['alert'] ?? 0 );
$ok_count         = (int) ( $stats['ok'] ?? 0 );
$improved_count   = (int) ( $stats['improved'] ?? 0 );
$filter_clases    = $filter_options['clases'] ?? array();
$filter_descripciones = $filter_options['descripciones'] ?? array();

logistica_admin_header( __( 'Inventario bodega', 'logistica' ) );
?>
<section
	class="logistica-warehouse-board"
	data-warehouse-board
	data-warehouse-server-page="1"
	data-warehouse-stats="<?php echo esc_attr( wp_json_encode( $stats ) ); ?>"
>
	<?php if ( ! logistica_is_tabbed_shell() ) : ?>
		<?php logistica_tab_loading_overlay( logistica_tab_loading_message( 'logistica-inventario-bodega' ) ); ?>
	<?php endif; ?>
	<div class="logistica-close-toolbar logistica-warehouse-toolbar">
		<div class="logistica-warehouse-toolbar__intro">
			<div class="logistica-warehouse-toolbar__badge" aria-hidden="true">
				<span class="dashicons dashicons-store"></span>
			</div>
			<div>
				<h2><?php esc_html_e( 'Inventario bodega', 'logistica' ); ?></h2>
				<p><?php esc_html_e( 'Controla existencias por código y lote, compara Kardex contra inventario físico y sincroniza el lote vigente con cierre de órdenes.', 'logistica' ); ?></p>
			</div>
		</div>
	</div>

	<div class="logistica-warehouse-stats" data-warehouse-stats-bar>
		<div class="logistica-warehouse-stat">
			<span class="logistica-warehouse-stat__value" data-warehouse-stat="total"><?php echo esc_html( (string) $total_rows ); ?></span>
			<span class="logistica-warehouse-stat__label"><?php esc_html_e( 'Códigos', 'logistica' ); ?></span>
		</div>
		<div class="logistica-warehouse-stat is-alert">
			<span class="logistica-warehouse-stat__value" data-warehouse-stat="alert"><?php echo esc_html( (string) $alert_count ); ?></span>
			<span class="logistica-warehouse-stat__label"><?php esc_html_e( 'Con diferencia', 'logistica' ); ?></span>
		</div>
		<div class="logistica-warehouse-stat is-ok">
			<span class="logistica-warehouse-stat__value" data-warehouse-stat="ok"><?php echo esc_html( (string) $ok_count ); ?></span>
			<span class="logistica-warehouse-stat__label"><?php esc_html_e( 'Equilibrados', 'logistica' ); ?></span>
		</div>
		<?php if ( $improved_count > 0 ) : ?>
			<div class="logistica-warehouse-stat is-improved">
				<span class="logistica-warehouse-stat__value" data-warehouse-stat="improved"><?php echo esc_html( (string) $improved_count ); ?></span>
				<span class="logistica-warehouse-stat__label"><?php esc_html_e( 'Mejoraron', 'logistica' ); ?></span>
			</div>
		<?php endif; ?>
	</div>

	<form
		id="logistica-warehouse-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_inventario_bodega">
		<input type="hidden" name="redirect_to" value="<?php echo esc_url( $import_redirect ); ?>">
		<?php wp_nonce_field( 'logistica_import_inventario_bodega' ); ?>
	</form>

	<?php if ( $alert_count > 0 ) : ?>
		<div class="logistica-warehouse-alert" role="alert" data-warehouse-alert>
			<span class="logistica-warehouse-alert__icon dashicons dashicons-warning" aria-hidden="true"></span>
			<div>
				<strong><?php esc_html_e( 'Diferencias Kardex vs físico', 'logistica' ); ?></strong>
				<p data-warehouse-alert-text>
					<?php
					printf(
						/* translators: %d: row count with difference */
						esc_html__( 'Hay %d códigos con diferencia entre saldo bodega e inventario físico. Revisa el inventario físico o edita el registro.', 'logistica' ),
						(int) $alert_count
					);
					?>
				</p>
			</div>
		</div>
	<?php endif; ?>

	<div class="logistica-tapas-excel-wrap logistica-warehouse-table-wrap" data-excel-zoom-root="warehouse">
		<?php
		logistica_table_excel_view_header(
			__( 'Compara saldo bodega contra inventario físico. Edita el inventario físico directamente en la tabla.', 'logistica' )
		);
		logistica_excel_table_zoom_toolbar();
		?>
		<div class="logistica-tapas-filters" data-warehouse-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-warehouse-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-warehouse-filter-search
						placeholder="<?php esc_attr_e( 'Código, descripción, lote, bodega...', 'logistica' ); ?>"
						autocomplete="off"
						spellcheck="false"
					>
				</label>
				<label class="logistica-tapas-filters__field logistica-tapas-filters__field--search">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Descripción', 'logistica' ); ?></span>
					<input
						type="search"
						list="logistica-warehouse-descripcion-options"
						data-warehouse-filter-descripcion
						placeholder="<?php esc_attr_e( 'Escribe parte de la descripción...', 'logistica' ); ?>"
						autocomplete="off"
						spellcheck="false"
					>
					<datalist id="logistica-warehouse-descripcion-options">
						<?php foreach ( $filter_descripciones as $filter_descripcion ) : ?>
							<option value="<?php echo esc_attr( $filter_descripcion ); ?>"></option>
						<?php endforeach; ?>
					</datalist>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Clase', 'logistica' ); ?></span>
					<select data-warehouse-filter-clase>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<?php foreach ( $filter_clases as $filter_clase ) : ?>
							<option value="<?php echo esc_attr( $filter_clase ); ?>"><?php echo esc_html( $filter_clase ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Estado', 'logistica' ); ?></span>
					<select data-warehouse-filter-status>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<option value="diff"><?php esc_html_e( 'Con diferencia', 'logistica' ); ?></option>
						<option value="ok"><?php esc_html_e( 'Equilibrados', 'logistica' ); ?></option>
						<option value="improved"><?php esc_html_e( 'Mejoraron', 'logistica' ); ?></option>
						<option value="registro_activo"><?php esc_html_e( 'Registro activo', 'logistica' ); ?></option>
						<option value="registro_inactivo"><?php esc_html_e( 'Registro inactivo', 'logistica' ); ?></option>
						<option value="lote_vigente"><?php esc_html_e( 'Lote vigente', 'logistica' ); ?></option>
					</select>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Saldo bodega', 'logistica' ); ?></span>
					<select data-warehouse-filter-saldo>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<option value="omit_zero"><?php esc_html_e( 'Omitir en 0', 'logistica' ); ?></option>
					</select>
				</label>
				<div class="logistica-tapas-filters__actions">
					<button type="button" class="button logistica-tapas-filters__btn" data-action="clear-warehouse-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-warehouse-filter-meta hidden></p>
		</div>
		<?php
		logistica_table_excel_toolbar(
			array(
				'export_url'       => $export_url,
				'import_form_id'   => 'logistica-warehouse-excel-upload',
				'import_input_id'  => 'logistica-warehouse-excel-file',
				'import_input_name'=> 'inventario_bodega_file',
				'import_data_attr' => 'warehouse-import-file',
				'import_action'    => 'import-warehouse-excel',
				'show_zoom'        => false,
			)
		);
		logistica_table_status_legend(
			array(
				array(
					'class' => 'is-warehouse-legend-diff',
					'label' => __( 'Con diferencia', 'logistica' ),
				),
				array(
					'class' => 'is-warehouse-legend-ok',
					'label' => __( 'Equilibrado', 'logistica' ),
				),
				array(
					'class' => 'is-warehouse-legend-improved',
					'label' => __( 'Mejoró', 'logistica' ),
				),
				array(
					'class' => 'is-warehouse-legend-inactive',
					'label' => __( 'Registro inactivo', 'logistica' ),
				),
				array(
					'class' => 'is-warehouse-legend-vigente',
					'label' => __( 'Lote vigente', 'logistica' ),
				),
			)
		);
		logistica_table_sheet_actions( __( 'Añadir referencia', 'logistica' ), 'warehouse-add-row' );
		?>

		<div class="logistica-warehouse-add-form-card" data-warehouse-form-card hidden>
			<form class="logistica-warehouse-add-form" data-warehouse-add-form>
				<div class="logistica-warehouse-add-form__grid">
					<label class="logistica-warehouse-add-form__field">
						<span><?php esc_html_e( 'Código', 'logistica' ); ?></span>
						<input type="text" name="codigo" data-warehouse-field required autocomplete="off" spellcheck="false">
					</label>
					<?php foreach ( $edit_fields as $field_key => $field_meta ) : ?>
						<label class="logistica-warehouse-add-form__field is-type-<?php echo esc_attr( $field_meta['type'] ); ?>">
							<span><?php echo esc_html( $field_meta['label'] ); ?></span>
							<?php if ( 'textarea' === $field_meta['type'] ) : ?>
								<textarea name="<?php echo esc_attr( $field_key ); ?>" data-warehouse-field rows="3"></textarea>
							<?php else : ?>
								<input
									type="<?php echo esc_attr( $field_meta['type'] ); ?>"
									name="<?php echo esc_attr( $field_key ); ?>"
									data-warehouse-field
									<?php echo ! empty( $field_meta['step'] ) ? 'step="' . esc_attr( $field_meta['step'] ) . '"' : ''; ?>
									<?php echo 'number' === $field_meta['type'] ? 'inputmode="decimal"' : ''; ?>
								>
							<?php endif; ?>
						</label>
					<?php endforeach; ?>
				</div>
				<div class="logistica-warehouse-add-form__actions">
					<button type="submit" class="button button-primary logistica-warehouse-add-form__submit" data-warehouse-add-submit>
						<span class="dashicons dashicons-saved" aria-hidden="true"></span>
						<?php esc_html_e( 'Agregar código', 'logistica' ); ?>
					</button>
					<button type="button" class="button" data-action="warehouse-close-add-form">
						<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
						<?php esc_html_e( 'Cancelar', 'logistica' ); ?>
					</button>
				</div>
				<p class="logistica-warehouse-add-form__hint"><?php esc_html_e( 'Cada combinación código + lote es un registro distinto. Si el lote queda vacío, se asigna automáticamente.', 'logistica' ); ?></p>
			</form>
		</div>

	<div class="logistica-warehouse-table-card">
	<div class="logistica-warehouse-scroll" data-warehouse-excel-scroll tabindex="0">
		<table class="logistica-warehouse-table">
			<thead>
				<tr>
					<th class="is-codigo logistica-warehouse-sortable" scope="col" data-warehouse-sort="codigo">
						<?php esc_html_e( 'Código', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="logistica-warehouse-sortable" scope="col" data-warehouse-sort="descripcion">
						<?php esc_html_e( 'Descripción', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="logistica-warehouse-sortable" scope="col" data-warehouse-sort="materia_prima">
						<?php esc_html_e( 'Bodega', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="logistica-warehouse-sortable" scope="col" data-warehouse-sort="medida">
						<?php esc_html_e( 'Medida', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="is-lote logistica-warehouse-sortable" scope="col" data-warehouse-sort="lote">
						<?php esc_html_e( 'Lote', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="is-fecha logistica-warehouse-sortable" scope="col" data-warehouse-sort="fecha_creacion">
						<?php esc_html_e( 'Fecha creación', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="is-numeric logistica-warehouse-sortable" scope="col" data-warehouse-sort="saldo_bodega">
						<?php esc_html_e( 'Saldo bodega', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="logistica-warehouse-sortable" scope="col" data-warehouse-sort="clase">
						<?php esc_html_e( 'Clase', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="is-inventario-fisico logistica-warehouse-sortable" scope="col" data-warehouse-sort="inventario_fisico">
						<?php esc_html_e( 'Inventario físico', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="is-numeric logistica-warehouse-sortable" scope="col" data-warehouse-sort="diferencia">
						<?php esc_html_e( 'Diferencia', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="logistica-warehouse-sortable" scope="col" data-warehouse-sort="estado">
						<?php esc_html_e( 'Estado', 'logistica' ); ?>
						<span class="logistica-warehouse-sort-indicator" aria-hidden="true"></span>
					</th>
					<th class="logistica-warehouse-sortable" scope="col" data-warehouse-sort="registro">
						<?php esc_html_e( 'Registro', 'logistica' ); ?>
						<span class="logistica-warehouse-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-warehouse-rows>
				<tr data-warehouse-loading>
					<td colspan="13"><?php esc_html_e( 'Cargando inventario…', 'logistica' ); ?></td>
				</tr>
			</tbody>
		</table>
		<p class="logistica-warehouse-filter-empty" data-warehouse-filter-empty hidden>
			<?php esc_html_e( 'No hay códigos que coincidan con los filtros seleccionados.', 'logistica' ); ?>
		</p>
	</div>
	<?php logistica_table_pagination( 'warehouse' ); ?>
	</div>
	</div>

	<div class="logistica-warehouse-modal" data-warehouse-modal hidden>
		<div class="logistica-warehouse-modal__backdrop" data-action="warehouse-close-modal" aria-hidden="true"></div>
		<div class="logistica-warehouse-modal__panel" role="dialog" aria-modal="true" aria-labelledby="logistica-warehouse-modal-title">
			<header class="logistica-warehouse-modal__head">
				<h3 id="logistica-warehouse-modal-title">
					<?php esc_html_e( 'Editar código', 'logistica' ); ?>
					<span data-warehouse-modal-codigo></span>
				</h3>
				<button type="button" class="logistica-warehouse-modal__close" data-action="warehouse-close-modal" aria-label="<?php esc_attr_e( 'Cerrar', 'logistica' ); ?>">&times;</button>
			</header>
			<form class="logistica-warehouse-modal__form" data-warehouse-edit-form>
				<input type="hidden" name="row_id" data-field="row_id" value="">
				<input type="hidden" name="codigo" data-field="codigo" value="">
				<div class="logistica-warehouse-modal__grid">
					<?php foreach ( $edit_fields as $field_key => $field_meta ) : ?>
						<label class="logistica-warehouse-modal__field is-type-<?php echo esc_attr( $field_meta['type'] ); ?>">
							<span><?php echo esc_html( $field_meta['label'] ); ?></span>
							<?php if ( 'textarea' === $field_meta['type'] ) : ?>
								<textarea name="<?php echo esc_attr( $field_key ); ?>" data-field="<?php echo esc_attr( $field_key ); ?>" rows="3"></textarea>
							<?php else : ?>
								<input
									type="<?php echo esc_attr( $field_meta['type'] ); ?>"
									name="<?php echo esc_attr( $field_key ); ?>"
									data-field="<?php echo esc_attr( $field_key ); ?>"
									<?php echo ! empty( $field_meta['step'] ) ? 'step="' . esc_attr( $field_meta['step'] ) . '"' : ''; ?>
								>
							<?php endif; ?>
						</label>
					<?php endforeach; ?>
				</div>
				<p class="logistica-warehouse-modal__hint"><?php esc_html_e( 'El código no se puede cambiar. Cada lote es un registro distinto. Si este registro es el vigente (activo y más antiguo), el lote se sincroniza al cierre de órdenes.', 'logistica' ); ?></p>
				<footer class="logistica-warehouse-modal__foot">
					<button type="button" class="button" data-action="warehouse-close-modal"><?php esc_html_e( 'Cancelar', 'logistica' ); ?></button>
					<button type="submit" class="button button-primary" data-warehouse-save><?php esc_html_e( 'Guardar cambios', 'logistica' ); ?></button>
				</footer>
			</form>
		</div>
	</div>
</section>
<?php logistica_admin_footer(); ?>
