<?php
/**
 * Custom Fields — Gutenberg block integration.
 *
 * @package CustomFields
 */

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

add_action( 'init', 'wpps_cf_register_gutenberg_block', 20 );
add_action( 'enqueue_block_editor_assets', 'wpps_cf_enqueue_block_editor_assets' );

function wpps_cf_register_block_editor_script(): void {
	$path = dirname( __DIR__ ) . '/assets/cf-block-editor.js';
	if ( ! is_readable( $path ) || wp_script_is( 'wpps-cf-block-editor', 'registered' ) ) {
		return;
	}

	$plugin_file = defined( 'WP_POWERSUITE_PLUGIN_FILE' ) ? WP_POWERSUITE_PLUGIN_FILE : dirname( __DIR__, 3 ) . '/wp-powersuite.php';
	wp_register_script(
		'wpps-cf-block-editor',
		plugins_url( 'modules/custom-fields/assets/cf-block-editor.js', $plugin_file ),
		[ 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ],
		(string) filemtime( $path ),
		true
	);
}

function wpps_cf_register_gutenberg_block(): void {
	if ( ! function_exists( 'register_block_type' ) ) {
		return;
	}

	wpps_cf_register_block_editor_script();

	register_block_type(
		'wp-powersuite/custom-field',
		[
			'api_version'     => 2,
			'title'           => __( 'PowerSuite Custom Field', 'wp-powersuite' ),
			'description'     => __( 'Display a custom field value from the current post.', 'wp-powersuite' ),
			'category'        => 'widgets',
			'icon'            => 'list-view',
			'attributes'      => [
				'groupKey' => [
					'type'    => 'string',
					'default' => '',
				],
				'fieldName' => [
					'type'    => 'string',
					'default' => '',
				],
				'format' => [
					'type'    => 'string',
					'default' => 'display',
				],
				'defaultValue' => [
					'type'    => 'string',
					'default' => '',
				],
			],
			'editor_script'   => 'wpps-cf-block-editor',
			'render_callback' => 'wpps_cf_render_gutenberg_block',
			'supports'        => [
				'html' => false,
			],
		]
	);
}

function wpps_cf_enqueue_block_editor_assets(): void {
	wpps_cf_register_block_editor_script();
	if ( ! wp_script_is( 'wpps-cf-block-editor', 'registered' ) ) {
		return;
	}

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

	wp_localize_script(
		'wpps-cf-block-editor',
		'wppsCfBlock',
		[
			'fields' => $field_options,
		]
	);
}

/**
 * @param array<string, mixed> $attributes
 */
function wpps_cf_render_gutenberg_block( array $attributes ): string {
	$group_key  = sanitize_key( (string) ( $attributes['groupKey'] ?? '' ) );
	$field_name = sanitize_key( (string) ( $attributes['fieldName'] ?? '' ) );

	if ( $group_key === '' || $field_name === '' ) {
		$selection = sanitize_text_field( (string) ( $attributes['selection'] ?? '' ) );
		if ( $selection !== '' && strpos( $selection, ':' ) !== false ) {
			$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'  => sanitize_key( (string) ( $attributes['format'] ?? 'display' ) ),
			'default' => (string) ( $attributes['defaultValue'] ?? '' ),
		]
	);
}
