<?php
/**
 * FoodOrd Products Block Class
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_Products_Block
 */
class Foodord_Products_Block {

	/**
	 * Initialize the block
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'register_block' ) );
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
	}

	/**
	 * Register the block
	 */
	public function register_block() {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}

		register_block_type(
			'foodord/products',
			array(
				'attributes'      => array(
					'limit'   => array(
						'type'    => 'number',
						'default' => -1,
					),
					'columns' => array(
						'type'    => 'number',
						'default' => 4,
					),
					'orderby' => array(
						'type'    => 'string',
						'default' => 'date',
					),
					'order'   => array(
						'type'    => 'string',
						'default' => 'DESC',
					),
				),
				'render_callback' => array( $this, 'render_block' ),
				'editor_script'   => 'foodord-products-block-editor',
				'editor_style'    => 'foodord-products-block-editor',
				'style'           => 'foodord-products-block',
			)
		);
	}

	/**
	 * Enqueue block assets for editor only
	 */
	public function enqueue_block_editor_assets() {
		// Check if we're in the block editor.
		if ( is_admin() && function_exists( 'get_current_screen' ) ) {
			$screen = get_current_screen();
			if ( $screen && $screen->is_block_editor() ) {
				wp_enqueue_script(
					'foodord-products-block-editor',
					FOODORD_URL . 'admin/js/blocks/foodord-products-block.js',
					array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ),
					FOODORD_VERSION,
					true
				);

				wp_enqueue_style(
					'foodord-products-block-editor',
					FOODORD_URL . 'admin/css/blocks/foodord-products-block-editor.css',
					array( 'wp-edit-blocks' ),
					FOODORD_VERSION
				);

				// Frontend styles for editor preview.
				wp_enqueue_style(
					'foodord-products-block',
					FOODORD_URL . 'public/css/shortcode-products.css',
					array(),
					FOODORD_VERSION
				);
			}
		}
	}

	/**
	 * Enqueue frontend styles
	 */
	private function enqueue_frontend_styles() {
		wp_enqueue_style(
			'foodord-products-block',
			FOODORD_URL . 'public/css/shortcode-products.css',
			array(),
			FOODORD_VERSION
		);
	}

	/**
	 * Render the block
	 *
	 * @param array $attributes Block attributes.
	 * @return string HTML output
	 */
	public function render_block( $attributes ) {
		// Enqueue frontend styles when block is rendered.
		$this->enqueue_frontend_styles();

		// Mark that products block is present.
		$GLOBALS['foodord_has_products_block'] = true;
		// Use the shared renderer to maintain consistency with shortcode.
		return Foodord_Products_Renderer::render( $attributes );
	}
}
