<?php

namespace CommerceBird;

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

if ( ! class_exists( 'CMBIRD_AI_Product_Blocks_Block' ) ) {
	/**
	 * Dynamic WooCommerce block for AI product blocks.
	 */
	class CMBIRD_AI_Product_Blocks_Block {

		const OPTION_ENABLED = 'cmbird_ai_review_summary_enabled';

		/**
		 * Constructor.
		 */
		public function __construct() {
			add_action( 'init', array( $this, 'register_block' ) );
			add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) );
		}

		/**
		 * Enqueue block editor script.
		 *
		 * @return void
		 */
		public function enqueue_editor_assets(): void {
			wp_enqueue_script(
				'commercebird-ai-review-summary-editor',
				plugin_dir_url( __FILE__ ) . 'ai-review-summary/editor.js',
				array( 'wp-blocks', 'wp-element' ),
				'1.0.0',
				true
			);
		}

		/**
		 * Register dynamic block.
		 *
		 * @return void
		 */
		public function register_block(): void {
			if ( ! function_exists( 'register_block_type' ) ) {
				return;
			}

			register_block_type(
				plugin_dir_path( __FILE__ ) . 'ai-review-summary',
				array(
					'render_callback' => array( $this, 'render' ),
				)
			);
		}

		/**
		 * Render callback.
		 *
		 * @param array  $attributes Block attributes.
		 * @param string $content Block content.
		 * @param object $block Block instance.
		 * @return string
		 */
		public function render( $attributes, $content, $block ): string {
			if ( ! (bool) get_option( self::OPTION_ENABLED, false ) ) {
				return '';
			}

			$post_id = 0;
			if ( isset( $block->context['postId'] ) ) {
				$post_id = (int) $block->context['postId'];
			}
			if ( $post_id <= 0 ) {
				$post_id = get_the_ID();
			}
			if ( $post_id <= 0 ) {
				return '';
			}

			$summary = get_post_meta( $post_id, \CommerceBird\CMBIRD_AI_Product_Blocks_Generator::META_KEY, true );
			if ( empty( $summary ) ) {
				return '';
			}

			$html  = '<div class="cmbird-ai-review-summary wp-block">';
			$html .= '<h3>' . esc_html__( 'Review Summary', 'commercebird' ) . '</h3>';
			$html .= '<p>' . esc_html( $summary ) . '</p>';
			$html .= '</div>';

			return $html;
		}
	}
}

if ( ! class_exists( 'CMBIRD_AI_Review_Summary_Block' ) && class_exists( 'CMBIRD_AI_Product_Blocks_Block' ) ) {
	class_alias( __NAMESPACE__ . '\\CMBIRD_AI_Product_Blocks_Block', __NAMESPACE__ . '\\CMBIRD_AI_Review_Summary_Block' );
}
