<?php
/**
 * File Path: includes/export/class-mbs-exporter-xlsx.php
 *
 * XLSX Exporter (PRO)
 *
 * Streams all published mbs_book posts and their active format rows as a
 * downloadable XLSX file. Column headers match MBS_Importer_CSV::ACCEPTED_COLUMNS
 * exactly, mirroring the structure of the CSV exporter for round-trip compatibility.
 *
 * Each format row is exported as one worksheet row. A book with three formats
 * (paperback, ebook, hardcover) produces three rows, all sharing the same
 * title, author, publisher, and post-level metadata.
 *
 * Data helpers (column_headers, get_book_data, build_row, safe_cell) are
 * provided by MBS_Book_Export_Data (D-001, D-002, D-003).
 *
 * Gates: mbs_is_registered() + mbs_is_pro() (GP-T-1).
 * Output: direct HTTP stream -- calls exit on completion.
 * SQL: all queries go through MBS_Format_Row_DAO (GP-SQL-1).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Exporter_XLSX { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Stream an XLSX export to the browser and exit.
	 *
	 * Called directly by the mbs_export_xlsx AJAX handler after nonce and
	 * capability checks have already passed. This method enforces its own
	 * license gates as a defense-in-depth measure (GP-T-1).
	 *
	 * @return void Does not return -- exits after streaming.
	 */
	public static function download(): void {
		if ( ! mbs_is_registered() ) {
			wp_die( esc_html__( 'A valid license is required to export books.', 'my-book-showroom' ), 403 );
		}

		if ( ! mbs_is_pro() ) {
			wp_die( esc_html__( 'XLSX export requires a PRO license.', 'my-book-showroom' ), 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to export books.', 'my-book-showroom' ), 403 );
		}

		// -- Gather rows (D-009) -----------------------------------------------

		$rows = array_merge(
			array( MBS_Book_Export_Data::column_headers() ),
			MBS_Book_Export_Data::collect_all_rows()
		);

		// -- Build XLSX via MBS_XLSX_Builder (REF-22) ---------------------------

		$temp_dir = trailingslashit( get_temp_dir() ) . 'mbs-temp-export' . DIRECTORY_SEPARATOR;
		wp_mkdir_p( $temp_dir );

		$temp_path = $temp_dir . 'export_' . get_current_user_id() . '_' . uniqid() . '.xlsx';

		$build = MBS_XLSX_Builder::build( $rows, $temp_path );

		if ( is_wp_error( $build ) ) {
			wp_die( esc_html( $build->get_error_message() ), 500 );
		}

		// -- Stream to browser -------------------------------------------------

		$filename = 'mbs-books-' . gmdate( 'Y-m-d' ) . '.xlsx';

		while ( ob_get_level() ) {
			ob_end_clean();
		}

		header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_filesize
		header( 'Content-Length: ' . filesize( $temp_path ) );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
		readfile( $temp_path );

		wp_delete_file( $temp_path );

		exit;
	}
}
