<?php
/**
 * Custom Fields — Divi dynamic content integration.
 *
 * @package CustomFields
 */

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

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

function wpps_cf_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_cf_divi_register_dynamic_fields', 10, 3 );
	add_filter( 'et_builder_dynamic_content_meta_value', 'wpps_cf_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_cf_divi_register_dynamic_fields( array $custom_fields, $post_id, $raw_custom_fields ): array {
	unset( $post_id, $raw_custom_fields );

	foreach ( \CustomFields\FieldOutput::integratableFields() as $field ) {
		$key       = 'wpps_cf_' . $field['group_key'] . '_' . $field['field_name'];
		$divi_type = in_array( $field['type'], [ 'image', 'file', 'gallery', 'url' ], true ) ? 'url' : 'text';

		$custom_fields[ $key ] = [
			'label'    => $field['group_label'] . ' — ' . $field['field_label'],
			'type'     => $divi_type,
			'meta_key' => 'wpps_cf:' . $field['group_key'] . ':' . $field['field_name'],
			'custom'   => true,
			'group'    => __( 'WP PowerSuite Fields', 'wp-powersuite' ),
		];
	}

	return $custom_fields;
}

function wpps_cf_divi_resolve_dynamic_value( $meta_value, $meta_key, $post_id ) {
	if ( ! is_string( $meta_key ) || strpos( $meta_key, 'wpps_cf:' ) !== 0 ) {
		return $meta_value;
	}

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

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

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

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