<?php
/**
 * XLSX format exporter using PhpSpreadsheet.
 *
 * @package Leadite
 */

namespace Leadite\Export;

defined( 'ABSPATH' ) || exit;

class XlsxExporter extends Exporter {

	public function format() {
		return 'xlsx';
	}

	public function mime_type() {
		return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
	}

	public function export( array $leads ) {
		if ( ! class_exists( '\PhpOffice\PhpSpreadsheet\Spreadsheet' ) ) {
			wp_die(
				esc_html__( 'PhpSpreadsheet library is not installed. Please run "composer install" in the Leadite plugin directory.', 'leadite' )
			);
		}

		// XLSX is a binary ZIP-based format: discard any open output buffers so
		// stray notices printed earlier cannot corrupt the file body.
		while ( ob_get_level() > 0 ) {
			ob_end_clean();
		}

		$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
		$sheet       = $spreadsheet->getActiveSheet();

		// Set Right-to-Left sheet orientation for RTL layouts.
		if ( is_rtl() ) {
			$sheet->setRightToLeft( true );
		}

		list( $headers, $rows ) = Helper::prepare_export_data( $leads );

		$sheet->fromArray( $headers, null, 'A1' );

		if ( ! empty( $rows ) ) {
			$sheet->fromArray( $rows, null, 'A2' );
		}

		$highest_col  = $sheet->getHighestColumn();
		$header_range = 'A1:' . $highest_col . '1';

		$sheet->getStyle( $header_range )->getFont()->setBold( true );

		// Safer than range('A', $highest_col), because it works after column Z.
		foreach ( $sheet->getColumnIterator() as $column ) {
			$sheet->getColumnDimension( $column->getColumnIndex() )->setAutoSize( true );
		}

		$filename = 'Leadite-export-' . gmdate( 'Y-m-d-His' ) . '.xlsx';
		$tmp_file = wp_tempnam( $filename );

		if ( ! $tmp_file ) {
			wp_die( esc_html__( 'Could not create temporary export file.', 'leadite' ) );
		}

		$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx( $spreadsheet );
		$writer->save( $tmp_file );

		$spreadsheet->disconnectWorksheets();
		unset( $spreadsheet );

		// Clean anything that WordPress/plugins may have buffered before download.
		while ( ob_get_level() > 0 ) {
			if ( ! @ob_end_clean() ) {
				break;
			}
		}

		if ( headers_sent() ) {
			wp_delete_file( $tmp_file );
			wp_die( esc_html__( 'Export headers were already sent. XLSX download cannot continue.', 'leadite' ) );
		}

		header_remove( 'Content-Type' );
		header_remove( 'Content-Disposition' );
		header_remove( 'Content-Encoding' );

		nocache_headers();

		header( 'Content-Type: ' . $this->mime_type() );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Transfer-Encoding: binary' );
		header( 'Content-Length: ' . filesize( $tmp_file ) );
		header( 'Cache-Control: max-age=0, no-cache, no-store, must-revalidate' );
		header( 'Pragma: public' );

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

		wp_delete_file( $tmp_file );

		exit;
	}
}