<?php
/**
 * CSV Exporter for Redirects
 *
 * @package SEOvaultSEO\RedirectManager
 */

namespace SEOvaultSEO\RedirectManager;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Exports redirects to CSV format.
 */
class CsvExporter {

	/**
	 * Export an array of redirects to a CSV string.
	 *
	 * @param Redirect[] $redirects Redirects to export.
	 * @return string CSV string with headers.
	 */
	public function export( array $redirects ) {
		$csv = $this->get_headers();

		foreach ( $redirects as $redirect ) {
			if ( $redirect instanceof Redirect ) {
				$csv .= PHP_EOL . $this->format_row( $redirect );
			}
		}

		return $csv;
	}

	/**
	 * Format a single redirect as a CSV row.
	 *
	 * @param Redirect $redirect Redirect to format.
	 * @return string
	 */
	protected function format_row( Redirect $redirect ) {
		$origin = $redirect->get_origin();
		$target = $redirect->get_target();

		// Add leading slash for relative URLs in plain format.
		if ( Redirect::FORMAT_PLAIN === $redirect->get_format() && '' !== $origin && '/' !== $origin[0] && ! preg_match( '#^https?://#', $origin ) ) {
			$origin = '/' . $origin;
		}

		if ( '' !== $target && '/' !== $target[0] && ! preg_match( '#^https?://#', $target ) ) {
			$target = '/' . $target;
		}

		$columns = array(
			$this->escape_csv_field( $origin ),
			$this->escape_csv_field( $target ),
			$this->escape_csv_field( $redirect->get_type() ),
			$this->escape_csv_field( $redirect->get_format() ),
		);

		return implode( ',', $columns );
	}

	/**
	 * Get the CSV header row.
	 *
	 * @return string
	 */
	protected function get_headers() {
		$headers = array(
			__( 'Origin', 'seovault-ai' ),
			__( 'Target', 'seovault-ai' ),
			__( 'Type', 'seovault-ai' ),
			__( 'Format', 'seovault-ai' ),
		);

		return implode( ',', array_map( array( $this, 'escape_csv_field' ), $headers ) );
	}

	/**
	 * Escape a CSV field value (wrap in quotes, escape inner quotes).
	 *
	 * @param string $value Value to escape.
	 * @return string
	 */
	protected function escape_csv_field( $value ) {
		return '"' . str_replace( '"', '""', (string) $value ) . '"';
	}
}
