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

	$module_file = dirname( __DIR__ ) . '/module.php';
	$script_url  = function_exists( 'wp_powersuite_module_asset_url' )
		? wp_powersuite_module_asset_url( $module_file, 'assets/opb-block-editor.js' )
		: plugins_url( 'assets/opb-block-editor.js', $module_file );
	wp_register_script(
		'wpps-opb-block-editor',
		$script_url,
		[ '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', 'wppowersuite-lite' ),
			'description'     => __( 'Display a value from an Options Page Builder field.', 'wppowersuite-lite' ),
			'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 —', 'wppowersuite-lite' ), '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'] ?? '' ),
		]
	);
}
