<?php
namespace WPVOID\StockBeacon\Core;

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

/**
 * Escapes spreadsheet cells for standards-compliant CSV output.
 */
final class CsvSanitizer {
	/**
	 * Neutralize formula-leading values before applying RFC 4180-style quoting.
	 *
	 * @param mixed $value Cell value.
	 */
	public static function escape_cell( $value ): string {
		$value = (string) $value;
		if ( preg_match( '/\A(?:[=+\-@]|\x09|\x0A|\x0D)/', $value ) ) {
			$value = "'" . $value;
		}

		$value = str_replace( '"', '""', $value );
		if ( str_contains( $value, ',' ) || str_contains( $value, '"' ) || str_contains( $value, "\n" ) || str_contains( $value, "\r" ) ) {
			return '"' . $value . '"';
		}

		return $value;
	}
}
