<?php
/**
 * Custom Fields — Bricks Builder Dynamic Data Integration.
 *
 * Usage: {wp_powersuite_cf:group_key:field_name}
 *
 * @package CustomFields
 */

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

function wpps_cf_bricks_register_tags( $tags ) {
	foreach ( \CustomFields\FieldOutput::integratableFields() as $field ) {
		$tags[] = [
			'name'  => '{wp_powersuite_cf:' . $field['group_key'] . ':' . $field['field_name'] . '}',
			'label' => sprintf(
				/* translators: 1: group title, 2: field label */
				__( '%1$s — %2$s', 'wppowersuite-lite' ),
				$field['group_label'],
				$field['field_label']
			),
			'group' => __( 'WP PowerSuite Fields', 'wppowersuite-lite' ),
		];
	}

	return $tags;
}

function wpps_cf_bricks_render_tag( $tag, $post, $context = 'text' ) {
	unset( $context );

	if ( ! is_string( $tag ) ) {
		return $tag;
	}

	$clean = str_replace( [ '{', '}' ], '', $tag );
	if ( strpos( $clean, 'wp_powersuite_cf:' ) !== 0 ) {
		return $tag;
	}

	$parts = explode( ':', $clean, 3 );
	if ( count( $parts ) < 3 ) {
		return $tag;
	}

	$group_key  = sanitize_key( $parts[1] );
	$field_name = sanitize_key( $parts[2] );
	if ( $group_key === '' || $field_name === '' ) {
		return '';
	}

	$post_id = 0;
	if ( $post instanceof \WP_Post ) {
		$post_id = (int) $post->ID;
	} elseif ( is_numeric( $post ) ) {
		$post_id = (int) $post;
	}

	if ( $post_id <= 0 ) {
		$post_id = (int) get_the_ID();
	}

	return \CustomFields\FieldOutput::render( $group_key, $field_name, $post_id > 0 ? $post_id : null );
}

function wpps_cf_bricks_render_content( $content, $post, $context = 'text' ) {
	if ( ! is_string( $content ) || strpos( $content, '{wp_powersuite_cf:' ) === false ) {
		return $content;
	}

	return preg_replace_callback(
		'/\{wp_powersuite_cf:([^:}]+):([^}]+)\}/',
		static function ( array $matches ) use ( $post, $context ): string {
			return wpps_cf_bricks_render_tag( $matches[0], $post, $context );
		},
		$content
	);
}

function wpps_cf_init_bricks(): void {
	static $initialized = false;
	if ( $initialized || ! defined( 'BRICKS_VERSION' ) ) {
		return;
	}

	$initialized = true;

	add_filter( 'bricks/dynamic_tags_list', 'wpps_cf_bricks_register_tags' );
	add_filter( 'bricks/dynamic_data/render_tag', 'wpps_cf_bricks_render_tag', 20, 3 );
	add_filter( 'bricks/dynamic_data/render_content', 'wpps_cf_bricks_render_content', 20, 3 );
	add_filter( 'bricks/frontend/render_data', 'wpps_cf_bricks_render_content', 20, 2 );
}

add_action( 'init', 'wpps_cf_init_bricks', 20 );
