<?php
/**
 * WPFAQBlock Gutenberg Block Registration
 *
 * Registers the Gutenberg block from the build folder and maps its
 * render callback to our shortcode rendering logic. Also enqueues
 * the editor JS that injects Inspector Controls (sidebar options).
 *
 * @package WPFAQBlock
 * @since   2.0.0
 */

// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class WPFAQBlock_Block
 */
class WPFAQBlock_Block {

	/**
	 * Register the Gutenberg block and editor scripts.
	 *
	 * Hooked into: init (via loader)
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function register(): void {
		// Only register if the build folder exists (e.g., block.json is present)
		if ( ! file_exists( WPFAQBLOCK_DIR . 'build/block.json' ) ) {
			return;
		}

		register_block_type(
			WPFAQBLOCK_DIR . 'build',
			array(
				'render_callback' => array( $this, 'render_callback' ),
			)
		);

		// Enqueue the editor JS that injects Inspector Controls (sidebar options).
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) );
	}

	/**
	 * Enqueue the Gutenberg editor JS (Inspector Controls sidebar).
	 *
	 * This is the script that adds the FAQ Settings panel in the block sidebar.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function enqueue_editor_assets(): void {
		wp_enqueue_media();

		wp_enqueue_script(
			'wpfaqblock-editor-script',
			WPFAQBLOCK_URL . 'assets/js/wpfaqblock-editor.js',
			array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-hooks', 'wp-api-fetch' ),
			filemtime( WPFAQBLOCK_DIR . 'assets/js/wpfaqblock-editor.js' ),
			true
		);

		// Localize plugin URL so the editor JS can load theme preview images.
		wp_localize_script(
			'wpfaqblock-editor-script',
			'wpfaqblockEditor',
			array(
				'pluginUrl'    => WPFAQBLOCK_URL,
				'restPath'     => '/wp/v2/' . WPFAQBlock_CPT::SLUG,
				'termRestPath' => '/wp/v2/' . WPFAQBlock_Taxonomy::SLUG,
			)
		);

		// Enqueue the FAQ stylesheet in the editor too, for preview.
		wp_enqueue_style(
			'wpfaqblock-editor-style',
			WPFAQBLOCK_URL . 'assets/css/wpfaqblock-stylesheet.css',
			array(),
			WPFAQBLOCK_VERSION
		);
	}

	/**
	 * Render callback for the Gutenberg block.
	 *
	 * Maps block attributes to our shortcode rendering logic.
	 *
	 * @since 2.0.0
	 *
	 * @param array  $attributes Block attributes.
	 * @param string $content    Block content.
	 * @return string HTML output.
	 */
	public function render_callback( $attributes, $content ): string {
		// Handle className from Gutenberg.
		if ( isset( $attributes['className'] ) && ! empty( $attributes['className'] ) ) {
			$attributes['class'] = $attributes['className'];
		}

		$manual_ids = '';
		if (
			isset( $attributes['faqSelectionMode'] )
			&& 'manual' === $attributes['faqSelectionMode']
			&& ! empty( $attributes['faqManualIds'] )
			&& is_array( $attributes['faqManualIds'] )
		) {
			$manual_ids = implode( ',', array_map( 'absint', $attributes['faqManualIds'] ) );
		}

		$category = '';
		if (
			isset( $attributes['faqSelectionMode'] )
			&& 'category' === $attributes['faqSelectionMode']
			&& ! empty( $attributes['faqCategory'] )
		) {
			$category = sanitize_title( $attributes['faqCategory'] );
		}

		// Map all block attributes to our shortcode attributes (same as old plugin).
		$shortcode_atts = array(
			'category'         => $category,
			'title'            => isset( $attributes['faqtitle'] )      ? $attributes['faqtitle']      : '',
			'placeholder'      => isset( $attributes['faqplaceholder'] ) ? $attributes['faqplaceholder'] : '',
			'search'           => isset( $attributes['faqsearch'] )      ? $attributes['faqsearch']      : '',
			'order'            => isset( $attributes['faqorder'] )       ? $attributes['faqorder']       : '',
			'orderby'          => isset( $attributes['faqorderby'] )     ? $attributes['faqorderby']     : '',
			'open'             => isset( $attributes['faqdisplayall'] )  ? $attributes['faqdisplayall']  : '',
			'open_first'       => isset( $attributes['faqOpenFirst'] )   ? $attributes['faqOpenFirst']   : false,
			'accordion'        => isset( $attributes['faqaccordion'] )   ? $attributes['faqaccordion']   : '',
			'class'            => isset( $attributes['class'] )          ? $attributes['class']          : '',
			// Pass the selected theme — shortcode now applies it as a CSS class on the
			// grouped wrapper, so groups + theme both work simultaneously.
			'faqtheme'         => isset( $attributes['faqtheme'] ) ? $attributes['faqtheme'] : 'wpfaqblock-theme-1',
			'faqicon'          => isset( $attributes['faqicon'] )        ? $attributes['faqicon']        : 'plus',
			'ids'              => $manual_ids,
			'closed_icon'      => isset( $attributes['faqClosedIconUrl'] ) ? esc_url_raw( $attributes['faqClosedIconUrl'] ) : '',
			'open_icon'        => isset( $attributes['faqOpenIconUrl'] )   ? esc_url_raw( $attributes['faqOpenIconUrl'] )   : '',
			'category_title'   => isset( $attributes['faqShowCategoryTitle'] ) && false === $attributes['faqShowCategoryTitle'] ? '0' : '1',
			'include_category' => '',
			'exclude_category' => '',
		);

		// Instantiate the shortcode class and render.
		$shortcode = new WPFAQBlock_Shortcode();

		// Ensure frontend assets are enqueued when block is rendered.
		$shortcode->enqueue_assets();

		return $shortcode->render( $shortcode_atts );
	}
}
