<?php
/**
 * Options Page Builder — Divi dynamic content integration.
 *
 * @package OptionsPageBuilder
 */

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

add_action( 'init', 'wpps_opb_init_divi_integration', 25 );

function wpps_opb_init_divi_integration(): void {
	if ( ! defined( 'ET_BUILDER_VERSION' ) && ! function_exists( 'et_builder_get_dynamic_content_fields' ) ) {
		return;
	}

	add_filter( 'et_builder_custom_dynamic_content_fields', 'wpps_opb_divi_register_dynamic_fields', 10, 3 );
	add_filter( 'et_builder_dynamic_content_meta_value', 'wpps_opb_divi_resolve_dynamic_value', 10, 3 );
}

/**
 * @param array<string, array<string, mixed>> $custom_fields
 * @param mixed[]                           $raw_custom_fields
 * @return array<string, array<string, mixed>>
 */
function wpps_opb_divi_register_dynamic_fields( array $custom_fields, $post_id, $raw_custom_fields ): array {
	unset( $post_id, $raw_custom_fields );

	foreach ( wpps_opb_get_integratable_fields() as $field ) {
		$key      = 'wpps_opb_' . $field['page_slug'] . '_' . $field['field_id'];
		$divi_type = in_array( $field['type'], [ 'image', 'file', 'url' ], true ) ? 'url' : 'text';

		$custom_fields[ $key ] = [
			'label'    => $field['page_label'] . ' — ' . $field['field_label'],
			'type'     => $divi_type,
			'meta_key' => 'wpps_opb:' . $field['page_slug'] . ':' . $field['field_id'],
			'custom'   => true,
			'group'    => __( 'WP PowerSuite', 'wp-powersuite' ),
		];
	}

	return $custom_fields;
}

function wpps_opb_divi_resolve_dynamic_value( $meta_value, $meta_key, $post_id ) {
	unset( $post_id );

	if ( ! is_string( $meta_key ) || strpos( $meta_key, 'wpps_opb:' ) !== 0 ) {
		return $meta_value;
	}

	$parts = explode( ':', $meta_key, 3 );
	if ( count( $parts ) !== 3 ) {
		return $meta_value;
	}

	$page_slug = sanitize_key( $parts[1] );
	$field_id  = sanitize_key( $parts[2] );
	if ( $page_slug === '' || $field_id === '' || ! wpps_opb_page_exists( $page_slug ) ) {
		return '';
	}

	return wpps_opb_render_field_output( $page_slug, $field_id );
}
