<?php

namespace WDevs\CustomerOrderExport\Generators;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use WDevs\CustomerOrderExport\Template;

/**
 * Handles the generation of CSV files for WooCommerce order items
 *
 * This class is responsible for generating CSV files containing order item data using the PhpSpreadsheet library.
 *
 * @since      1.0.0
 * @package    Wdevs_Customer_Order_Export
 * @subpackage Wdevs_Customer_Order_Export/includes/Generators
 * @author     Wijnberg Developments <contact@wijnberg.dev>
 */
class CsvGenerator extends FileProcessor implements FileGeneratorInterface {

	/**
	 * Generates a CSV file for a specified WooCommerce order
	 *
	 * @param Template $template The template configuration object
	 * @param string $file_name The name/path for the output file
	 * @param int|null $order_id The ID of the WooCommerce order to process.
	 *                          If null, processes all orders or uses template default
	 * @param string $delimiter The delimiter character to use in output (default: ',')
	 * @return string The full file path of the generated output
	 *
	 * @since 1.0.0
	 */
	public function generate( $template, $file_name, $order_id = null, $delimiter = ',' ) {

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

		$this->set_flattened_selected_columns($template->get_selected_columns_flattened());

		$headers = $this->get_file_headers();

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

		$rows = $this->get_file_rows($order_id);

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

		$writer = new Csv( $spreadsheet );

		$writer->setDelimiter( $delimiter );

		$file_path = $this->get_file_path($file_name, 'csv');
		$writer->save( $file_path );

		return $file_path;
	}
}