<?php
/**
 * Vista de revisión de minutas de producción.
 *
 * @package Logistica
 */

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

$minuta_rows      = Logistica_Minutas::get_all();
$minuta_stats     = Logistica_Minutas::get_stats( $minuta_rows );
$review_columns   = Logistica_Minutas::review_column_keys();
$column_labels    = Logistica_Minutas::columns();
$text_columns     = array_flip( Logistica_Minutas::review_text_column_keys() );
$total_columns    = array_flip( Logistica_Minutas::review_total_column_keys() );
$copy_columns     = array_flip( Logistica_Minutas::review_copy_column_keys() );
$revision_options = Logistica_Minutas::revision_options();
$export_url       = wp_nonce_url(
	add_query_arg( 'action', 'logistica_export_minutas', admin_url( 'admin-post.php' ) ),
	'logistica_export_minutas'
);
$import_action    = admin_url( 'admin-post.php' );
$import_redirect   = logistica_tab_url( 'logistica-revision-minuta', is_admin() ? 'admin' : 'frontend' );

$filter_clientes  = array();
$filter_fechas    = array();
$filter_procesos  = array();
$filter_empleados = array();

foreach ( $minuta_rows as $minuta_row ) {
	$cliente  = trim( (string) ( $minuta_row['cliente'] ?? '' ) );
	$fecha    = trim( (string) ( $minuta_row['fecha'] ?? '' ) );
	$proceso  = trim( (string) ( $minuta_row['proceso'] ?? '' ) );
	$empleado = trim( (string) ( $minuta_row['empleado'] ?? '' ) );
	if ( '' !== $cliente ) {
		$filter_clientes[ $cliente ] = $cliente;
	}
	if ( '' !== $fecha ) {
		$filter_fechas[ $fecha ] = $fecha;
	}
	if ( '' !== $proceso ) {
		$filter_procesos[ $proceso ] = $proceso;
	}
	if ( '' !== $empleado ) {
		$filter_empleados[ $empleado ] = $empleado;
	}
}

natcasesort( $filter_clientes );
uksort(
	$filter_fechas,
	function ( $fecha_a, $fecha_b ) {
		$time_a = strtotime( (string) $fecha_a );
		$time_b = strtotime( (string) $fecha_b );

		if ( false !== $time_a && false !== $time_b && $time_a !== $time_b ) {
			return $time_b <=> $time_a;
		}

		return strnatcasecmp( (string) $fecha_b, (string) $fecha_a );
	}
);
natcasesort( $filter_procesos );
natcasesort( $filter_empleados );
?>
<section class="logistica-minutas-board" data-minutas-board data-minutas-stats="<?php echo esc_attr( wp_json_encode( $minuta_stats ) ); ?>">
	<?php if ( ! logistica_is_tabbed_shell() ) : ?>
		<?php logistica_tab_loading_overlay( logistica_tab_loading_message( 'logistica-revision-minuta' ) ); ?>
	<?php endif; ?>

	<div class="logistica-close-toolbar logistica-minutas-toolbar">
		<div class="logistica-minutas-toolbar__intro">
			<div class="logistica-minutas-toolbar__badge" aria-hidden="true">
				<span class="dashicons dashicons-clipboard"></span>
			</div>
			<div>
				<h2><?php esc_html_e( 'Revisión minuta', 'logistica' ); ?></h2>
				<p><?php esc_html_e( 'Vista organizada para revisar minutas de producción. Importa tu archivo Excel (hoja minutas) y marca el estado de revisión.', 'logistica' ); ?></p>
			</div>
		</div>
	</div>

	<div class="logistica-minutas-stats" data-minutas-stats-bar>
		<div class="logistica-minutas-stat">
			<span class="logistica-minutas-stat__value" data-minutas-stat="total"><?php echo esc_html( (string) (int) $minuta_stats['total'] ); ?></span>
			<span class="logistica-minutas-stat__label"><?php esc_html_e( 'Total minutas', 'logistica' ); ?></span>
		</div>
		<div class="logistica-minutas-stat">
			<span class="logistica-minutas-stat__value" data-minutas-stat="total_buenas"><?php echo esc_html( number_format_i18n( (float) $minuta_stats['total_buenas'], 0 ) ); ?></span>
			<span class="logistica-minutas-stat__label"><?php esc_html_e( 'Total buenas', 'logistica' ); ?></span>
		</div>
		<div class="logistica-minutas-stat is-alert">
			<span class="logistica-minutas-stat__value" data-minutas-stat="total_malas"><?php echo esc_html( number_format_i18n( (float) $minuta_stats['total_malas'], 0 ) ); ?></span>
			<span class="logistica-minutas-stat__label"><?php esc_html_e( 'Total malas', 'logistica' ); ?></span>
		</div>
		<div class="logistica-minutas-stat is-warn">
			<span class="logistica-minutas-stat__value" data-minutas-stat="sin_hora_final"><?php echo esc_html( (string) (int) $minuta_stats['sin_hora_final'] ); ?></span>
			<span class="logistica-minutas-stat__label"><?php esc_html_e( 'Sin hora final', 'logistica' ); ?></span>
		</div>
		<div class="logistica-minutas-stat is-warn">
			<span class="logistica-minutas-stat__value" data-minutas-stat="con_malas"><?php echo esc_html( (string) (int) $minuta_stats['con_malas'] ); ?></span>
			<span class="logistica-minutas-stat__label"><?php esc_html_e( 'Con malas', 'logistica' ); ?></span>
		</div>
		<div class="logistica-minutas-stat is-pending">
			<span class="logistica-minutas-stat__value" data-minutas-stat="pendientes_revision"><?php echo esc_html( (string) (int) $minuta_stats['pendientes_revision'] ); ?></span>
			<span class="logistica-minutas-stat__label"><?php esc_html_e( 'Pendientes revisión', 'logistica' ); ?></span>
		</div>
	</div>

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

	<div class="logistica-tapas-excel-wrap logistica-minutas-table-wrap" data-excel-zoom-root="minutas">
		<?php
		logistica_table_excel_view_header(
			__( 'Filtra y revisa las minutas. La columna Revisión se guarda al cambiar el valor.', 'logistica' )
		);
		logistica_excel_table_zoom_toolbar();
		?>
		<div class="logistica-tapas-filters" data-minutas-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-minutas-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-minutas-filter-search
						placeholder="<?php esc_attr_e( 'Minuta, cliente, referencia, orden...', 'logistica' ); ?>"
						autocomplete="off"
						spellcheck="false"
					>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Cliente', 'logistica' ); ?></span>
					<select data-minutas-filter-cliente>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<?php foreach ( $filter_clientes as $filter_cliente ) : ?>
							<option value="<?php echo esc_attr( $filter_cliente ); ?>"><?php echo esc_html( $filter_cliente ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Fecha', 'logistica' ); ?></span>
					<select data-minutas-filter-fecha>
						<option value=""><?php esc_html_e( 'Todas', 'logistica' ); ?></option>
						<?php foreach ( $filter_fechas as $filter_fecha ) : ?>
							<option value="<?php echo esc_attr( $filter_fecha ); ?>"><?php echo esc_html( $filter_fecha ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<div class="logistica-tapas-filters__field logistica-tapas-filters__field--multiselect">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Proceso', 'logistica' ); ?></span>
					<div class="logistica-filter-multiselect" data-minutas-filter-proceso>
						<button
							type="button"
							class="logistica-filter-multiselect__trigger"
							data-minutas-filter-proceso-trigger
							aria-haspopup="listbox"
							aria-expanded="false"
						>
							<span
								class="logistica-filter-multiselect__label"
								data-minutas-filter-proceso-label
								data-default-label="<?php esc_attr_e( 'Todos', 'logistica' ); ?>"
								data-selected-label="<?php echo esc_attr( __( '%d seleccionados', 'logistica' ) ); ?>"
							><?php esc_html_e( 'Todos', 'logistica' ); ?></span>
						</button>
						<div class="logistica-filter-multiselect__panel" data-minutas-filter-proceso-panel hidden>
							<div class="logistica-filter-multiselect__options" role="listbox" aria-multiselectable="true">
								<?php foreach ( $filter_procesos as $filter_proceso ) : ?>
									<label class="logistica-filter-multiselect__option" role="option">
										<input type="checkbox" value="<?php echo esc_attr( $filter_proceso ); ?>">
										<span><?php echo esc_html( $filter_proceso ); ?></span>
									</label>
								<?php endforeach; ?>
							</div>
						</div>
					</div>
				</div>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Empleado', 'logistica' ); ?></span>
					<select data-minutas-filter-empleado>
						<option value=""><?php esc_html_e( 'Todos', 'logistica' ); ?></option>
						<?php foreach ( $filter_empleados as $filter_empleado ) : ?>
							<option value="<?php echo esc_attr( $filter_empleado ); ?>"><?php echo esc_html( $filter_empleado ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<label class="logistica-tapas-filters__field">
					<span class="logistica-tapas-filters__label"><?php esc_html_e( 'Revisión', 'logistica' ); ?></span>
					<select data-minutas-filter-revision>
						<option value=""><?php esc_html_e( 'Todas', 'logistica' ); ?></option>
						<?php foreach ( $revision_options as $revision_option ) : ?>
							<option value="<?php echo esc_attr( $revision_option ); ?>"><?php echo esc_html( $revision_option ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<div class="logistica-tapas-filters__actions">
					<button type="button" class="button logistica-tapas-filters__btn" data-action="clear-minutas-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-minutas-filter-meta hidden></p>
		</div>
		<?php
		logistica_table_excel_toolbar(
			array(
				'export_url'        => $export_url,
				'import_form_id'    => 'logistica-minutas-excel-upload',
				'import_input_id'   => 'logistica-minutas-excel-file',
				'import_input_name' => 'minutas_file',
				'import_data_attr'  => 'minutas-import-file',
				'import_action'     => 'import-minutas-excel',
				'show_zoom'         => false,
			)
		);
		logistica_table_status_legend(
			array(
				array(
					'class' => 'is-minutas-legend-malas',
					'label' => __( 'Con unidades malas', 'logistica' ),
				),
				array(
					'class' => 'is-minutas-legend-sin-final',
					'label' => __( 'Sin hora final', 'logistica' ),
				),
				array(
					'class' => 'is-minutas-legend-pendiente',
					'label' => __( 'Revisión pendiente', 'logistica' ),
				),
			)
		);
		?>
		<div class="logistica-tapas-excel-scroll" data-minutas-excel-scroll>
			<table class="logistica-tapas-excel logistica-tapas-excel-table logistica-minutas-table">
				<thead>
					<tr>
						<?php foreach ( $review_columns as $review_key ) : ?>
							<th scope="col" class="<?php echo isset( $text_columns[ $review_key ] ) ? 'is-text' : 'is-num'; ?> is-col-<?php echo esc_attr( sanitize_html_class( $review_key ) ); ?>">
								<?php echo esc_html( $column_labels[ $review_key ] ?? $review_key ); ?>
							</th>
						<?php endforeach; ?>
					</tr>
				</thead>
				<tbody data-minutas-rows>
					<?php if ( empty( $minuta_rows ) ) : ?>
						<tr class="logistica-minutas-empty-row">
							<td colspan="<?php echo esc_attr( (string) count( $review_columns ) ); ?>">
								<?php esc_html_e( 'No hay minutas cargadas. Usa Importar documento para cargar tu archivo Excel.', 'logistica' ); ?>
							</td>
						</tr>
					<?php else : ?>
						<?php foreach ( $minuta_rows as $minuta_row ) : ?>
							<?php
							$row_classes = array( 'logistica-minutas-row' );
							if ( ! empty( $minuta_row['flags']['con_malas'] ) ) {
								$row_classes[] = 'is-minutas-malas';
							}
							if ( ! empty( $minuta_row['flags']['sin_hora_final'] ) ) {
								$row_classes[] = 'is-minutas-sin-final';
							}
							if ( ! empty( $minuta_row['flags']['pendiente'] ) ) {
								$row_classes[] = 'is-minutas-pendiente';
							}
							$search_blob = strtolower(
								implode(
									' ',
									array(
										(string) ( $minuta_row['minuta'] ?? '' ),
										(string) ( $minuta_row['cliente'] ?? '' ),
										(string) ( $minuta_row['referencia'] ?? '' ),
										(string) ( $minuta_row['empleado'] ?? '' ),
										(string) ( $minuta_row['orden'] ?? '' ),
										(string) ( $minuta_row['observacio'] ?? '' ),
									)
								)
							);
							?>
							<tr
								class="<?php echo esc_attr( implode( ' ', $row_classes ) ); ?>"
								data-minutas-row
								data-row-id="<?php echo esc_attr( (string) (int) ( $minuta_row['id'] ?? 0 ) ); ?>"
								data-minutas-cliente="<?php echo esc_attr( (string) ( $minuta_row['cliente'] ?? '' ) ); ?>"
								data-minutas-fecha="<?php echo esc_attr( (string) ( $minuta_row['fecha'] ?? '' ) ); ?>"
								data-minutas-proceso="<?php echo esc_attr( (string) ( $minuta_row['proceso'] ?? '' ) ); ?>"
								data-minutas-empleado="<?php echo esc_attr( (string) ( $minuta_row['empleado'] ?? '' ) ); ?>"
								data-minutas-revision="<?php echo esc_attr( (string) ( $minuta_row['revision'] ?? '' ) ); ?>"
								data-minutas-search="<?php echo esc_attr( $search_blob ); ?>"
								data-minutas-minutos="<?php echo esc_attr( (string) Logistica_Minutas::parse_number( $minuta_row['minutos'] ?? 0 ) ); ?>"
								data-minutas-buenas="<?php echo esc_attr( (string) Logistica_Minutas::parse_number( $minuta_row['buenas'] ?? 0 ) ); ?>"
								data-minutas-malas="<?php echo esc_attr( (string) Logistica_Minutas::parse_number( $minuta_row['malas'] ?? 0 ) ); ?>"
							>
								<?php foreach ( $review_columns as $review_key ) : ?>
									<?php
									$cell_class = isset( $text_columns[ $review_key ] ) ? 'is-text' : 'is-num';
									$cell_class .= ' is-col-' . sanitize_html_class( $review_key );
									?>
									<?php if ( 'revision' === $review_key ) : ?>
										<td class="logistica-minutas-revision-cell <?php echo esc_attr( $cell_class ); ?>" data-minutas-nav-cell>
											<select data-minutas-revision aria-label="<?php esc_attr_e( 'Revisión', 'logistica' ); ?>">
												<?php foreach ( $revision_options as $revision_option ) : ?>
													<option value="<?php echo esc_attr( $revision_option ); ?>" <?php selected( (string) ( $minuta_row['revision'] ?? '' ), $revision_option ); ?>>
														<?php echo esc_html( $revision_option ); ?>
													</option>
												<?php endforeach; ?>
											</select>
										</td>
									<?php elseif ( isset( $copy_columns[ $review_key ] ) ) : ?>
										<?php
										$cell_value = (string) ( $minuta_row[ $review_key ] ?? '' );
										$cell_class .= ' is-copy-cell';
										?>
										<td class="<?php echo esc_attr( $cell_class ); ?>" data-minutas-nav-cell>
											<?php
											logistica_minuta_copy_input(
												$cell_value,
												(string) ( $column_labels[ $review_key ] ?? $review_key ),
												false
											);
											?>
										</td>
									<?php else : ?>
										<td class="<?php echo esc_attr( $cell_class ); ?>" data-minutas-nav-cell tabindex="0"><?php echo esc_html( (string) ( $minuta_row[ $review_key ] ?? '' ) ); ?></td>
									<?php endif; ?>
								<?php endforeach; ?>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
				</tbody>
				<?php if ( ! empty( $minuta_rows ) ) : ?>
					<tfoot>
						<tr class="logistica-minutas-table-summary logistica-tapas-excel-summary" data-minutas-table-summary>
							<?php foreach ( $review_columns as $review_key ) : ?>
								<?php if ( 'minuta' === $review_key ) : ?>
									<th scope="row" class="is-text is-col-minuta">
										<?php esc_html_e( 'Totales', 'logistica' ); ?>
										<span class="logistica-minutas-summary-count" data-minutas-summary-count>(<?php echo esc_html( (string) (int) $minuta_stats['total'] ); ?>)</span>
									</th>
								<?php elseif ( isset( $total_columns[ $review_key ] ) ) : ?>
									<td class="is-num is-col-<?php echo esc_attr( sanitize_html_class( $review_key ) ); ?>" data-minutas-total="<?php echo esc_attr( $review_key ); ?>">
										<?php
										echo esc_html(
											number_format_i18n(
												(float) ( $minuta_stats[ 'total_' . $review_key ] ?? 0 ),
												0
											)
										);
										?>
									</td>
								<?php else : ?>
									<td class="is-text is-col-<?php echo esc_attr( sanitize_html_class( $review_key ) ); ?>"></td>
								<?php endif; ?>
							<?php endforeach; ?>
						</tr>
					</tfoot>
				<?php endif; ?>
			</table>
		</div>
		<?php logistica_table_pagination( 'minutas' ); ?>
	</div>
</section>