<?php

namespace WPDRMS\ASP\Statistics\Exporters;

use Exception;
use WPDRMS\PluginCore\Traits\SingletonTrait;
use WPDRMS\ASP\Statistics\StatisticsService;

/**
 * CSV Exporter for pre 4.28.0 statistics
 */
class LegacyCSVExporter {
	use SingletonTrait;

	/**
	 * Export old legacy stats to CSV
	 *
	 * @throws Exception
	 */
	public function getAllStatsToCSV(): void {
		global $wpdb;

		$filename   = 'stats_' . date( 'Y-m-d_H-i-s' ) . '.csv';
		$db_handler = \WPDRMS\ASP\Database\Manager::instance();

		nocache_headers();
		header( 'Content-Type: text/csv; charset=UTF-8' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// UTF-8 BOM for proper Excel support
		echo "\xEF\xBB\xBF";

		$output = fopen( 'php://output', 'w' );

		if ( $output === false ) {
			throw new Exception( "Couldn't open php://output for writing." );
		}

		if ( !$db_handler->exists('stats') || $db_handler->count('stats') === 0 ) {
			throw new Exception( 'No data found.' );
		}

		$headers = array(
			'Search ID',
			'Keyword',
			'Search count',
		);

		fputcsv( $output, $headers, ',', '"', '\\' );

		$results = $wpdb->get_results('SELECT search_id, keyword, num FROM ' . $db_handler->table('stats')); // phpcs:ignore


		foreach ( $results as $row ) {
			$line = array(
				$row->search_id,
				$row->keyword,
				$row->num,
			);

			fputcsv( $output, $line, ',', '"', '\\' );
		}

		fclose( $output ); // phpcs:ignore
		die();
	}
}
