<?php
/**
 * Invoice History Page View
 *
 * Displays the paginated list of all Verifactu invoices.
 *
 * @package FreeFacTu
 * @since   1.0.0
 * 
 * @var array  $invoices         Array of invoice objects
 * @var int    $total_invoices   Total number of invoices
 * @var int    $total_pages      Total number of pages
 * @var int    $paged            Current page number
 * @var string $filter_date_from Date from filter value
 * @var string $filter_date_to   Date to filter value
 * @var string $filter_status    Status filter value
 * @var bool   $has_filters      Whether any filters are active
 */

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

<!-- Integrated Invoice Toolbar -->
<div class="freefactu-invoice-toolbar">
	<!-- Filter Controls -->
	<form method="get" action="" class="freefactu-toolbar__filters<?php echo esc_attr( $has_filters ? ' has-active-filters' : '' ); ?>" id="freefactu-filter-form">
		<input type="hidden" name="page" value="freefactu">
		<input type="hidden" name="tab" value="facturas">
		<input type="hidden" id="filter_date_from" name="filter_date_from" value="<?php echo esc_attr( $filter_date_from ); ?>">
		<input type="hidden" id="filter_date_to" name="filter_date_to" value="<?php echo esc_attr( $filter_date_to ); ?>">
		
		<?php
		// Determine what to display in the date button
		$freefactu_current_year = current_time( 'Y' );
		$freefactu_date_display = $freefactu_current_year; // Default to current year
		$freefactu_has_date_filter = ! empty( $filter_date_from ) || ! empty( $filter_date_to );
		
		if ( $freefactu_has_date_filter ) {
			$freefactu_from_formatted = ! empty( $filter_date_from ) ? date_i18n( 'j M Y', strtotime( $filter_date_from ) ) : '';
			$freefactu_to_formatted   = ! empty( $filter_date_to ) ? date_i18n( 'j M Y', strtotime( $filter_date_to ) ) : '';
			
			if ( $freefactu_from_formatted && $freefactu_to_formatted ) {
				$freefactu_date_display = $freefactu_from_formatted . ' – ' . $freefactu_to_formatted;
			} elseif ( $freefactu_from_formatted ) {
				$freefactu_date_display = sprintf( 
					/* translators: %s: Start date */
					__( 'Desde %s', 'freefactu' ), 
					$freefactu_from_formatted 
				);
			} elseif ( $freefactu_to_formatted ) {
				$freefactu_date_display = sprintf( 
					/* translators: %s: End date */
					__( 'Hasta %s', 'freefactu' ), 
					$freefactu_to_formatted 
				);
			}
		}
		?>
		
		<!-- Google Analytics Style Date Picker Trigger -->
		<div class="freefactu-daterange" id="freefactu-daterange">
			<button type="button" class="freefactu-daterange__trigger" id="freefactu-daterange-trigger" aria-expanded="false" aria-haspopup="true">
				<span class="dashicons dashicons-calendar-alt"></span>
				<span class="freefactu-daterange__label" id="freefactu-daterange-label"><?php echo esc_html( $freefactu_date_display ); ?></span>
				<span class="dashicons dashicons-arrow-down-alt2 freefactu-daterange__arrow"></span>
			</button>
			
			<!-- Date Range Picker Panel -->
			<div class="freefactu-daterange__panel" id="freefactu-daterange-panel" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'Seleccionar rango de fechas', 'freefactu' ); ?>">
				<div class="freefactu-daterange__panel-inner">
					<!-- Presets Sidebar -->
					<div class="freefactu-daterange__presets">
						<button type="button" class="freefactu-daterange__preset" data-preset="this-month"><?php esc_html_e( 'Este mes', 'freefactu' ); ?></button>
						<button type="button" class="freefactu-daterange__preset" data-preset="last-month"><?php esc_html_e( 'Último mes', 'freefactu' ); ?></button>
						<div class="freefactu-daterange__preset-divider"></div>
						<button type="button" class="freefactu-daterange__preset" data-preset="q4"><?php esc_html_e( '4º Trimestre', 'freefactu' ); ?></button>
						<button type="button" class="freefactu-daterange__preset" data-preset="q3"><?php esc_html_e( '3r Trimestre', 'freefactu' ); ?></button>
						<button type="button" class="freefactu-daterange__preset" data-preset="q2"><?php esc_html_e( '2º Trimestre', 'freefactu' ); ?></button>
						<button type="button" class="freefactu-daterange__preset" data-preset="q1"><?php esc_html_e( '1r Trimestre', 'freefactu' ); ?></button>
						<div class="freefactu-daterange__preset-divider"></div>
						<button type="button" class="freefactu-daterange__preset" data-preset="this-year"><?php esc_html_e( 'Este año', 'freefactu' ); ?></button>
						<button type="button" class="freefactu-daterange__preset" data-preset="last-year"><?php esc_html_e( 'Año pasado', 'freefactu' ); ?></button>
						<div class="freefactu-daterange__preset-divider"></div>
						<button type="button" class="freefactu-daterange__preset freefactu-daterange__preset--clear" data-preset="clear"><?php esc_html_e( 'Borrar filtro', 'freefactu' ); ?></button>
					</div>
					
					<!-- Calendar Section -->
					<div class="freefactu-daterange__calendars">
						<!-- Selected Dates Display -->
						<div class="freefactu-daterange__selection">
							<div class="freefactu-daterange__date-field">
								<label><?php esc_html_e( 'Fecha inicio', 'freefactu' ); ?></label>
								<input type="text" id="freefactu-date-start-display" readonly placeholder="<?php esc_attr_e( 'Seleccionar', 'freefactu' ); ?>" value="<?php echo esc_attr( $filter_date_from ? date_i18n( 'j M Y', strtotime( $filter_date_from ) ) : '' ); ?>">
							</div>
							<span class="freefactu-daterange__date-separator">→</span>
							<div class="freefactu-daterange__date-field">
								<label><?php esc_html_e( 'Fecha fin', 'freefactu' ); ?></label>
								<input type="text" id="freefactu-date-end-display" readonly placeholder="<?php esc_attr_e( 'Seleccionar', 'freefactu' ); ?>" value="<?php echo esc_attr( $filter_date_to ? date_i18n( 'j M Y', strtotime( $filter_date_to ) ) : '' ); ?>">
							</div>
						</div>
						
						<!-- Scrollable Calendar Container -->
						<div class="freefactu-daterange__calendar-scroll" id="freefactu-calendar-scroll">
							<div class="freefactu-daterange__months-container" id="freefactu-months-container">
								<!-- Months will be rendered here by JavaScript -->
							</div>
						</div>
						
						<!-- Actions -->
						<div class="freefactu-daterange__actions">
							<button type="button" class="freefactu-daterange__btn freefactu-daterange__btn--cancel" id="freefactu-daterange-cancel">
								<?php esc_html_e( 'Cancelar', 'freefactu' ); ?>
							</button>
							<button type="button" class="freefactu-daterange__btn freefactu-daterange__btn--apply" id="freefactu-daterange-apply">
								<?php esc_html_e( 'Aplicar', 'freefactu' ); ?>
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<select id="filter_status" name="filter_status" class="freefactu-toolbar__select">
			<option value=""><?php esc_html_e( 'Todos', 'freefactu' ); ?></option>
			<option value="success" <?php selected( $filter_status, 'success' ); ?>><?php esc_html_e( 'Éxito', 'freefactu' ); ?></option>
			<option value="alert_aeat" <?php selected( $filter_status, 'alert_aeat' ); ?>><?php esc_html_e( 'Error AEAT', 'freefactu' ); ?></option>
			<option value="alert_qr" <?php selected( $filter_status, 'alert_qr' ); ?>><?php esc_html_e( 'Error QR', 'freefactu' ); ?></option>
		</select>
		
		<?php if ( $has_filters ) : ?>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=freefactu&tab=facturas' ) ); ?>" class="freefactu-toolbar__btn freefactu-toolbar__btn--clear" title="<?php esc_attr_e( 'Limpiar filtros', 'freefactu' ); ?>">
				<span class="dashicons dashicons-no-alt"></span>
			</a>
			<span class="freefactu-toolbar__count"><?php echo esc_html( number_format_i18n( $total_invoices ) ); ?></span>
		<?php endif; ?>
	</form>
	
	<!-- Spacer to push export to the right -->
	<div class="freefactu-toolbar__spacer"></div>
	
	<!-- Export Button -->
	<?php if ( class_exists( 'Freefactu_Export' ) ) : ?>
		<button type="button" id="freefactu-open-export-modal" class="freefactu-toolbar__btn freefactu-toolbar__btn--export" title="<?php esc_attr_e( 'Exportar facturas', 'freefactu' ); ?>">
			<span class="dashicons dashicons-download"></span>
			<span class="freefactu-toolbar__btn-text"><?php esc_html_e( 'Exportar', 'freefactu' ); ?></span>
		</button>
		<?php Freefactu_Export::render_export_modal(); ?>
	<?php endif; ?>
</div>


<table class="wp-list-table widefat fixed striped table-view-list freefactu-invoice-table">
	<thead>
		<tr>
			<th scope="col" class="column-order-id"><?php esc_html_e( 'ID Pedido', 'freefactu' ); ?></th>
			<th scope="col" class="column-invoice-number"><?php esc_html_e( 'Factura Verifactu', 'freefactu' ); ?></th>
			<th scope="col" class="column-date"><?php esc_html_e( 'Fecha', 'freefactu' ); ?></th>
			<th scope="col" class="column-total"><?php esc_html_e( 'Total', 'freefactu' ); ?></th>
			<th scope="col" class="column-qr"><?php esc_html_e( 'QR', 'freefactu' ); ?></th>
			<th scope="col"><?php esc_html_e( 'Estado', 'freefactu' ); ?></th>
			<th scope="col"><?php esc_html_e( 'Acciones', 'freefactu' ); ?></th>
		</tr>
	</thead>
	<tbody>
		<?php if ( ! empty( $invoices ) ) : ?>
			<?php 
			foreach ( $invoices as $freefactu_invoice ) :
				$order                  = wc_get_order( $freefactu_invoice->order_id );
				$freefactu_order_exists = $order ? true : false;
				
				// Generate QR data
				$freefactu_qr_img      = '';
				$freefactu_qr_data_uri = '';
				$freefactu_qr_url      = '';
				
				if ( $freefactu_invoice->csv ) {
					$freefactu_options     = get_option( 'freefactu_settings' );
					$freefactu_company_nif = isset( $freefactu_options['company_nif'] ) ? $freefactu_options['company_nif'] : '';
					$freefactu_env         = isset( $freefactu_options['environment'] ) ? $freefactu_options['environment'] : 'test';
					$freefactu_base_url    = ( $freefactu_env === 'production' ) 
						? 'https://www2.agenciatributaria.gob.es/wlpl/TIKE-CONT/ValidarQR?' 
						: 'https://prewww2.aeat.es/wlpl/TIKE-CONT/ValidarQR?';
					
					$freefactu_params = array(
						'nif'      => $freefactu_company_nif,
						'numserie' => $freefactu_invoice->invoice_number,
						'fecha'    => date_i18n( 'd-m-Y', strtotime( $freefactu_invoice->invoice_date ) ),
						'importe'  => number_format( $freefactu_invoice->total, 2, '.', '' ),
					);
					
					$freefactu_qr_url    = $freefactu_base_url . http_build_query( $freefactu_params );
					$freefactu_qr_base64 = Freefactu_History::generate_qr_code_base64( $freefactu_qr_url, 100 );
					
					if ( ! empty( $freefactu_qr_base64 ) && Freefactu_History::is_valid_data_uri( $freefactu_qr_base64 ) ) {
						$freefactu_qr_data_uri = $freefactu_qr_base64;
						$freefactu_qr_img      = 'HAS_QR';
					} else {
						$freefactu_qr_img = '<a href="' . esc_url( $freefactu_qr_url ) . '" target="_blank" title="' . esc_attr__( 'Verificar factura', 'freefactu' ) . '">' . esc_html__( 'Ver QR', 'freefactu' ) . '</a>';
					}
				}
				
				// Include the invoice row partial
				include FREEFACTU_PLUGIN_DIR . 'includes/admin/partials/invoice-row.php';
			endforeach; 
			?>
		<?php else : ?>
			<tr>
				<td colspan="7" class="freefactu-table-nopadding-cell">
					<div class="freefactu-empty-state-card">
						<div class="freefactu-empty-state-card-icon"><span class="dashicons dashicons-clipboard"></span></div>
						<h3 class="freefactu-empty-state-card-title">
							<?php esc_html_e( 'No hay facturas registradas', 'freefactu' ); ?>
						</h3>
						<p class="freefactu-empty-state-card-text">
							<?php esc_html_e( 'Las facturas se generan desde los pedidos de WooCommerce. Accede a la lista de pedidos para crear tu primera factura Verifactu.', 'freefactu' ); ?>
						</p>
						<?php
						// Dynamic HPOS-aware orders URL
						$freefactu_orders_url = class_exists( '\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController' )
							&& wc_get_container()->get( \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
							? admin_url( 'admin.php?page=wc-orders' )
							: admin_url( 'edit.php?post_type=shop_order' );
						?>
						<a href="<?php echo esc_url( $freefactu_orders_url ); ?>" class="button button-primary freefactu-btn-flex">
							<span class="dashicons dashicons-cart freefactu-icon-16"></span>
							<?php esc_html_e( 'Ir a Pedidos de WooCommerce', 'freefactu' ); ?>
						</a>
					</div>
				</td>
			</tr>
		<?php endif; ?>
	</tbody>
</table>

<?php if ( $total_pages > 1 ) : ?>
	<div class="tablenav bottom">
		<div class="tablenav-pages">
			<?php
			// Build base URL preserving filter parameters
			$freefactu_base_args = array( 'page' => 'freefactu', 'tab' => 'facturas' );
			if ( $filter_date_from ) {
				$freefactu_base_args['filter_date_from'] = $filter_date_from;
			}
			if ( $filter_date_to ) {
				$freefactu_base_args['filter_date_to'] = $filter_date_to;
			}
			if ( $filter_status ) {
				$freefactu_base_args['filter_status'] = $filter_status;
			}
			
			echo wp_kses_post( paginate_links( array(
				'base'      => add_query_arg( array_merge( $freefactu_base_args, array( 'paged' => '%#%' ) ), admin_url( 'admin.php' ) ),
				'format'    => '',
				'prev_text' => __( '&laquo;', 'freefactu' ),
				'next_text' => __( '&raquo;', 'freefactu' ),
				'total'     => $total_pages,
				'current'   => $paged,
			) ) );
			?>
		</div>
	</div>
<?php endif; ?>
