<?php
defined( 'ABSPATH' ) || exit;

/**
 * Small text extraction helpers used by the WordPress publisher.
 */
final class Costudio_Publisher_Text_Extractor {

	private function __construct() {
	}

	public static function line( string $content, array $markers ): string {
		foreach ( $markers as $marker ) {
			if ( preg_match( '/' . preg_quote( $marker, '/' ) . ':\s*([^\n]+)/i', $content, $m ) ) {
				return trim( str_replace( array( '**', '__' ), '', wp_strip_all_tags($m[1] ) ) );
			}
			if ( preg_match( '/' . preg_quote( $marker, '/' ) . '\s*\n+\s*(.+?)(?:\n|$)/i', $content, $m ) ) {
				return trim( str_replace( array( '**', '__' ), '', wp_strip_all_tags($m[1] ) ) );
			}
		}
		return '';
	}

	/**
	 * @param string       $content
	 * @param string|array $label
	 */
	public static function labeled( string $content, $label ): string {
		$labels = (array) $label;
		foreach ( $labels as $l ) {
			$pattern = '/(?:^|\n)\*?\*?' . preg_quote( $l, '/' ) . '\*?\*?:?\s*(.+?)(?:\n|$)/i';
			if ( preg_match( $pattern, $content, $m ) ) {
				return trim( str_replace( array( '**', '__' ), '', wp_strip_all_tags($m[1] ) ) );
			}
		}
		return '';
	}

	public static function tag( string $content, string $tag ): string {
		$pattern = '/\[' . preg_quote( $tag, '/' ) . '\](.*?)\[\/' . preg_quote( $tag, '/' ) . '\]/si';
		if ( preg_match( $pattern, $content, $m ) ) {
			return trim( wp_strip_all_tags($m[1] ) );
		}
		return '';
	}
}
