<?php
/**
 * Tao file .xlsx don gian (mot sheet).
 *
 * @package DatvetaucaotocBooking
 */

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Datvetau_Booking_Xlsx_Writer {

	/**
	 * @param array<int,array<int,string>> $rows
	 */
	public static function build( array $rows ): string {
		if ( ! class_exists( ZipArchive::class ) ) {
			return '';
		}
		$tmp = wp_tempnam( 'datvetau-import-sample.xlsx' );
		if ( ! $tmp ) {
			return '';
		}
		$zip = new ZipArchive();
		if ( true !== $zip->open( $tmp, ZipArchive::OVERWRITE ) ) {
			return '';
		}

		$sheet_xml = self::sheet_xml( $rows );
		$zip->addFromString( '[Content_Types].xml', self::content_types_xml() );
		$zip->addFromString( '_rels/.rels', self::root_rels_xml() );
		$zip->addFromString( 'xl/workbook.xml', self::workbook_xml() );
		$zip->addFromString( 'xl/_rels/workbook.xml.rels', self::workbook_rels_xml() );
		$zip->addFromString( 'xl/worksheets/sheet1.xml', $sheet_xml );
		$zip->addFromString( 'xl/styles.xml', self::styles_xml() );
		$zip->close();

		$bytes = (string) file_get_contents( $tmp );
		wp_delete_file( $tmp );
		return $bytes;
	}

	/**
	 * @param array<int,array<int,string>> $rows
	 */
	private static function sheet_xml( array $rows ): string {
		$lines = array( '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' );
		$lines[] = '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>';
		foreach ( $rows as $r_idx => $row ) {
			$row_num = $r_idx + 1;
			$lines[] = '<row r="' . $row_num . '">';
			foreach ( $row as $c_idx => $value ) {
				$ref = self::cell_ref( $c_idx, $row_num );
				$value = htmlspecialchars( (string) $value, ENT_XML1 | ENT_QUOTES, 'UTF-8' );
				if ( is_numeric( $value ) && '' !== $value && 0 === $c_idx && $row_num > 1 ) {
					// ngay co the la so serial — de dang text trong mau.
				}
				$lines[] = '<c r="' . $ref . '" t="inlineStr"><is><t>' . $value . '</t></is></c>';
			}
			$lines[] = '</row>';
		}
		$lines[] = '</sheetData></worksheet>';
		return implode( '', $lines );
	}

	private static function cell_ref( int $col, int $row ): string {
		$n       = $col + 1;
		$letters = '';
		while ( $n > 0 ) {
			--$n;
			$letters = chr( ord( 'A' ) + ( $n % 26 ) ) . $letters;
			$n       = (int) ( $n / 26 );
		}
		return $letters . (string) $row;
	}

	private static function content_types_xml(): string {
		return '<?xml version="1.0" encoding="UTF-8"?>'
			. '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
			. '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
			. '<Default Extension="xml" ContentType="application/xml"/>'
			. '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
			. '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
			. '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
			. '</Types>';
	}

	private static function root_rels_xml(): string {
		return '<?xml version="1.0" encoding="UTF-8"?>'
			. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
			. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
			. '</Relationships>';
	}

	private static function workbook_xml(): string {
		return '<?xml version="1.0" encoding="UTF-8"?>'
			. '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
			. 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
			. '<sheets><sheet name="Lich" sheetId="1" r:id="rId1"/></sheets></workbook>';
	}

	private static function workbook_rels_xml(): string {
		return '<?xml version="1.0" encoding="UTF-8"?>'
			. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
			. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'
			. '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
			. '</Relationships>';
	}

	private static function styles_xml(): string {
		return '<?xml version="1.0" encoding="UTF-8"?>'
			. '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>';
	}
}
