<?php
/**
 * Freefactu Export Class
 *
 * Handles export functionality for VeriFactu invoices in XML and CSV formats.
 * Required for AEAT inspection compliance (§12.3 of compliance checklist).
 *
 * @package Freefactu
 * @since 1.1.0
 */

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

class Freefactu_Export {

	/**
	 * Initialize export handlers.
	 */
	public static function init() {
		add_action( 'admin_post_freefactu_export_csv', array( __CLASS__, 'handle_csv_export' ) );
		add_action( 'admin_post_freefactu_export_xml', array( __CLASS__, 'handle_xml_export' ) );
	}

	/**
	 * Handle CSV export request.
	 *
	 * @return void
	 */
	public static function handle_csv_export() {
		// Verify permissions
		if ( ! current_user_can( 'manage_verifactu' ) ) {
			wp_die( esc_html__( 'No tienes permisos para exportar datos.', 'freefactu' ) );
		}

		// Verify nonce
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'freefactu_export' ) ) {
			wp_die( esc_html__( 'Error de seguridad. Por favor, recarga la página.', 'freefactu' ) );
		}

		// Get date range
		$date_from = isset( $_GET['date_from'] ) ? sanitize_text_field( wp_unslash( $_GET['date_from'] ) ) : '';
		$date_to = isset( $_GET['date_to'] ) ? sanitize_text_field( wp_unslash( $_GET['date_to'] ) ) : '';

		// Get invoices
		$invoices = self::get_invoices_for_export( $date_from, $date_to );

		if ( empty( $invoices ) ) {
			wp_die( esc_html__( 'No se encontraron facturas en el rango de fechas especificado.', 'freefactu' ) );
		}

		// Generate filename
		$filename = 'freefactu_export_' . gmdate( 'Y-m-d_H-i-s' ) . '.csv';

		// Set headers for CSV download
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $filename ) . '"' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// Create output stream
		$output = fopen( 'php://output', 'w' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen

		// Add BOM for Excel UTF-8 compatibility
		fprintf( $output, chr( 0xEF ) . chr( 0xBB ) . chr( 0xBF ) );

		// Write CSV header
		fputcsv( $output, array(
			__( 'Número Factura', 'freefactu' ),
			__( 'Fecha', 'freefactu' ),
			__( 'Pedido', 'freefactu' ),
			__( 'Total', 'freefactu' ),
			__( 'CSV AEAT', 'freefactu' ),
			__( 'Hash', 'freefactu' ),
			__( 'Estado', 'freefactu' ),
			__( 'Error', 'freefactu' ),
		), ';' ); // Use semicolon for Spanish Excel compatibility

		// Write invoice data
		foreach ( $invoices as $invoice ) {
			fputcsv( $output, array(
				$invoice->invoice_number,
				$invoice->invoice_date,
				$invoice->order_id,
				number_format( $invoice->total, 2, ',', '.' ),
				$invoice->csv,
				$invoice->hash,
				self::get_status_label( $invoice->status ),
				$invoice->error_message,
			), ';' );
		}

		fclose( $output ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
		exit;
	}

	/**
	 * Handle XML export request.
	 *
	 * @return void
	 */
	public static function handle_xml_export() {
		// Verify permissions
		if ( ! current_user_can( 'manage_verifactu' ) ) {
			wp_die( esc_html__( 'No tienes permisos para exportar datos.', 'freefactu' ) );
		}

		// Verify nonce
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'freefactu_export' ) ) {
			wp_die( esc_html__( 'Error de seguridad. Por favor, recarga la página.', 'freefactu' ) );
		}

		// Get date range
		$date_from = isset( $_GET['date_from'] ) ? sanitize_text_field( wp_unslash( $_GET['date_from'] ) ) : '';
		$date_to = isset( $_GET['date_to'] ) ? sanitize_text_field( wp_unslash( $_GET['date_to'] ) ) : '';

		// Get invoices
		$invoices = self::get_invoices_for_export( $date_from, $date_to );

		if ( empty( $invoices ) ) {
			wp_die( esc_html__( 'No se encontraron facturas en el rango de fechas especificado.', 'freefactu' ) );
		}

		// Get company info
		$options = get_option( 'freefactu_settings' );
		$company_name = isset( $options['company_name'] ) ? $options['company_name'] : '';
		$company_nif = isset( $options['company_nif'] ) ? $options['company_nif'] : '';

		// Generate filename
		$filename = 'freefactu_export_' . gmdate( 'Y-m-d_H-i-s' ) . '.xml';

		// Set headers for XML download
		header( 'Content-Type: application/xml; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $filename ) . '"' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// Create XML document
		$dom = new DOMDocument( '1.0', 'UTF-8' );
		$dom->formatOutput = true;

		// Root element
		$root = $dom->createElement( 'ExportacionFacturasVerifactu' );
		$root->setAttribute( 'xmlns', 'https://freefactu.es/export/v1' );
		$root->setAttribute( 'version', '1.0' );
		$root->setAttribute( 'fechaExportacion', gmdate( 'c' ) );
		$dom->appendChild( $root );

		// Obligado section
		$obligado = $dom->createElement( 'ObligadoEmision' );
		$root->appendChild( $obligado );
		$obligado->appendChild( $dom->createElement( 'NombreRazon', $company_name ) );
		$obligado->appendChild( $dom->createElement( 'NIF', $company_nif ) );

		// Export range
		$rango = $dom->createElement( 'RangoExportacion' );
		$root->appendChild( $rango );
		if ( $date_from ) {
			$rango->appendChild( $dom->createElement( 'FechaDesde', $date_from ) );
		}
		if ( $date_to ) {
			$rango->appendChild( $dom->createElement( 'FechaHasta', $date_to ) );
		}
		$rango->appendChild( $dom->createElement( 'TotalFacturas', count( $invoices ) ) );

		// Invoices
		$facturas = $dom->createElement( 'Facturas' );
		$root->appendChild( $facturas );

		foreach ( $invoices as $invoice ) {
			$factura = $dom->createElement( 'Factura' );
			$facturas->appendChild( $factura );

			// Invoice identification
			$id_factura = $dom->createElement( 'IDFactura' );
			$factura->appendChild( $id_factura );
			$id_factura->appendChild( $dom->createElement( 'IDEmisorFactura', $company_nif ) );
			$id_factura->appendChild( $dom->createElement( 'NumSerieFactura', $invoice->invoice_number ) );
			$id_factura->appendChild( $dom->createElement( 'FechaExpedicionFactura', gmdate( 'd-m-Y', strtotime( $invoice->invoice_date ) ) ) );

			// Financial data
			$factura->appendChild( $dom->createElement( 'ImporteTotal', number_format( $invoice->total, 2, '.', '' ) ) );

			// AEAT confirmation
			$aeat = $dom->createElement( 'ConfirmacionAEAT' );
			$factura->appendChild( $aeat );
			$aeat->appendChild( $dom->createElement( 'CSV', $invoice->csv ) );
			$aeat->appendChild( $dom->createElement( 'Huella', $invoice->hash ) );

			// Status
			$factura->appendChild( $dom->createElement( 'Estado', $invoice->status ) );

			// Order reference
			$factura->appendChild( $dom->createElement( 'ReferenciaWooCommerce', $invoice->order_id ) );
		}

		// Summary
		$resumen = $dom->createElement( 'Resumen' );
		$root->appendChild( $resumen );
		
		$total_sum = array_sum( array_column( $invoices, 'total' ) );
		$success_count = count( array_filter( $invoices, function( $inv ) { return $inv->status === 'success'; } ) );
		$alert_count = count( $invoices ) - $success_count;

		$resumen->appendChild( $dom->createElement( 'TotalFacturas', count( $invoices ) ) );
		$resumen->appendChild( $dom->createElement( 'FacturasExitosas', $success_count ) );
		$resumen->appendChild( $dom->createElement( 'FacturasConAlerta', $alert_count ) );
		$resumen->appendChild( $dom->createElement( 'ImporteTotalExportado', number_format( $total_sum, 2, '.', '' ) ) );

		echo $dom->saveXML(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Get invoices for export within date range.
	 *
	 * @param string $date_from Start date (Y-m-d format).
	 * @param string $date_to End date (Y-m-d format).
	 * @return array Array of invoice objects.
	 */
	private static function get_invoices_for_export( $date_from = '', $date_to = '' ) {
		global $wpdb;
		$table_name = Freefactu_DB::get_table_name();

$query = "SELECT * FROM " . esc_sql( $table_name ) . " WHERE 1=1";
		$params = array();

		if ( ! empty( $date_from ) ) {
			$query .= " AND invoice_date >= %s";
			$params[] = $date_from . ' 00:00:00';
		}

		if ( ! empty( $date_to ) ) {
			$query .= " AND invoice_date <= %s";
			$params[] = $date_to . ' 23:59:59';
		}

		$query .= " ORDER BY invoice_date ASC";

		if ( ! empty( $params ) ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			$sql = $wpdb->prepare( $query, $params );
		} else {
			$sql = $query;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
		return $wpdb->get_results( $sql );
	}

	/**
	 * Get human-readable status label.
	 *
	 * @param string $status Internal status code.
	 * @return string Translated status label.
	 */
	private static function get_status_label( $status ) {
		$labels = array(
			'success'    => __( 'Éxito', 'freefactu' ),
			'alert_aeat' => __( 'Error AEAT', 'freefactu' ),
			'alert_qr'   => __( 'Error QR', 'freefactu' ),
			'alert_pdf'  => __( 'Error PDF', 'freefactu' ),
		);

		return isset( $labels[ $status ] ) ? $labels[ $status ] : $status;
	}

	/**
	 * Render export UI section for history page.
	 * Shows a button that opens the export modal.
	 *
	 * @return void
	 */
	public static function render_export_section() {
		?>
		<div class="freefactu-export-trigger" style="margin-bottom: 20px;">
			<button type="button" id="freefactu-open-export-modal" class="button button-secondary" style="display: inline-flex; align-items: center; gap: 6px;">
				<span class="dashicons dashicons-download" style="font-size: 18px; width: 18px; height: 18px;"></span>
				<?php esc_html_e( 'Exportar facturas', 'freefactu' ); ?>
			</button>
		</div>
		<?php
		// Also render the modal container (hidden by default)
		self::render_export_modal();
	}

	/**
	 * Render the export modal dialog.
	 *
	 * @return void
	 */
	public static function render_export_modal() {
		$nonce = wp_create_nonce( 'freefactu_export' );
		?>
		<div id="freefactu-export-modal-overlay" class="freefactu-export-modal-overlay">
			<div class="freefactu-export-modal" role="dialog" aria-labelledby="freefactu-export-modal-title" aria-modal="true">
				<div class="freefactu-export-modal-header">
					<h2 id="freefactu-export-modal-title">
						<span class="dashicons dashicons-download"></span>
						<?php esc_html_e( 'Exportar Facturas', 'freefactu' ); ?>
					</h2>
					<button type="button" class="freefactu-export-modal-close" aria-label="<?php esc_attr_e( 'Cerrar', 'freefactu' ); ?>">
						<span class="dashicons dashicons-no-alt"></span>
					</button>
				</div>
				<div class="freefactu-export-modal-body">
					<p class="freefactu-export-description">
						<?php esc_html_e( 'Selecciona el rango de fechas y el formato para exportar tus facturas. Deja las fechas vacías para exportar todas las facturas.', 'freefactu' ); ?>
					</p>
					
					<form method="get" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="freefactu-export-form">
						<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( $nonce ); ?>">
						
						<div class="freefactu-export-dates">
							<div class="freefactu-export-field">
								<label for="export_date_from">
									<?php esc_html_e( 'Fecha desde', 'freefactu' ); ?>
								</label>
								<input type="date" id="export_date_from" name="date_from">
							</div>
							
							<div class="freefactu-export-field">
								<label for="export_date_to">
									<?php esc_html_e( 'Fecha hasta', 'freefactu' ); ?>
								</label>
								<input type="date" id="export_date_to" name="date_to">
							</div>
						</div>
						
						<div class="freefactu-export-formats">
							<p class="freefactu-export-formats-title"><?php esc_html_e( 'Formato de exportación:', 'freefactu' ); ?></p>
							
							<div class="freefactu-export-buttons">
								<button type="submit" name="action" value="freefactu_export_csv" class="button button-hero">
									<span class="dashicons dashicons-media-spreadsheet"></span>
									<span class="freefactu-export-btn-content">
										<strong><?php esc_html_e( 'Exportar CSV', 'freefactu' ); ?></strong>
										<small><?php esc_html_e( 'Compatible con Excel y hojas de cálculo', 'freefactu' ); ?></small>
									</span>
								</button>
								
								<button type="submit" name="action" value="freefactu_export_xml" class="button button-hero">
									<span class="dashicons dashicons-media-code"></span>
									<span class="freefactu-export-btn-content">
										<strong><?php esc_html_e( 'Exportar XML', 'freefactu' ); ?></strong>
										<small><?php esc_html_e( 'Compatible con inspecciones AEAT', 'freefactu' ); ?></small>
									</span>
								</button>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
		<?php
	}
}

