<?php
/**
 * Options Page Builder - Bricks Builder Dynamic Data Integration
 *
 * Registers dynamic data tags to use WP PowerSuite options page fields in Bricks.
 * Usage: {wp_powersuite_opb:page_slug:field_id}
 *
 * @package OptionsPageBuilder
 * @since 1.0.0
 */

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

/**
 * Register Bricks dynamic tags.
 */
function wpps_opb_bricks_register_tags( $tags ) {
	$pages = get_option( 'wp_powersuite_opb_pages', [] );
	if ( ! is_array( $pages ) || empty( $pages ) ) {
		return $tags;
	}

	foreach ( $pages as $p ) {
		if ( ! is_array( $p ) || empty( $p['slug'] ) || empty( $p['fields'] ) || ! is_array( $p['fields'] ) ) {
			continue;
		}

		$slug       = sanitize_key( $p['slug'] );
		$page_label = $p['page_title'] ?? $p['menu_title'] ?? $slug;

		foreach ( $p['fields'] as $field ) {
			if ( ! is_array( $field ) || in_array( $field['type'] ?? '', [ 'group', 'message' ], true ) ) {
				continue;
			}

			$field_id = $field['field_id'] ?? $field['id'] ?? '';
			if ( $field_id === '' ) {
				continue;
			}

			$field_label = $field['label'] ?? ucfirst( str_replace( '_', ' ', $field_id ) );

			$tags[] = [
				'name'  => '{wp_powersuite_opb:' . $slug . ':' . sanitize_key( $field_id ) . '}',
				'label' => sprintf(
					/* translators: 1: page title, 2: field label */
					__( '%1$s — %2$s', 'wppowersuite-lite' ),
					$page_label,
					$field_label
				),
				'group' => __( 'WP PowerSuite', 'wppowersuite-lite' ),
			];
		}
	}

	return $tags;
}

/**
 * Render Bricks dynamic tag.
 */
function wpps_opb_bricks_render_tag( $tag, $post, $context = 'text' ) {
	if ( ! is_string( $tag ) ) {
		return $tag;
	}

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

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

	$page_slug = sanitize_key( $parts[1] );
	$field_id  = sanitize_key( $parts[2] );

	if ( empty( $page_slug ) || empty( $field_id ) ) {
		return $tag;
	}

	if ( ! wpps_opb_page_exists( $page_slug ) ) {
		return '';
	}

	return wpps_opb_render_field_output( $page_slug, $field_id );
}

/**
 * Render tag in content (for bricks/dynamic_data/render_content and bricks/frontend/render_data).
 */
function wpps_opb_bricks_render_content( $content, $post, $context = 'text' ) {
	if ( strpos( $content, '{wp_powersuite_opb:' ) === false ) {
		return $content;
	}

	$content = preg_replace_callback( '/\{wp_powersuite_opb:([^:]+):([^}]+)\}/', function( $m ) use ( $post, $context ) {
		$tag = $m[0];
		return wpps_opb_bricks_render_tag( $tag, $post, $context );
	}, $content );

	return $content;
}

/**
 * Register Bricks integrations.
 */
function wpps_opb_init_bricks() {
	if ( ! defined( 'BRICKS_VERSION' ) ) {
		return;
	}
	add_filter( 'bricks/dynamic_tags_list', 'wpps_opb_bricks_register_tags' );
	add_filter( 'bricks/dynamic_data/render_tag', 'wpps_opb_bricks_render_tag', 20, 3 );
	add_filter( 'bricks/dynamic_data/render_content', 'wpps_opb_bricks_render_content', 20, 3 );
	add_filter( 'bricks/frontend/render_data', 'wpps_opb_bricks_render_content', 20, 2 );
}

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