<?php
/**
 * Options Page Builder — Gutenberg block integration.
 *
 * @package OptionsPageBuilder
 */

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

add_action( 'init', 'wpps_opb_register_gutenberg_block', 20 );
add_action( 'enqueue_block_editor_assets', 'wpps_opb_enqueue_block_editor_assets' );

function wpps_opb_register_block_editor_script(): void {
	$path = dirname( __DIR__ ) . '/assets/opb-block-editor.js';
	if ( ! is_readable( $path ) || wp_script_is( 'wpps-opb-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-opb-block-editor',
		plugins_url( 'modules/options-page-builder/assets/opb-block-editor.js', $plugin_file ),
		[ 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ],
		(string) filemtime( $path ),
		true
	);
}

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

	wpps_opb_register_block_editor_script();

	register_block_type(
		'wp-powersuite/opb-field',
		[
			'api_version'     => 2,
			'title'           => __( 'PowerSuite Option', 'wp-powersuite' ),
			'description'     => __( 'Display a value from an Options Page Builder field.', 'wp-powersuite' ),
			'category'        => 'widgets',
			'icon'            => 'admin-settings',
			'attributes'      => [
				'pageSlug' => [
					'type'    => 'string',
					'default' => '',
				],
				'fieldId' => [
					'type'    => 'string',
					'default' => '',
				],
				'format' => [
					'type'    => 'string',
					'default' => 'display',
				],
				'defaultValue' => [
					'type'    => 'string',
					'default' => '',
				],
			],
			'editor_script'   => 'wpps-opb-block-editor',
			'render_callback' => 'wpps_opb_render_gutenberg_block',
			'supports'        => [
				'html' => false,
			],
		]
	);
}

function wpps_opb_enqueue_block_editor_assets(): void {
	wpps_opb_register_block_editor_script();
	if ( ! wp_script_is( 'wpps-opb-block-editor', 'registered' ) ) {
		return;
	}

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

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

/**
 * @param array<string, mixed> $attributes
 */
function wpps_opb_render_gutenberg_block( array $attributes ): string {
	$page_slug = sanitize_key( (string) ( $attributes['pageSlug'] ?? '' ) );
	$field_id  = sanitize_key( (string) ( $attributes['fieldId'] ?? '' ) );

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