<?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', 'wppowersuite-lite' ),
		]
	);

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

	$field_options = [ '' => __( '— Select —', 'wppowersuite-lite' ) ];
	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', 'wppowersuite-lite' ),
				'options' => $field_options,
			],
			'format' => [
				'type'    => 'select',
				'label'   => __( 'Output', 'wppowersuite-lite' ),
				'options' => [
					'display' => __( 'Display value', 'wppowersuite-lite' ),
					'raw'     => __( 'Raw stored value', 'wppowersuite-lite' ),
					'html'    => __( 'HTML', 'wppowersuite-lite' ),
					'url'     => __( 'URL', 'wppowersuite-lite' ),
				],
				'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 ]
	);
}
