<?php
/**
 * Options Page Builder — Beaver Themer field connection integration.
 *
 * @package OptionsPageBuilder
 */

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

add_action( 'fl_page_data_add_properties', 'wpps_opb_register_beaver_themer_properties' );

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

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

	\FLPageData::add_post_property(
		'wpps_opb_field',
		[
			'label'  => __( 'PowerSuite Option', 'wp-powersuite' ),
			'group'  => 'wpps_opb',
			'type'   => [ 'string', 'url', 'html', 'photo' ],
			'getter' => 'wpps_opb_beaver_themer_getter',
		]
	);

	$field_options = [ '' => __( '— Select —', 'wp-powersuite' ) ];
	foreach ( wpps_opb_get_integratable_fields() as $field ) {
		$key = $field['page_slug'] . ':' . $field['field_id'];
		$field_options[ $key ] = $field['page_label'] . ' — ' . $field['field_label'];
	}

	\FLPageData::add_post_property_settings_fields(
		'wpps_opb_field',
		[
			'field' => [
				'type'    => 'select',
				'label'   => __( 'Option 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' ),
				],
				'default' => 'display',
			],
		]
	);
}

/**
 * @param object $settings
 * @param string $property
 */
function wpps_opb_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 );
	$page_slug = sanitize_key( $parts[0] );
	$field_id  = sanitize_key( $parts[1] ?? '' );
	if ( $page_slug === '' || $field_id === '' || ! wpps_opb_page_exists( $page_slug ) ) {
		return '';
	}

	return wpps_opb_render_field_output(
		$page_slug,
		$field_id,
		[ 'format' => $format ]
	);
}
