<?php
/**
 * Integrate Nevo with the WordPress block editor.
 *
 * @package Nevo
 */

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

/**
 * Check what sidebar layout we're using.
 * @since 1.0
 *
 * @param bool $meta Check for post meta.
 * @return string The saved sidebar layout.
 */
function nevo_get_block_editor_sidebar_layout( $meta = true ) {
	$layout = Nevo()->get_setting( 'sidebar_layout' );

	if ( function_exists( 'get_current_screen' ) ) {
		$screen = get_current_screen();

		if ( is_object( $screen ) && 'post' === $screen->post_type ) {
			$layout = Nevo()->get_setting( 'post_single_sidebar_layout' );
		}
		elseif ( is_object( $screen ) && 'page' === $screen->post_type ) {
			$layout = Nevo()->get_setting( 'page_single_sidebar_layout' );
		}
		elseif ( is_object( $screen ) && 'nevo_block' === $screen->post_type ) {
			$layout = Nevo()->get_setting( 'sidebar_layout' );
		}
		elseif ( is_object( $screen ) ) {
			$layout = Nevo()->get_setting( $screen->post_type . '_single_sidebar_layout' );
		}
	}

	// Add in our default filter in case people have adjusted it.
	$layout = apply_filters( 'nevo_sidebar_layout', $layout );

	if ( $meta ) {
		$layout_meta = wp_parse_args( get_post_meta( get_the_ID(), '_nevo_page_settings', true ), array() );

		if ( isset( $layout_meta['sidebar_layout'] ) ) {
			$layout = $layout_meta['sidebar_layout'];
		}
	}

	return apply_filters( 'nevo_block_editor_sidebar_layout', $layout );
}

/**
 * Check whether we're disabling the content title or not.
 * We need this function as the post meta in nevo_show_title() only runs
 * on is_singular()
 *
 * @since 1.0
 */
function nevo_get_block_editor_show_content_title() {
	$title = nevo_show_title();

	$disable_title = wp_parse_args( get_post_meta( get_the_ID(), '_nevo_page_settings', true ), array() );

	if ( isset( $disable_title['disable_content_title'] ) ) {
		$title = false;
	}

	return apply_filters( 'nevo_block_editor_show_content_title', $title );
}

/**
 * Get the content width for this post.
 *
 * @since 1.0
 */
function nevo_get_block_editor_content_width() {
	$container_width = Nevo()->get_setting( 'container_width' );
	$container_width = wp_parse_args(
		$container_width,
		array(
			'unit' => '',
			'value' => '1200',
		)
	);

	$sidebar_width = Nevo()->get_setting( 'sidebar_width' );
	$sidebar_width = wp_parse_args(
		$sidebar_width,
		array(
			'unit' => '',
			'value' => '30',
		)
	);
	$narrow_width = Nevo()->get_setting( 'container_narrow_width' );
	$narrow_width = wp_parse_args(
		$narrow_width,
		array(
			'unit' => '',
			'value' => '840',
		)
	);
	$container_width = $container_width['value'];
	$right_sidebar_width = $sidebar_width['value'];
	$left_sidebar_width = $sidebar_width['value'];
	$content_narrow_width = $narrow_width['value'];

	$layout = nevo_get_block_editor_sidebar_layout();
	if ( !$layout ) {
		$layout = nevo_get_block_editor_sidebar_layout( false );
	}
	
	if ( 'content-narrow' === $layout ) {
		$content_width = $content_narrow_width;
	} elseif ( 'left-sidebar' === $layout ) {
		$content_width = $container_width * ( ( 100 - $left_sidebar_width ) / 100 );
	} elseif ( 'right-sidebar' === $layout ) {
		$content_width = $container_width * ( ( 100 - $right_sidebar_width ) / 100 );
	} elseif ( 'no-sidebar' === $layout ) {
		$content_width = $container_width;
	} else {
		$content_width = $container_width * ( ( 100 - ( $left_sidebar_width + $right_sidebar_width ) ) / 100 );
	}

	return apply_filters( 'nevo_block_editor_content_width', $content_width );
}

/**
 * Support Gutenberg Editor.
 *
 * @since 0.2.6
 */
class Nevo_Editor {
	private $action      = 'nevo_load_editor_style';
	private $editor_file = 'assets/css/admin/block-editor.css';
	public function __construct() {
		$current_wp_version = $GLOBALS['wp_version'];
		if ( version_compare( $current_wp_version, '5.8', '>=' ) ) {
			add_filter( 'block_editor_settings_all', array( $this, 'editor_settings' ) );
		} else {
			add_filter( 'block_editor_settings', array( $this, 'editor_settings' ) );
		}

		// Add ajax action to load css file.
		add_action( 'wp_ajax_' . $this->action, array( $this, 'css_file' ) );
		// Add more editor assets.
		add_action( 'enqueue_block_assets', array( $this, 'assets' ) );
		add_action( 'enqueue_block_editor_assets', array( $this, 'assets' ) );
	}

	/**
	 * Add more editor styles and scripts
	 *
	 * @todo Add Custom Fonts and styling settings.
	 *
	 * @return void
	 */
	function assets() {
		$show_editor_styles = apply_filters( 'nevo_show_block_editor_styles', true );
		
		wp_enqueue_style( 'nevo-editor-fonts', Nevo_Customizer_Auto_CSS::get_instance()->get_font_url() );
		wp_register_style( 'nevo-block-editor', false, array(), true, true );
		wp_add_inline_style( 'nevo-block-editor', $this->css() );
		wp_enqueue_style( 'nevo-block-editor' );
		$current_wp_version = $GLOBALS['wp_version'];
		if ( version_compare( $current_wp_version, '6.7', '>=' ) ) {
			wp_enqueue_script(
				'nevo-block-editor',
				trailingslashit( get_template_directory_uri() ) . 'assets/js/admin/block-editor.min.js',
				array( 'jquery', 'wp-data', 'wp-dom-ready', 'wp-element', 'wp-plugins', 'wp-polyfill' ),
				Nevo::$version,
				true
			);
		} else {
			wp_enqueue_script( 'nevo-block-editor', get_template_directory_uri() . '/assets/js/admin/block-editor-old.js', array( 'jquery' ), Nevo::$version, true );
		}
		
		$spacing_settings = '';
		$spacing_settings = wp_parse_args(
			$spacing_settings,
				array(
					'content_left' => '30',
					'content_right' => '30',
				)
		);
		$container_width = Nevo()->get_setting( 'container_width' );
		$container_width = wp_parse_args(
			$container_width,
			array(
				'unit' => '',
				'value' => '1200',
			)
		);
		$sidebar_width = Nevo()->get_setting( 'sidebar_width' );
		$sidebar_width = wp_parse_args(
			$sidebar_width,
			array(
				'unit' => '',
				'value' => '30',
			)
		);
		$narrow_width = Nevo()->get_setting( 'container_narrow_width' );
		$narrow_width = wp_parse_args(
			$narrow_width,
			array(
				'unit' => '',
				'value' => '840',
			)
		);
		wp_localize_script(
			'nevo-block-editor',
			'nevo_block_editor',
			array(
				'global_sidebar_layout' => nevo_get_block_editor_sidebar_layout( false ),
				'container_width' => $container_width['value'],
				'narrow_width' => $narrow_width['value'],
				'right_sidebar_width' => apply_filters( 'nevo_right_sidebar_width', $sidebar_width['value'] ),
				'left_sidebar_width' => apply_filters( 'nevo_left_sidebar_width', $sidebar_width['value'] ),
				'content_padding_right' => absint( $spacing_settings['content_right'] ) . 'px',
				'content_padding_left' => absint( $spacing_settings['content_left'] ) . 'px',
			)
		);
	}

	/**
	 * Add styling settings to editor.
	 *
	 * @return string CSS code.
	 */
	public function css() {
		$container_width = Nevo()->get_setting( 'container_width' );
		$container_width = wp_parse_args(
			$container_width,
			array(
				'unit' => '',
				'value' => '1200',
			)
		);
		$fields = array();
		$keys   = array(
			'container_width',
			'content_styling',
			'global_typography_base_p',
			'global_typography_blockquote',
			'global_typography_heading_h1',
			'global_typography_heading_h2',
			'global_typography_heading_h3',
			'global_typography_heading_h4',
			'global_typography_heading_h5',
			'global_typography_heading_h6',
			'global_color_style',
			'global_typography_base_entry_title',
			'post_single_typography',
		);

		foreach ( $keys as $k ) {
			$f = Nevo()->customizer->get_field_setting( $k );
			if ( $f ) {
				$fields[ $k ] = $f;
			}
		}
		
		if ( $fields['global_typography_base_p'] ) {
			$fields['global_typography_base_p']['selector']   = 'body, body .editor-styles-wrapper p, .editor-styles-wrapper .block-library-rich-text__tinymce p';
		}
		if ( $fields['global_typography_blockquote'] ) {
			$fields['global_typography_blockquote']['selector']   = 'body blockquote.wp-block, body .wp-block-quote, body .editor-styles-wrapper .wp-block-quote p, .wp-block-pullquote blockquote, .wp-block-pullquote cite, .wp-block-pullquote p';
		}
		if ( $fields['global_typography_heading_h1'] ) {
			$fields['global_typography_heading_h1']['selector'] = 'body .editor-styles-wrapper h1.wp-block:not(.wp-block-post-title), .editor-styles-wrapper .block-library-rich-text__tinymce h1';
		}
		if ( $fields['global_typography_heading_h2'] ) {
			$fields['global_typography_heading_h2']['selector'] = 'body .editor-styles-wrapper h2, .editor-styles-wrapper .block-library-rich-text__tinymce h2';
		}
		if ( $fields['global_typography_heading_h3'] ) {
			$fields['global_typography_heading_h3']['selector'] = 'body .editor-styles-wrapper h3, .editor-styles-wrapper .block-library-rich-text__tinymce h3';
		}
		if ( $fields['global_typography_heading_h4'] ) {
			$fields['global_typography_heading_h4']['selector'] = 'body .editor-styles-wrapper h4, .editor-styles-wrapper .block-library-rich-text__tinymce h4';
		}
		if ( $fields['global_typography_heading_h5'] ) {
			$fields['global_typography_heading_h5']['selector'] = 'body .editor-styles-wrapper h5, .editor-styles-wrapper .block-library-rich-text__tinymce h5';
		}
		if ( $fields['global_typography_heading_h6'] ) {
			$fields['global_typography_heading_h6']['selector'] = 'body .editor-styles-wrapper h6, .editor-styles-wrapper .block-library-rich-text__tinymce h6';
		}
		if ( $fields['global_typography_base_entry_title'] ) {
			$fields['global_typography_base_entry_title']['selector'] = 'body .editor-styles-wrapper h1.editor-post-title, body .editor-styles-wrapper h1.wp-block-post-title';
		}
		if ( $fields['post_single_typography'] ) {
			$fields['post_single_typography']['selector'] = 'body .editor-styles-wrapper h1.editor-post-title, body .editor-styles-wrapper h1.wp-block-post-title';
		}
		
		$content_width = nevo_get_block_editor_content_width();
		$underline_links = Nevo()->get_setting( 'content_link_text_decoration' );
		$content_container = wp_parse_args( get_post_meta( get_the_ID(), '_nevo_page_settings', true ), array() );
		
		if ( $fields['content_styling'] ) {
			$fields['site_content_styling']['selector'] = array(
				'normal' => '.edit-post-visual-editor.editor-styles-wrapper',
			);
		}

		if ( isset( $fields['content_styling'] ) && $fields['content_styling'] ) {
			$fields['content_styling']['selector'] = array(
				'normal' => 'body .edit-post-visual-editor .editor-styles-wrapper',
			);
		}

		$c   = new Nevo_Customizer_Auto_CSS();
		$css = $c->render_css( $fields );
		
		$css .= 'body {
			--nvt-white:#ffffff;
			--nvt-dark:#212529;
			--nvt-contrast:#f7f8f9;
			--nvt-wide-width-size: '. $content_width .'px;
			--nvt-content-width-size: calc( ' . $content_width .'px' . ' - 60px );
		}
		.wp-block a{
			text-decoration:'. $underline_links .';
		}
		
		.body, p {
			color: var(--nvt-base);
		}
		.editor-styles-wrapper .editor-post-title__input {
			color: var(--nvt-title);
		}
		body .editor-styles-wrapper h1.wp-block, .editor-styles-wrapper .block-library-rich-text__tinymce h1, body .editor-styles-wrapper h2.wp-block, .editor-styles-wrapper .block-library-rich-text__tinymce h2, body .editor-styles-wrapper h3.wp-block, .editor-styles-wrapper .block-library-rich-text__tinymce h3, body .editor-styles-wrapper h4.wp-block, .editor-styles-wrapper .block-library-rich-text__tinymce h4, body .editor-styles-wrapper h5.wp-block, .editor-styles-wrapper .block-library-rich-text__tinymce h5, body .editor-styles-wrapper h6.wp-block, .editor-styles-wrapper .block-library-rich-text__tinymce h6 {
			color: var(--nvt-heading);
		}
		a, a:visited {
			color: var(--nvt-link);
		}
		a:hover, a:focus {
			color: var(--nvt-link-hover);
		}
		
		.editor-styles-wrapper .block-editor-block-list__layout.is-root-container > :where(:not(.alignleft):not(.alignright):not(.alignfull)) {
			margin-left: auto !important;
    		margin-right: auto !important;
		}';
		$global_colors = Nevo()->get_setting( 'global_color_style' );
		foreach ( $global_colors['normal'] as $colorName => $colorValue ) {
			if ($colorName != 'link') {
				$css .= '.editor-styles-wrapper .has-' . $colorName . '-color{color:var(--nvt-' . str_replace('_', '-', $colorName) . ')!important;}';
				$css .= '.editor-styles-wrapper .has-' . $colorName . '-background-color{background-color:var(--nvt-' . str_replace('_', '-', $colorName) . ')!important;}';
			}
		}
		$css .= '.editor-styles-wrapper .has-trang-color{color:var(--nvt-white)!important;}';
		$css .= '.editor-styles-wrapper .has-trang-background-color{background-color:var(--nvt-white)!important;}';
		
		$css .= '.edit-post-layout__content .edit-post-layout__metaboxes { background: #FFF; }
		.edit-post-layout__metaboxes:not(:empty) { margin-top: 0px; }
		.editor-styles-wrapper textarea.editor-post-title__input { min-height: 0; }
		.editor-styles-wrapper textarea.editor-post-title__input:focus { background: none; }
		';
		
		if ( isset( $content_container['content_container'] ) && 'true' === $content_container['content_container'] ) {
			$css .= '.editor-styles-wrapper .wp-block{max-width: 100%;}';
		} elseif ( isset( $fields['container_width'] ) && $fields['container_width'] ) {
			$css .= '.editor-styles-wrapper .wp-block{max-width: calc( ' . $content_width . 'px' . ' - 60px );}';
		}
		if ( apply_filters( 'nevo_group_inner_container_style', true ) ) {
			$css .= '.wp-block-group__inner-container{max-width: ' . $container_width['value'] . 'px;}';
		}
		return $css;
	}

	/**
	 * Create a dymanic stylesheet url.
	 *
	 * @return string CSS URL
	 */
	public function editor_style_url() {
		return add_query_arg(
			array(
				'action' => $this->action,
				'nonce'  => wp_create_nonce( $this->action ),
			),
			admin_url( 'admin-ajax.php' )
		);
	}

	/**
	 * Add edditor settings.
	 *
	 * @see block_editor_scripts_and_styles
	 *
	 * @param array $editor_settings
	 * @return array
	 */
	public function editor_settings( $editor_settings ) {

		$editor_settings['styles'][] = array(
			'css' => $this->load_style(),
		);

		return $editor_settings;
	}

	/**
	 * Render dynamic CSS content.
	 *
	 * @return void
	 */
	public function css_file() {
		header( 'Content-type: text/css; charset: UTF-8' );
		echo $this->load_style();
	}

	/**
	 * Load CSS content.
	 *
	 * @return string CSS code.
	 */
	public function load_style() {
		$file_contents = '';
		/* $file          = get_template_directory() . '/' . $this->editor_file;
		if (file_exists($file)) {
			$file_contents = file_get_contents($file);
		} */
		/**
		 * Remove editor background
		 *
		 * @since 1.0
		 */
		$config_fields = Nevo()->customizer->get_config();
		$c             = new Nevo_Customizer_Auto_CSS();
		$css_code      = $c->render_css( $config_fields );

		$file_contents .= $css_code;
		return $file_contents;
	}

}

new Nevo_Editor();
