<?php
/**
 * Custom Fields — universal content tag replacement.
 *
 * Replaces {wp_powersuite_cf:group_key:field_name} in post content and widget text.
 *
 * @package CustomFields
 */

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

add_filter( 'the_content', 'wpps_cf_filter_content_tags', 18 );
add_filter( 'widget_text_content', 'wpps_cf_filter_content_tags', 18 );
add_filter( 'widget_block_content', 'wpps_cf_filter_content_tags', 18 );

function wpps_cf_filter_content_tags( string $content ): string {
	return wpps_cf_replace_content_tags( $content );
}

/**
 * Replace PowerSuite custom field tags in arbitrary content.
 */
function wpps_cf_replace_content_tags( string $content, ?int $post_id = null ): string {
	if ( strpos( $content, '{wp_powersuite_cf:' ) === false ) {
		return $content;
	}

	return (string) preg_replace_callback(
		'/\{wp_powersuite_cf:([^:}]+):([^}]+)\}/',
		static function ( array $matches ) use ( $post_id ): string {
			$group_key  = sanitize_key( $matches[1] );
			$field_name = sanitize_key( $matches[2] );
			if ( $group_key === '' || $field_name === '' ) {
				return '';
			}

			return \CustomFields\FieldOutput::render( $group_key, $field_name, $post_id );
		},
		$content
	);
}
