<?php


class TU_Block {
	const NAME = 'ultimatum-block';

	public static function init() {
		if ( self::can_use_blocks() ) {
			TU_Block::hooks();
			TU_Block::register_block();
		}
	}

	public static function can_use_blocks() {
		return function_exists( 'register_block_type' );
	}

	public static function hooks() {
		global $wp_version;
		add_filter( version_compare( $wp_version, '5.7.9', '>' ) ? 'block_categories_all' : 'block_categories', array( __CLASS__, 'register_block_category' ), 10, 2 );

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
	}

	/**
	 * Register the block
	 * Dependencies & version are generated by wordpress webpack
	 */
	public static function register_block() {

		$asset_file = include TVE_Ult_Const::plugin_path() . 'blocks/build/index.asset.php';

		// Register our block script with WordPress
		wp_register_script( 'tu-block-editor', TVE_Ult_Const::plugin_url() . 'blocks/build/index.js', $asset_file['dependencies'], $asset_file['version'], false );

		register_block_type(
			'thrive/' . self::NAME,
			array(
				'render_callback' => 'TU_Block::render_block',
				'editor_script'   => 'tu-block-editor',
				'editor_style'    => 'tu-block-editor',
			)
		);
	}

	/**
	 * Render block shortcodes
	 *
	 * @param $attributes
	 *
	 * @return string
	 */
	public static function render_block( $attributes ) {

		if ( isset( $attributes['selectedCampaign'] ) && isset( $attributes['selectedDesign'] ) && ! is_admin() ) {

			$data = array(
				'id'     => $attributes['selectedCampaign'],
				'design' => $attributes['selectedDesign'],
			);

			return TU_Shortcodes::countdown( $data );
		}

		return '';
	}

	/**
	 * Enqueue block styles & data
	 *
	 * @param $hook
	 */
	public static function enqueue_scripts( $hook ) {
		if ( tve_should_load_blocks() ) {
			wp_localize_script( 'tu-block-editor', 'TVU_Data',
				array(
					'campaigns'     => tve_ult_get_campaign_with_shortcodes(),
					'dashboard_url' => admin_url( 'admin.php?page=tve_ult_dashboard' ),
					'block_preview' => TVE_Ult_Const::plugin_url( '/blocks/img/block-preview.png' ),
				)
			);
			tve_ult_enqueue_style( 'thrive-ult-block-style', TVE_Ult_Const::plugin_url( '/blocks/css/styles.css' ) );
		}
	}

	/**
	 * Register Thrive Block category if doesnt exists
	 *
	 * @param $categories
	 * @param $post
	 *
	 * @return array|mixed
	 */
	public static function register_block_category( $categories, $post ) {
		$category_slugs = wp_list_pluck( $categories, 'slug' );

		return in_array( 'thrive', $category_slugs, true ) ? $categories : array_merge(
			array(
				array(
					'slug'  => 'thrive',
					'title' => __( 'Thrive Library', 'thrive-ult'),
					'icon'  => 'wordpress',
				),
			),
			$categories
		);
	}
}
