<?php

namespace WPDRMS\ASP\Synonyms\Exporters;

use Exception;
use WPDRMS\ASP\Synonyms\ORM\Synonym;
use WPDRMS\PluginCore\Traits\SingletonTrait;

defined('ABSPATH') || die("You can't access this file directly.");

class SynonymsJSONExporter {
	use SingletonTrait;

	/**
	 * Returns all synonyms encoded as a JSON string.
	 *
	 * @throws Exception When there are no synonyms or encoding fails.
	 * @return string JSON content
	 */
	public function exportAll(): string {
		$rows = Synonym::exportAll();

		if ( empty($rows) ) {
			throw new Exception(__('No synonyms to export.', 'ajax-search-pro'));
		}

		$json = wp_json_encode($rows, JSON_PRETTY_PRINT);

		if ( $json === false ) {
			throw new Exception(__('Could not encode synonyms as JSON.', 'ajax-search-pro'));
		}

		return $json;
	}

	/**
	 * Streams the synonyms JSON as a file download and terminates execution.
	 *
	 * @throws Exception When there are no synonyms to export.
	 */
	public function download(): void {
		$content  = $this->exportAll();
		$filename = 'asp_synonyms_export_' . gmdate('Y-m-d_H-i-s') . '.json';

		nocache_headers();
		header('Content-Type: application/json; charset=UTF-8');
		header('Content-Disposition: attachment; filename="' . $filename . '"');
		header('Pragma: no-cache');
		header('Expires: 0');
		header('Content-Length: ' . strlen($content));

		echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		die();
	}
}
