<?php
namespace TotalThemeCore\Vcex;

defined( 'ABSPATH' ) || exit;

abstract class Block {

	/**
	 * Block namespace.
	 */
	protected $namespace = 'vcex';

	/**
	 * Block name.
	 */
	protected $block_name = '';

	/**
	 * Path to block json file.
	 */
	protected $json_path = '';

	/**
	 * Block args.
	 */
	protected $args = array();

	/**
	 * Render Callback function.
	 */
	protected $render_callback = '';

	/**
	 * Editor styles.
	 */
	protected $editor_styles = array();

	/**
	 * Editor scripts
	 */
	protected $editor_scripts = array();

	/**
	 * Editor script dependencies.
	 */
	protected $editor_dependency = array(
		'wp-blocks',
		'wp-i18n',
		'wp-element',
		'wp-components',
		'wp-editor',
	);

	/**
	 * Setup the block.
	 */
	abstract public function setup();

	/**
	 * Registers the block to WordPress.
	 */
	public function register_block() {
		$this->setup();

		if ( ! $this->block_name ) {
			return;
		}

		register_block_type( $this->json_path, $this->get_args() );

		add_action( 'enqueue_block_editor_assets', array( $this, 'register_block_scripts' ) );
	}

	/**
	 * Return register_block_type args.
	 */
	public function get_args() {
		if ( empty( $this->args['render_callback'] ) && method_exists( $this, 'render_callback' ) ) {
			$this->args['render_callback'] = array( $this, 'render_callback' );
		}

		return $this->args;
	}

	/**
	 * Register block scripts.
	 */
	public function register_block_scripts() {
		wp_register_script(
			$this->namespace . '-' . $this->block_name . '-editor',
			TTC_PLUGIN_DIR_URL . 'inc/' . $this->namespace . '/blocks/' . $this->block_name . '/index.min.js',
			$this->editor_dependency,
			TTC_VERSION
		);

		if ( $this->editor_scripts ) {
			foreach( $this->editor_scripts as $script ) {
				wp_enqueue_script(
					$script['handle'],
					$script['src'],
					$script['deps'] ?? array(),
					TTC_VERSION
				);
			}
		}

		if ( $this->editor_styles ) {
			foreach( $this->editor_styles as $style ) {
				wp_enqueue_style(
					$style['handle'],
					$style['src'],
					$style['deps'] ?? array(),
					TTC_VERSION
				);
			}
		}
	}

	/**
	 * Wrapper for displaying a block shortcode.
	 */
	public function do_shortcode( $tag, $atts = array(), $content = null ) {
		global $shortcode_tags;

		if ( ! isset( $shortcode_tags[$tag] ) || ! is_callable( $shortcode_tags[$tag] ) ) {
			return false;
		}

		$shortcode = call_user_func( $shortcode_tags[$tag], $atts, $content, $tag );

		if ( $shortcode ) {
			$class = 'wp-block-' . sanitize_html_class( $this->namespace . '-' . $this->block_name );

			if ( ! empty( $atts['className'] ) ) {
				$class .= ' ' . esc_attr( trim( $atts['className'] ) );
			}

			return '<div class="' . esc_attr( $class ) . '">' . $shortcode . '</div>';
		}
	}

	/**
	 * Check if we are currently in the block editor.
	 */
	public function is_block_editor() {
		if ( is_callable( array( 'WP_Screen', 'is_block_editor' ) ) ) {
			return WP_Screen::is_block_editor();
		}
		return false;
	}

}