<?php
class ALPHA_Block_Inline_Style {
	public function __construct() {
		add_action( 'init', array( $this, 'alpha_register_post_meta' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_columns_styles' ) );
		add_action( 'save_post', array( $this, 'on_save_post' ), 99, 1 );
		add_action( 'delete_post', array( $this, 'on_delete_post' ), 99, 1 );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_google_fonts' ) );
	}

	function enqueue_google_fonts() {
		$prev_used_fonts = get_option( 'alpha_block_used_fonts', array() );
		// merge The array one step
		$all_used_fonts = array();
		foreach ( $prev_used_fonts as $post_fonts ) {
			$all_used_fonts = array_merge( $all_used_fonts, $post_fonts );
		}

		$grouped_fonts = array();
		foreach ( $all_used_fonts as $font ) {
			if ( ! isset( $font['fontFamily'] ) || ! isset( $font['fontWeight'] ) ) {
				continue;
			}
			$family = $font['fontFamily'];
			$weight = $font['fontWeight'];
			if ( ! isset( $grouped_fonts[ $family ] ) ) {
				$grouped_fonts[ $family ] = array();
			}
			if ( ! in_array( $weight, $grouped_fonts[ $family ], true ) ) {
				$grouped_fonts[ $family ][] = $weight;
			}
		}

		if ( ! empty( $grouped_fonts ) ) {
			$font_families_parts = array();
			foreach ( $grouped_fonts as $family => $weights ) {
				sort( $weights );
				$font_families_parts[] = str_replace( ' ', '+', $family ) . ':' . implode( ',', $weights );
			}
			$fonts_url = 'https://fonts.googleapis.com/css?family=' . implode( '|', $font_families_parts ) . '&display=swap';
			wp_enqueue_style( 'alpha-google-fonts', $fonts_url, array(), null );
		}
	}

	function on_save_post( $post_id ) {
		if ( wp_is_post_revision( $post_id ) ) {
			return;
		}

		$post = get_post( $post_id );
		if ( ! has_blocks( $post->post_content ) ) {
			return;
		}

		$blocks      = parse_blocks( $post->post_content );
		$css         = '';
		$compiledCss = array();
		$usedFont    = array();
		$block_names = array();

		$compiledCss = $this->get_all_compiledCss( $blocks );

		$usedFont = $this->get_all_fonts( $blocks );

		if ( $usedFont ) {
			$prev_used_fonts             = get_option( 'alpha_block_used_fonts', array() );
			$prev_used_fonts[ $post_id ] = $usedFont;
			update_option( 'alpha_block_used_fonts', $prev_used_fonts );
			// wp_send_json( $prev_used_fonts );
		}

		update_post_meta( $post_id, 'alpha_block_css', $compiledCss );
	}

	function get_all_compiledCss( $blocks ) {
			$compiledCss = array();

		foreach ( $blocks as $block ) {
			if ( isset( $block['blockName'] ) && strpos( $block['blockName'], 'alpha-blocks' ) !== false ) {
				if ( ! empty( $block['attrs']['compiledCss'] ) ) {
					$compiledCss[] = $block['attrs']['compiledCss'];
				}
				if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
					$inner_compiledCss = $this->get_all_compiledCss( $block['innerBlocks'] );
					$compiledCss       = array_merge( $compiledCss, $inner_compiledCss );
				}
			}
		}

		return $compiledCss;
	}

	function get_all_fonts( $blocks ) {
		$usedFonts = array();

		foreach ( $blocks as $block ) {
			// $usedFonts['blockName'][] = $block['blockName'];
			// $usedFonts['blockName'][] = $block['attrs'];
			if ( isset( $block['blockName'] ) && strpos( $block['blockName'], 'alpha-blocks' ) !== false ) {
				if ( ! empty( $block['attrs']['typography'] ) ) {
					$_fonts               = array();
					$_fonts['fontFamily'] = $block['attrs']['typography']['fontFamily'];
					$_fonts['fontWeight'] = $block['attrs']['typography']['fontWeight'];
					$usedFonts[]          = $_fonts;
				}
				if ( ! empty( $block['attrs']['subHeadingTypography'] ) ) {
					$_fonts               = array();
					$_fonts['fontFamily'] = $block['attrs']['subHeadingTypography']['fontFamily'];
					$_fonts['fontWeight'] = $block['attrs']['subHeadingTypography']['fontWeight'];
					$usedFonts[]          = $_fonts;
				}
				if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
					$inner_fonts = $this->get_all_fonts( $block['innerBlocks'] );
					$usedFonts   = array_merge( $usedFonts, $inner_fonts );
				}
			}
		}
		// wp_send_json( array( $usedFonts ) );

		return $usedFonts;
	}

	function on_delete_post( $post_id ) {
		$prev_used_fonts = get_option( 'alpha_used_fonts', array() );
		if ( isset( $prev_used_fonts[ $post_id ] ) ) {
			unset( $prev_used_fonts[ $post_id ] );
			update_option( 'alpha_block_used_fonts', $prev_used_fonts );
		}
	}

	function alpha_register_post_meta() {
		register_post_meta(
			'',
			'alpha_block_css',
			array(
				'show_in_rest'  => array(
					'schema' => array(
						'type'                 => 'object',
						'additionalProperties' => array(
							'type' => 'string', // each value is a CSS string
						),
					),
				),
				'single'        => true,
				'type'          => 'object',
				'auth_callback' => function () {
					return current_user_can( 'edit_posts' );
				},
			)
		);
	}


	public function enqueue_columns_styles() {
		if ( is_singular() ) {

			wp_enqueue_style( 'alpha-block-all-inline-css', plugins_url( 'assets/alpha-block-all-inline-css.css', ALPHA_PLUGIN_FILE ) );

			$post_id   = get_the_ID();
			$block_css = get_post_meta( $post_id, 'alpha_block_css', true );
			$css       = '';

			if ( is_array( $block_css ) ) {
				foreach ( $block_css as $block_style ) {
					$css .= $block_style;
				}
			}

				// echo '<pre>';
				// print_r( $block_css );
				// echo '</pre>';
				// exit;
			if ( ! empty( $css ) ) {

				wp_add_inline_style( 'alpha-block-all-inline-css', $css );
			}
		}
	}
}
