<?php
/**
 * Debug Snapshot Section Partial
 *
 * Displays snapshot comparison and detailed data for the debug page.
 *
 * @package FreeFacTu
 * @since   1.0.0
 * 
 * @var object   $invoice_db   Invoice database record
 * @var WC_Order $order        Order object (may be null)
 * @var bool     $order_exists Whether the order still exists
 */

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

// Get snapshot data
$freefactu_has_snapshot   = ! empty( $invoice_db->invoice_snapshot );
$freefactu_snapshot_data  = null;
$freefactu_snapshot_error = null;

if ( $freefactu_has_snapshot ) {
	$freefactu_snapshot_data = json_decode( $invoice_db->invoice_snapshot, true );
	if ( ! $freefactu_snapshot_data ) {
		$freefactu_snapshot_error = __( 'Error: Datos del snapshot corruptos', 'freefactu' );
	}
}
?>

<h2><?php esc_html_e( 'Snapshot de la Factura', 'freefactu' ); ?></h2>

<?php if ( ! $freefactu_has_snapshot ) : ?>
	<div class="freefactu-warning-box">
		<strong><?php esc_html_e( 'No hay snapshot disponible', 'freefactu' ); ?></strong><br>
		<?php esc_html_e( 'Esta factura no tiene un snapshot guardado. El snapshot captura el estado exacto del pedido en el momento de envío a Verifactu.', 'freefactu' ); ?>
	</div>
<?php elseif ( $freefactu_snapshot_error ) : ?>
	<div class="freefactu-error-box">
		<strong><?php echo esc_html( $freefactu_snapshot_error ); ?></strong>
	</div>
<?php else : ?>
	<div class="freefactu-info-box">
		<strong><?php esc_html_e( 'Snapshot disponible', 'freefactu' ); ?></strong><br>
		<?php esc_html_e( 'Este snapshot captura el estado exacto del pedido cuando se envió a Verifactu.', 'freefactu' ); ?>
	</div>

	<?php
	// Compare with current order if it exists
	$freefactu_has_differences = false;
	$freefactu_differences     = array();
	$freefactu_current_data    = null;

	if ( $order_exists ) {
		$freefactu_pdf_generator = Freefactu_Factory::create_generator( $order );
		$freefactu_current_data  = $freefactu_pdf_generator->prepare_template_data( true );

		// Compare totals
		if ( isset( $freefactu_snapshot_data['totals']['total'] ) && isset( $freefactu_current_data['totals']['total'] ) ) {
			$freefactu_snapshot_total = floatval( $freefactu_snapshot_data['totals']['total'] );
			$freefactu_current_total  = floatval( $freefactu_current_data['totals']['total'] );
			if ( abs( $freefactu_snapshot_total - $freefactu_current_total ) > 0.01 ) {
				$freefactu_has_differences         = true;
				$freefactu_differences['total']    = array(
					'snapshot' => $freefactu_snapshot_total,
					'current'  => $freefactu_current_total,
				);
			}
		}

		// Compare item count
		if ( isset( $freefactu_snapshot_data['items'] ) && isset( $freefactu_current_data['items'] ) ) {
			$freefactu_snapshot_count = count( $freefactu_snapshot_data['items'] );
			$freefactu_current_count  = count( $freefactu_current_data['items'] );
			if ( $freefactu_snapshot_count !== $freefactu_current_count ) {
				$freefactu_has_differences            = true;
				$freefactu_differences['item_count']  = array(
					'snapshot' => $freefactu_snapshot_count,
					'current'  => $freefactu_current_count,
				);
			}
		}

		// Compare customer name
		if ( isset( $freefactu_snapshot_data['customer']['name'] ) && isset( $freefactu_current_data['customer']['name'] ) ) {
			$freefactu_snapshot_name = trim( $freefactu_snapshot_data['customer']['name'] );
			$freefactu_current_name  = trim( $freefactu_current_data['customer']['name'] );
			if ( $freefactu_snapshot_name !== $freefactu_current_name ) {
				$freefactu_has_differences               = true;
				$freefactu_differences['customer_name']  = array(
					'snapshot' => $freefactu_snapshot_name,
					'current'  => $freefactu_current_name,
				);
			}
		}

		// Compare subtotal
		if ( isset( $freefactu_snapshot_data['totals']['subtotal'] ) && isset( $freefactu_current_data['totals']['subtotal'] ) ) {
			$freefactu_snapshot_subtotal = floatval( $freefactu_snapshot_data['totals']['subtotal'] );
			$freefactu_current_subtotal  = floatval( $freefactu_current_data['totals']['subtotal'] );
			if ( abs( $freefactu_snapshot_subtotal - $freefactu_current_subtotal ) > 0.01 ) {
				$freefactu_has_differences         = true;
				$freefactu_differences['subtotal'] = array(
					'snapshot' => $freefactu_snapshot_subtotal,
					'current'  => $freefactu_current_subtotal,
				);
			}
		}
	}
	?>

	<?php if ( $order_exists && $freefactu_has_differences ) : ?>
		<div class="freefactu-warning-box freefactu-snapshot-warning">
			<strong><span class="dashicons dashicons-warning"></span> <?php esc_html_e( 'Diferencias detectadas', 'freefactu' ); ?></strong><br>
			<?php esc_html_e( 'El pedido actual tiene diferencias con el snapshot guardado:', 'freefactu' ); ?>
			<ul class="freefactu-snapshot-warning__list">
				<?php if ( isset( $freefactu_differences['total'] ) ) : ?>
					<li><?php esc_html_e( 'Total:', 'freefactu' ); ?>
						<?php echo wp_kses_post( wc_price( $freefactu_differences['total']['snapshot'] ) ); ?> →
						<?php echo wp_kses_post( wc_price( $freefactu_differences['total']['current'] ) ); ?>
					</li>
				<?php endif; ?>
				<?php if ( isset( $freefactu_differences['subtotal'] ) ) : ?>
					<li><?php esc_html_e( 'Subtotal:', 'freefactu' ); ?>
						<?php echo wp_kses_post( wc_price( $freefactu_differences['subtotal']['snapshot'] ) ); ?> →
						<?php echo wp_kses_post( wc_price( $freefactu_differences['subtotal']['current'] ) ); ?>
					</li>
				<?php endif; ?>
				<?php if ( isset( $freefactu_differences['item_count'] ) ) : ?>
					<li><?php esc_html_e( 'Número de artículos:', 'freefactu' ); ?>
						<?php echo esc_html( $freefactu_differences['item_count']['snapshot'] ); ?> →
						<?php echo esc_html( $freefactu_differences['item_count']['current'] ); ?>
					</li>
				<?php endif; ?>
				<?php if ( isset( $freefactu_differences['customer_name'] ) ) : ?>
					<li><?php esc_html_e( 'Nombre del cliente:', 'freefactu' ); ?>
						<?php echo esc_html( $freefactu_differences['customer_name']['snapshot'] ); ?> →
						<?php echo esc_html( $freefactu_differences['customer_name']['current'] ); ?>
					</li>
				<?php endif; ?>
			</ul>
		</div>
	<?php elseif ( $order_exists ) : ?>
		<div class="freefactu-info-box freefactu-snapshot-success">
			<strong><span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e( 'Sin diferencias', 'freefactu' ); ?></strong><br>
			<?php esc_html_e( 'El pedido actual coincide con el snapshot guardado.', 'freefactu' ); ?>
		</div>
	<?php endif; ?>

	<?php if ( $order_exists && $freefactu_current_data ) : ?>
		<h2 class="freefactu-snapshot-heading"><?php esc_html_e( 'Comparación Detallada (Snapshot vs Actual)', 'freefactu' ); ?></h2>
		
		<table class="comp-table">
			<thead>
				<tr>
					<th class="comp-header-label"><?php esc_html_e( 'Campo', 'freefactu' ); ?></th>
					<th class="comp-header-val"><?php esc_html_e( 'Snapshot (Guardado)', 'freefactu' ); ?></th>
					<th class="comp-header-val"><?php esc_html_e( 'Pedido Woo (Actual)', 'freefactu' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php
				/**
				 * Render comparison row helper function.
				 *
				 * @param string $label Display label.
				 * @param mixed  $val1  Snapshot value.
				 * @param mixed  $val2  Current value.
				 * @param string $type  Value type (text, currency, float, percent).
				 */
				$freefactu_render_comp_row = function( $label, $val1, $val2, $type = 'text' ) {
					$normalize = function( $v, $t ) {
						if ( $t === 'currency' || $t === 'float' || $t === 'percent' ) {
							return is_null( $v ) ? 0.0 : (float) $v;
						}
						if ( is_null( $v ) ) {
							return '';
						}
						return trim( (string) $v );
					};
					
					$n1 = $normalize( $val1, $type );
					$n2 = $normalize( $val2, $type );
					
					$match = false;
					if ( $type === 'currency' || $type === 'float' || $type === 'percent' ) {
						$match = abs( $n1 - $n2 ) < 0.005;
						if ( $type === 'currency' ) {
							$display1 = wc_price( $n1 );
							$display2 = wc_price( $n2 );
						} elseif ( $type === 'percent' ) {
							$display1 = number_format( $n1, 2 ) . '%';
							$display2 = number_format( $n2, 2 ) . '%';
						} else {
							$display1 = esc_html( $n1 );
							$display2 = esc_html( $n2 );
						}
					} else {
						$match    = $n1 === $n2;
						$display1 = esc_html( $n1 );
						$display2 = esc_html( $n2 );
					}
					
					if ( $val1 === null || $val1 === '' ) {
						$display1 = '<span class="comp-empty">-</span>';
					}
					if ( $val2 === null || $val2 === '' ) {
						$display2 = '<span class="comp-empty">-</span>';
					}

					$class1 = 'comp-match';
					$class2 = $match ? 'comp-match' : 'comp-diff';
					?>
					<tr>
						<td><?php echo esc_html( $label ); ?></td>
						<td class="<?php echo esc_attr( $class1 ); ?>"><?php echo $display1; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
						<td class="<?php echo esc_attr( $class2 ); ?>"><?php echo $display2; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
					</tr>
					<?php
				};

				// 1. Customer Data
				echo '<tr><td colspan="3" class="comp-section">' . esc_html__( 'Datos del Cliente', 'freefactu' ) . '</td></tr>';
				$freefactu_cust_s = $freefactu_snapshot_data['customer'] ?? array();
				$freefactu_cust_c = $freefactu_current_data['customer'] ?? array();
				$freefactu_render_comp_row( __( 'Nombre', 'freefactu' ), $freefactu_cust_s['name'] ?? null, $freefactu_cust_c['name'] ?? null );
				$freefactu_render_comp_row( __( 'NIF/CIF', 'freefactu' ), $freefactu_cust_s['nif'] ?? null, $freefactu_cust_c['nif'] ?? null );
				
				$freefactu_addr_s = $freefactu_cust_s['address_1'] ?? ( $freefactu_cust_s['address'] ?? null );
				$freefactu_addr_c = $freefactu_cust_c['address_1'] ?? ( $freefactu_cust_c['address'] ?? null );
				$freefactu_render_comp_row( __( 'Dirección', 'freefactu' ), $freefactu_addr_s, $freefactu_addr_c );
				
				$freefactu_render_comp_row( __( 'Ciudad', 'freefactu' ), $freefactu_cust_s['city'] ?? null, $freefactu_cust_c['city'] ?? null );
				$freefactu_render_comp_row( __( 'Código Postal', 'freefactu' ), $freefactu_cust_s['postcode'] ?? null, $freefactu_cust_c['postcode'] ?? null );
				$freefactu_render_comp_row( __( 'País', 'freefactu' ), $freefactu_cust_s['country'] ?? null, $freefactu_cust_c['country'] ?? null );

				// 2. Totals
				echo '<tr><td colspan="3" class="comp-section">' . esc_html__( 'Totales', 'freefactu' ) . '</td></tr>';
				$freefactu_tot_s = $freefactu_snapshot_data['totals'] ?? array();
				$freefactu_tot_c = $freefactu_current_data['totals'] ?? array();
				$freefactu_render_comp_row( __( 'Subtotal', 'freefactu' ), $freefactu_tot_s['subtotal'] ?? null, $freefactu_tot_c['subtotal'] ?? null, 'currency' );
				$freefactu_render_comp_row( __( 'Total Impuestos', 'freefactu' ), $freefactu_tot_s['tax_total'] ?? null, $freefactu_tot_c['tax_total'] ?? null, 'currency' );
				$freefactu_render_comp_row( __( 'Total General', 'freefactu' ), $freefactu_tot_s['total'] ?? null, $freefactu_tot_c['total'] ?? null, 'currency' );

				// 3. Items
				echo '<tr><td colspan="3" class="comp-section">' . esc_html__( 'Artículos', 'freefactu' ) . '</td></tr>';
				$freefactu_items_s   = $freefactu_snapshot_data['items'] ?? array();
				$freefactu_items_c   = $freefactu_current_data['items'] ?? array();
				$freefactu_max_items = max( count( $freefactu_items_s ), count( $freefactu_items_c ) );
				
				for ( $freefactu_i = 0; $freefactu_i < $freefactu_max_items; $freefactu_i++ ) {
					$freefactu_it_s  = $freefactu_items_s[ $freefactu_i ] ?? null;
					$freefactu_it_c  = $freefactu_items_c[ $freefactu_i ] ?? null;
					$freefactu_index = $freefactu_i + 1;
					
					/* translators: %d: item number */
					echo '<tr><td colspan="3" class="freefactu-comp-item-header">' . esc_html( sprintf( __( 'Artículo #%d', 'freefactu' ), $freefactu_index ) ) . '</td></tr>';
					
					$freefactu_render_comp_row( __( 'Nombre', 'freefactu' ), $freefactu_it_s['name'] ?? null, $freefactu_it_c['name'] ?? null );
					$freefactu_render_comp_row( __( 'Cantidad', 'freefactu' ), $freefactu_it_s['quantity'] ?? null, $freefactu_it_c['quantity'] ?? null, 'float' );
					$freefactu_render_comp_row( __( 'Precio Unidad', 'freefactu' ), $freefactu_it_s['unit_price'] ?? null, $freefactu_it_c['unit_price'] ?? null, 'currency' );
					$freefactu_render_comp_row( __( 'Tasa IVA', 'freefactu' ), $freefactu_it_s['tax_rate'] ?? null, $freefactu_it_c['tax_rate'] ?? null, 'percent' );
					$freefactu_render_comp_row( __( 'Total Línea', 'freefactu' ), $freefactu_it_s['total'] ?? null, $freefactu_it_c['total'] ?? null, 'currency' );
				}
				if ( 0 === $freefactu_max_items ) {
					echo '<tr><td colspan="3" class="comp-empty freefactu-comp-empty-center">' . esc_html__( 'No hay artículos', 'freefactu' ) . '</td></tr>';
				}

				// 4. Tax Breakdown
				echo '<tr><td colspan="3" class="comp-section">' . esc_html__( 'Desglose de IVA', 'freefactu' ) . '</td></tr>';
				$freefactu_tax_s   = $freefactu_snapshot_data['tax_breakdown'] ?? array();
				$freefactu_tax_c   = $freefactu_current_data['tax_breakdown'] ?? array();
				$freefactu_max_tax = max( count( $freefactu_tax_s ), count( $freefactu_tax_c ) );
				
				for ( $freefactu_i = 0; $freefactu_i < $freefactu_max_tax; $freefactu_i++ ) {
					$freefactu_t_s   = $freefactu_tax_s[ $freefactu_i ] ?? null;
					$freefactu_t_c   = $freefactu_tax_c[ $freefactu_i ] ?? null;
					$freefactu_index = $freefactu_i + 1;
					
					$freefactu_rate_lbl = '';
					if ( isset( $freefactu_t_s['rate'] ) ) {
						$freefactu_rate_lbl = $freefactu_t_s['rate'] . '%';
					} elseif ( isset( $freefactu_t_c['rate'] ) ) {
						$freefactu_rate_lbl = $freefactu_t_c['rate'] . '%';
					}
					
					/* translators: %1$d: tax number, %2$s: rate percentage */
					echo '<tr><td colspan="3" class="freefactu-comp-item-header">' . esc_html( sprintf( __( 'Impuesto #%1$d %2$s', 'freefactu' ), $freefactu_index, $freefactu_rate_lbl ? "($freefactu_rate_lbl)" : '' ) ) . '</td></tr>';
					
					$freefactu_render_comp_row( __( 'Tasa %', 'freefactu' ), $freefactu_t_s['rate'] ?? null, $freefactu_t_c['rate'] ?? null, 'percent' );
					$freefactu_render_comp_row( __( 'Base Imponible', 'freefactu' ), $freefactu_t_s['base'] ?? null, $freefactu_t_c['base'] ?? null, 'currency' );
					$freefactu_render_comp_row( __( 'Cuota IVA', 'freefactu' ), $freefactu_t_s['amount'] ?? null, $freefactu_t_c['amount'] ?? null, 'currency' );
				}
				if ( 0 === $freefactu_max_tax ) {
					echo '<tr><td colspan="3" class="comp-empty freefactu-comp-empty-center">' . esc_html__( 'Sin desglose de impuestos', 'freefactu' ) . '</td></tr>';
				}
				?>
			</tbody>
		</table>
	<?php endif; ?>

<?php endif; ?>
