<?php
/**
 * Exit if accessed directly.
 *
 * @link       https://posimyth.com/
 * @since      1.0.2
 *
 * @package    Wdesignkit
 * @subpackage Wdesignkit/includes/gutenberg
 * */

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

if ( ! class_exists( 'Wdkit_Gutenberg_Files_Load' ) ) {

	/**
	 * This class used for only gutenberg widget load
	 *
	 * @since 1.0.2
	 */
	class Wdkit_Gutenberg_Files_Load {

		/**
		 * Instance
		 *
		 * @since 1.0.2
		 * @var The single instance of the class.
		 */
		private static $instance = null;

		/**
		 * Instance
		 *
		 * Ensures only one instance of the class is loaded or can be loaded.
		 *
		 * @since 1.0.2
		 * @return instance of the class.
		 */
		public static function instance() {
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Perform some compatibility checks to make sure basic requirements are meet.
		 *
		 * @since 1.0.2
		 */
		public function __construct() {
			add_action( 'enqueue_block_editor_assets', array( $this, 'editor_assets' ) );
			$this->wdkit_register_gutenberg_widgets();

			// add_filter( 'render_block', [ $this, 'render_block' ], 1000, 2 );
		}

		public function render_block( $block_content, $block ){

			$attrs = $block['attrs'] ?? [];

			if ( isset( $block['blockName'] ) && $block['blockName'] === 'tpgb/tp-heading' ) {

                // Determine title and tag
                $new_title = !empty( $attrs['exTitle'] ) ? $attrs['exTitle'] : '';
                $t_tag     = !empty( $attrs['tTag'] ) ? $attrs['tTag'] : 'h3';

				if ( !empty($new_title) ){
					$pattern = '/<' . preg_quote($t_tag, '/') . '([^>]*)>(.*?)<\/' . preg_quote($t_tag, '/') . '>/i';
					$replacement = '<' . $t_tag . '$1>' . wp_kses_post( $new_title ) . '</' . $t_tag . '>';
	
					$block_content = preg_replace( $pattern, $replacement, $block_content );
				}


            }

            if ( isset( $block['blockName'] ) && $block['blockName'] === 'tpgb/tp-pro-paragraph' ) {
        
                // Get attributes or set defaults
                $title   = !empty( $attrs['exTitle'] ) ? $attrs['exTitle'] : '';
                $content = !empty( $attrs['exproCnt'] ) ? $attrs['exproCnt'] : '';
        
                $title_tag = !empty( $attrs['titleTag'] ) ? $attrs['titleTag'] : 'h3';
                $desc_tag  = !empty( $attrs['descTag'] ) ? $attrs['descTag'] : 'p';
        
                // Replace inner HTML for pro-heading-inner using dynamic titleTag
                if ( preg_match( '/<' . preg_quote($title_tag, '/') . '[^>]*class="[^"]*pro-heading-inner[^"]*"[^>]*>.*?<\/' . preg_quote($title_tag, '/') . '>/is', $block_content ) && !empty($title) ) {
                    $block_content = preg_replace(
                        '/<' . preg_quote($title_tag, '/') . '([^>]*)class="([^"]*pro-heading-inner[^"]*)"([^>]*)>.*?<\/' . preg_quote($title_tag, '/') . '>/is',
                        '<' . $title_tag . '$1class="$2"$3>' . wp_kses_post( $title ) . '</' . $title_tag . '>',
                        $block_content
                    );
                }
        
                // Replace inner HTML for pro-paragraph-inner using dynamic descTag
                if ( preg_match( '/<div[^>]*class="[^"]*pro-paragraph-inner[^"]*"[^>]*>.*?<\/div>/is', $block_content ) && !empty($content)) {
                    $block_content = preg_replace(
                        '/<div([^>]*)class="([^"]*pro-paragraph-inner[^"]*)"([^>]*)>.*?<\/div>/is',
                        '<div$1class="$2"$3><' . $desc_tag . '>' . wp_kses_post( $content ) . '</' . $desc_tag . '></div>',
                        $block_content
                    );
                }
            }

            if ( isset( $block['blockName'] ) && $block['blockName'] === 'tpgb/tp-button-core' ) {
               
                $btn_text = !empty( $attrs['exbtxt'] ) ? $attrs['exbtxt'] : '';
        
                if ( preg_match( '/<span[^>]*class="[^"]*tpgb-btn-txt[^"]*"[^>]*>.*?<\/span>/is', $block_content ) && !empty($btn_text) ) {
                    $block_content = preg_replace(
                        '/<span([^>]*)class="([^"]*tpgb-btn-txt[^"]*)"([^>]*)>.*?<\/span>/is',
                        '<span$1class="$2"$3>' . wp_kses_post( $btn_text ) . '</span>',
                        $block_content
                    );
                }
            }

			return $block_content;
		}

		/**
		 * Load Gutenburg Builder js and css for controller.
		 *
		 * @since 1.0.2
		 */
		public function editor_assets() {

			$wp_localize_tpgb = array(
				'category'  => 'tpgb',
				'admin_url' => esc_url( admin_url() ),
				'home_url'  => home_url(),
				'ajax_url'  => esc_url( admin_url( 'admin-ajax.php' ) ),
			);

			global $pagenow;
			$scripts_dep = array( 'wp-blocks', 'wp-i18n', 'wp-plugins', 'wp-element', 'wp-components', 'wp-api-fetch', 'media-upload', 'media-editor' );
			if ( 'widgets.php' !== $pagenow && 'customize.php' !== $pagenow ) {
				$scripts_dep = array_merge( $scripts_dep, array( 'wp-editor', 'wp-edit-post' ) );
				wp_enqueue_script( 'wkit-editor-block-pmgc', WDKIT_URL . '/assets/js/main/gutenberg/wkit_g_pmgc.js', $scripts_dep, WDKIT_VERSION, false );
				wp_localize_script( 'wkit-editor-block-pmgc', 'wdkit_blocks_load', $wp_localize_tpgb );
			}
		}

		/**
		 * Here is Register Gutenberg Widgets
		 *
		 * @since 1.0.2
		 */
		public function wdkit_register_gutenberg_widgets() {
			$dir = trailingslashit( WDKIT_BUILDER_PATH ) . '/gutenberg/';

			if ( ! is_dir( $dir ) ) {
				return false;
			}

			$list = ! empty( $dir ) ? scandir( $dir ) : array();
			if ( empty( $list ) || count( $list ) <= 2 ) {
				return false;
			}

			$get_db_widget = get_option( 'wkit_deactivate_widgets', [] );
			$server_w_unique = array_column($get_db_widget, 'w_unique');

			foreach ( $list as $key => $value ) {
				if ( in_array( $value, array( '..', '.' ), true ) ) {
					continue;
				}

				if (! is_dir( trailingslashit( $dir ) . $value ) ){
					return false;
				}

				if ( ! strpos( $value, '.' ) ) {
					$sub_dir = scandir( trailingslashit( $dir ) . '/' . $value );

					foreach ( $sub_dir as $sub_dir_value ) {
						if ( in_array( $sub_dir_value, array( '..', '.' ), true ) ) {
							continue;
						}

						$file      = new SplFileInfo( $sub_dir_value );
						$check_ext = $file->getExtension();
						$ext       = pathinfo( $sub_dir_value, PATHINFO_EXTENSION );

						if ( 'php' === $ext ) {
							$json_file   = str_replace( '.php', '.json', $sub_dir_value );
							$str_replace = str_replace( '.php', '', $sub_dir_value );

							$json_path = trailingslashit( WDKIT_BUILDER_PATH ) . "/gutenberg/{$value}/{$json_file}";
							$json_data = wp_json_file_decode( $json_path );

							$w_type = ! empty( $json_data->widget_data->widgetdata->publish_type ) ? $json_data->widget_data->widgetdata->publish_type : '';
							$widget_id = ! empty( $json_data->widget_data->widgetdata->widget_id ) ? $json_data->widget_data->widgetdata->widget_id : '';
							if ( ! empty( $w_type ) && 'Publish' === $w_type ) {
								if( ! in_array( $widget_id , $server_w_unique ) ){	
									include trailingslashit( WDKIT_BUILDER_PATH ) . "/gutenberg/{$value}/{$sub_dir_value}";
								}
							}
						}
					}
				}
			}
		}
	}

	add_filter( 'block_categories_all', 'wdkit_register_block_category', 9999992, 1 );

	/**
	 * Gutenberg block category for The Plus Addon.
	 *
	 * @since 1.0.2
	 *
	 * @param array $categories Block categories.
	 */
	function wdkit_register_block_category( $categories ) {
		$category_list  = get_option( 'wkit_builder' );
		$new_categories = array();

		foreach ( $category_list as $value ) {
			$new_categories[] = array(
				'slug'  => $value,
				'title' => esc_html( $value ),
			);
		}

		return array_merge( $new_categories, $categories );
	}

	Wdkit_Gutenberg_Files_Load::instance();
}
