<?php
/**
 * Gutenberg Block integration for Product Display
 *
 * @package Product_Display
 */

// Exit if accessed directly
if ( ! defined('ABSPATH') ) {
	exit;
}

/**
 * Class PRODDISP_Gutenberg
 *
 * This class handles the Gutenberg block integration for Product Display plugin.
 */
class PRODDISP_Gutenberg {
	/**
	 * The single instance of the class
	 */
	protected static $_instance = null;

	/**
	 * Main Instance
	 */
	public static function get_instance() {
		if ( is_null(self::$_instance) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action('init', array( $this, 'register_blocks' ));
		add_action('enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ));

		// Register block category (support both old and new hooks)
		if ( function_exists('get_default_block_categories') ) {
			add_filter('block_categories_all', array( $this, 'register_block_category' ), 10, 2);
		} else {
			add_filter('block_categories', array( $this, 'register_block_category_legacy' ), 10, 2);
		}
	}

	/**
	 * Register Gutenberg blocks
	 */
	public function register_blocks() {
		// Check if Gutenberg is available
		if ( ! function_exists('register_block_type') ) {
			return;
		}

		// Register Product Display Showcase block
		register_block_type('product-display/showcase', array(
			'editor_script' => 'proddisp-gutenberg-blocks',
			'editor_style' => 'proddisp-gutenberg-blocks',
			'style' => 'wcps-styles',
			'render_callback' => array( $this, 'render_showcase_block' ),
			'attributes' => array(
				'showcaseId' => array(
					'type' => 'string',
					'default' => '',
				),
				'overrideLimit' => array(
					'type' => 'boolean',
					'default' => false,
				),
				'limit' => array(
					'type' => 'number',
					'default' => 4,
				),
				'overrideColumns' => array(
					'type' => 'boolean',
					'default' => false,
				),
				'columns' => array(
					'type' => 'number',
					'default' => 4,
				),
				'overrideOrderBy' => array(
					'type' => 'boolean',
					'default' => false,
				),
				'orderBy' => array(
					'type' => 'string',
					'default' => 'date',
				),
				'order' => array(
					'type' => 'string',
					'default' => 'DESC',
				),
				'overrideIcons' => array(
					'type' => 'boolean',
					'default' => false,
				),
				'addtocartIcon' => array(
					'type' => 'string',
					'default' => 'fas fa-shopping-cart',
				),
				'wishlistIcon' => array(
					'type' => 'string',
					'default' => 'fas fa-heart',
				),
				'compareIcon' => array(
					'type' => 'string',
					'default' => 'fas fa-balance-scale',
				),
				'quickviewIcon' => array(
					'type' => 'string',
					'default' => 'fas fa-eye',
				),
				'customCssClass' => array(
					'type' => 'string',
					'default' => '',
				),
				'alignment' => array(
					'type' => 'string',
					'default' => 'none',
				),
			),
		));
	}

	/**
	 * Enqueue block editor assets
	 */
	public function enqueue_block_editor_assets() {
		// Enqueue block editor script
		wp_enqueue_script(
			'proddisp-gutenberg-blocks',
			PRODDISP_PLUGIN_URL . 'assets/src/js/wcps-gutenberg-blocks.js',
			array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-block-editor', 'wp-components' ),
			PRODDISP_VERSION,
			true
		);

		// Enqueue block editor styles (use built version if available, fallback to source)
		$css_file = file_exists(PRODDISP_PLUGIN_PATH . 'assets/build/css/wcps-gutenberg-blocks.min.css')
			? 'assets/build/css/wcps-gutenberg-blocks.min.css'
			: 'assets/src/css/wcps-gutenberg-blocks.css';

		wp_enqueue_style(
			'proddisp-gutenberg-blocks',
			PRODDISP_PLUGIN_URL . $css_file,
			array( 'wp-edit-blocks' ),
			PRODDISP_VERSION
		);

		// Enqueue FontAwesome for icons
		wp_enqueue_style(
			'fontawesome',
			'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css',
			array(),
			'6.0.0'
		);

		// Localize script with data
		wp_localize_script('proddisp-gutenberg-blocks', 'proddispGutenberg', array(
			'showcases' => $this->get_showcases_for_editor(),
			'categories' => $this->get_product_categories(),
			'adminUrl' => admin_url('admin.php?page=product-display'),
			// 'upgradeUrl' => admin_url('admin.php?page=product-display-pricing'),
			'upgradeUrl' => 'https://wpazleen.com/product-display/',
			'isProActive' => PRODDISP_Loader::is_pro_active(),
			'nonce' => wp_create_nonce('proddisp_gutenberg_nonce'),
		));
	}

	/**
	 * Render showcase block
	 */
	public function render_showcase_block( $attributes ) {
		// Extract attributes
		$showcase_id = isset($attributes['showcaseId']) ? $attributes['showcaseId'] : '';

		if ( empty($showcase_id) ) {
			return '<div class="proddisp-block-placeholder">' . __('Please select a showcase in the block settings.', 'product-display') . '</div>';
		}

		// Build shortcode attributes
		$shortcode_atts = array( 'id' => $showcase_id );

		// Add override settings
		if ( ! empty($attributes['overrideLimit']) && ! empty($attributes['limit']) ) {
			$shortcode_atts['limit'] = $attributes['limit'];
		}

		if ( ! empty($attributes['overrideColumns']) && ! empty($attributes['columns']) ) {
			$shortcode_atts['columns'] = $attributes['columns'];
		}

		if ( ! empty($attributes['overrideOrderBy']) ) {
			if ( ! empty($attributes['orderBy']) ) {
				$shortcode_atts['orderby'] = $attributes['orderBy'];
			}
			if ( ! empty($attributes['order']) ) {
				$shortcode_atts['order'] = $attributes['order'];
			}
		}

		// Add icon overrides
		if ( ! empty($attributes['overrideIcons']) ) {
			if ( ! empty($attributes['addtocartIcon']) ) {
				$shortcode_atts['addtocart_icon'] = $attributes['addtocartIcon'];
			}
			if ( ! empty($attributes['wishlistIcon']) ) {
				$shortcode_atts['wishlist_icon'] = $attributes['wishlistIcon'];
			}
			if ( ! empty($attributes['compareIcon']) ) {
				$shortcode_atts['compare_icon'] = $attributes['compareIcon'];
			}
			if ( ! empty($attributes['quickviewIcon']) ) {
				$shortcode_atts['quickview_icon'] = $attributes['quickviewIcon'];
			}
		}

		// Build shortcode string
		$shortcode_string = '[product_display';
		foreach ( $shortcode_atts as $key => $value ) {
			// Ensure value is not null to avoid PHP 8.1+ deprecation warnings
			$safe_value = $value !== null ? $value : '';
			$shortcode_string .= ' ' . $key . '="' . esc_attr($safe_value) . '"';
		}
		$shortcode_string .= ']';

		// Wrap with custom CSS class if provided
		$css_class = ! empty($attributes['customCssClass']) && is_string($attributes['customCssClass']) ? sanitize_html_class($attributes['customCssClass']) : '';
		$alignment = ! empty($attributes['alignment']) && $attributes['alignment'] !== 'none' ? 'align' . $attributes['alignment'] : '';

		$wrapper_classes = array( 'proddisp-gutenberg-block' );
		if ( $css_class ) {
			$wrapper_classes[] = $css_class;
		}
		if ( $alignment ) {
			$wrapper_classes[] = $alignment;
		}

		$output = '<div class="' . esc_attr(implode(' ', $wrapper_classes)) . '">';
		$output .= do_shortcode($shortcode_string);
		$output .= '</div>';

		return $output;
	}



	/**
	 * Get showcases for editor
	 */
	private function get_showcases_for_editor() {
		$showcases = get_option('proddisp_saved_showcases', array());
		$formatted_showcases = array();

		if ( ! empty($showcases) ) {
			foreach ( $showcases as $id => $showcase ) {
				$name = isset($showcase['name']) && ! empty($showcase['name']) ? $showcase['name'] : 'Showcase #' . $id;
				$layout = isset($showcase['layout']) && ! empty($showcase['layout']) ? ucfirst($showcase['layout']) : 'Grid';
				$mode = isset($showcase['proddisp_layout_mode']) && ! empty($showcase['proddisp_layout_mode']) ? ' - ' . ucfirst(str_replace('-', ' ', $showcase['proddisp_layout_mode'])) : '';

				$formatted_showcases[] = array(
					'value' => $id,
					'label' => $name . ' (' . $layout . $mode . ')',
					'name' => $name,
					'layout' => $layout,
					'mode' => $mode,
					'columns' => isset($showcase['columns']) ? $showcase['columns'] : '4',
					'limit' => isset($showcase['limit']) ? $showcase['limit'] : '4',
				);
			}
		}

		return $formatted_showcases;
	}

	/**
	 * Get product categories
	 */
	private function get_product_categories() {
		$categories = array();

		if ( class_exists('WooCommerce') ) {
			$terms = get_terms(array(
				'taxonomy' => 'product_cat',
				'hide_empty' => false,
			));

			if ( ! is_wp_error($terms) ) {
				$categories[] = array(
					'value' => 0,
					'label' => __('All Categories', 'product-display'),
				);

				foreach ( $terms as $term ) {
					$categories[] = array(
						'value' => $term->term_id,
						'label' => $term->name . ' (' . $term->count . ')',
					);
				}
			}
		}

		return $categories;
	}

	/**
	 * Register custom block category (WordPress 5.8+)
	 */
	public function register_block_category( $categories, $post ) {
		return array_merge(
			array(
				array(
					'slug' => 'product-display',
					'title' => __('Product Display', 'product-display'),
					'icon' => 'products',
				),
			),
			$categories
		);
	}

	/**
	 * Register custom block category (WordPress 5.0-5.7)
	 */
	public function register_block_category_legacy( $categories, $post ) {
		return array_merge(
			$categories,
			array(
				array(
					'slug' => 'product-display',
					'title' => __('Product Display', 'product-display'),
					'icon' => 'products',
				),
			)
		);
	}
}
