<?php
/**
 * Custom Fields — Beaver Themer field connection integration.
 *
 * @package CustomFields
 */

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

add_action( 'fl_page_data_add_properties', 'wpps_cf_register_beaver_themer_properties' );

function wpps_cf_register_beaver_themer_properties(): void {
	if ( ! class_exists( 'FLPageData' ) ) {
		return;
	}

	\FLPageData::add_group(
		'wpps_cf',
		[
			'label' => __( 'WP PowerSuite Fields', 'wp-powersuite' ),
		]
	);

	\FLPageData::add_post_property(
		'wpps_cf_field',
		[
			'label'  => __( 'PowerSuite Custom Field', 'wp-powersuite' ),
			'group'  => 'wpps_cf',
			'type'   => [ 'string', 'url', 'html', 'photo' ],
			'getter' => 'wpps_cf_beaver_themer_getter',
		]
	);

	$field_options = [ '' => __( '— Select —', 'wp-powersuite' ) ];
	foreach ( \CustomFields\FieldOutput::integratableFields() as $field ) {
		$field_options[ $field['selection'] ] = $field['group_label'] . ' — ' . $field['field_label'];
	}

	\FLPageData::add_post_property_settings_fields(
		'wpps_cf_field',
		[
			'field'  => [
				'type'    => 'select',
				'label'   => __( 'Custom Field', 'wp-powersuite' ),
				'options' => $field_options,
			],
			'format' => [
				'type'    => 'select',
				'label'   => __( 'Output', 'wp-powersuite' ),
				'options' => [
					'display' => __( 'Display value', 'wp-powersuite' ),
					'raw'     => __( 'Raw stored value', 'wp-powersuite' ),
					'html'    => __( 'HTML', 'wp-powersuite' ),
					'url'     => __( 'URL', 'wp-powersuite' ),
					'text'    => __( 'Plain text', 'wp-powersuite' ),
				],
				'default' => 'display',
			],
		]
	);
}

/**
 * @param object $settings
 * @param string $property
 */
function wpps_cf_beaver_themer_getter( $settings, $property ): string {
	unset( $property );

	$selection = is_object( $settings ) && isset( $settings->field ) ? (string) $settings->field : '';
	$format    = is_object( $settings ) && isset( $settings->format ) ? sanitize_key( (string) $settings->format ) : 'display';

	if ( $selection === '' || strpos( $selection, ':' ) === false ) {
		return '';
	}

	$parts      = explode( ':', $selection, 2 );
	$group_key  = sanitize_key( $parts[0] );
	$field_name = sanitize_key( $parts[1] ?? '' );
	if ( $group_key === '' || $field_name === '' ) {
		return '';
	}

	return \CustomFields\FieldOutput::render(
		$group_key,
		$field_name,
		null,
		[ 'format' => $format ]
	);
}
