<?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;
	}

	$module_file = dirname( __DIR__ ) . '/module.php';
	$script_url  = function_exists( 'wp_powersuite_module_asset_url' )
		? wp_powersuite_module_asset_url( $module_file, 'assets/cf-block-editor.js' )
		: plugins_url( 'assets/cf-block-editor.js', $module_file );
	wp_register_script(
		'wpps-cf-block-editor',
		$script_url,
		[ 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-server-side-render' ],
		(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'     => 3,
			'title'           => __( 'PowerSuite Custom Field', 'wppowersuite-lite' ),
			'description'     => __( 'Display a custom field value from the current post.', 'wppowersuite-lite' ),
			'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',
			'uses_context'    => [ 'postId' ],
			'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 —', 'wppowersuite-lite' ), '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 $content = '', ?\WP_Block $block = null ): string {
	unset( $content );

	$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 '';
	}

	$post_id = null;
	if ( $block instanceof \WP_Block && isset( $block->context['postId'] ) ) {
		$post_id = absint( (string) $block->context['postId'] );
		$post_id = $post_id > 0 ? $post_id : null;
	}

	return \CustomFields\FieldOutput::render(
		$group_key,
		$field_name,
		$post_id,
		[
			'format'  => sanitize_key( (string) ( $attributes['format'] ?? 'display' ) ),
			'default' => (string) ( $attributes['defaultValue'] ?? '' ),
		]
	);
}
