<?php
/**
 * Plain Text Sanitizer
 *
 * @package AIPT\Api\BulkGenerator\Standard\Core
 * @since 2.5.0
 */

namespace AIPT\Api\BulkGenerator\Standard\Core;

class PlainTextSanitizer {

	public static function sanitize( string $text ): string {
		$text = preg_replace( '/<\/(p|div|h[1-6]|li|blockquote)>/i', "</$1>\n\n", $text );
		$text = preg_replace( '/<br\s*\/?>/i', "\n", $text );

		$text = wp_strip_all_tags( $text );

		$text = preg_replace( '/\*\*(.*?)\*\*/', '$1', $text );
		$text = preg_replace( '/\*(.*?)\*/', '$1', $text );
		$text = preg_replace( '/__(.*?)__/', '$1', $text );
		$text = preg_replace( '/_(.*?)_/', '$1', $text );
		$text = preg_replace( '/`(.*?)`/', '$1', $text );
		$text = preg_replace( '/\[(.*?)\]\(.*?\)/', '$1', $text );

		$text = preg_replace( '/^#+\s*(.*)$/m', '$1', $text );
		$text = preg_replace( '/^\s*[-\*\+•]\s*(.*)$/m', '$1', $text );
		$text = preg_replace( '/^\s*\d+\.\s*(.*)$/m', '$1', $text );
		$text = preg_replace( '/^\s*[a-zA-Z]\.\s*(.*)$/m', '$1', $text );
		$text = preg_replace( '/^\s*[IVX]+\.\s*(.*)$/m', '$1', $text );

		$text = preg_replace( '/\n{3,}/', "\n\n", $text );
		$text = preg_replace( '/[^\S\n]+/', ' ', $text );
		$text = preg_replace( '/^[ \t]+|[ \t]+$/m', '', $text );

		return trim( $text );
	}

	public static function sanitizeTags( string $text ): string {
		$text = wp_strip_all_tags( $text );
		$text = preg_replace( '/\*\*(.*?)\*\*/', '$1', $text );
		$text = preg_replace( '/\*(.*?)\*/', '$1', $text );
		$text = preg_replace( '/\n+/', ', ', $text );
		$text = preg_replace( '/,\s*,/', ',', $text );
		$text = preg_replace( '/\s+/', ' ', $text );

		return trim( $text, ', ' );
	}
}
