<?php
/**
 * Essential Grid core init.
 *
 * @package   Essential_Grid
 * @author    ThemePunch <info@themepunch.com>
 * @link      https://www.essential-grid.com/
 * @copyright 2025 ThemePunch
 * @since: 3.1.10
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit();
}

/**
 * Handle Essential Grid initialization.
 */
class Essential_Grid_Init {

	/**
	 * Init Essential Grid.
	 * 
	 * @param string $file
	 */
	public function __construct( $file ) {
		global $esg_loadbalancer;
		
		$this->esg_load_plugin_area_files( 'public' );
		if ( is_admin() ) {
			$this->esg_load_plugin_area_files( 'admin' );
		}

		Essential_Grid_Db::define_tables();

		$esg_loadbalancer = new Essential_Grid_LoadBalancer();
		$esg_loadbalancer->refresh_server_list();

		register_activation_hook( $file, [ 'Essential_Grid', 'activation_hooks' ] );

		add_action( 'plugins_loaded', [ $this, 'esg_on_plugins_loaded_public' ] );
		add_action( 'after_setup_theme', [ $this, 'esg_on_theme_setup' ] );

		if ( is_admin() ) {
			add_action( 'plugins_loaded', [ $this, 'esg_on_plugins_loaded_admin' ], 5 );
		}
	}

	/**
	 * Load all plugin files for a specific area.
	 *
	 * @param string $area public|admin.
	 */
	protected function esg_load_plugin_area_files( $area ) {
		$area = ( $area === 'admin' ) ? 'admin' : 'public';

		$directories   = [];
		$terminal_file = '';

		if ( $area === 'admin' ) {
			$directories   = [ ESG_PLUGIN_ADMIN_PATH . 'includes' ];
			$terminal_file = ESG_PLUGIN_ADMIN_PATH . 'essential-grid-admin.class.php';
		} else {
			$directories   = [ ESG_PLUGIN_PUBLIC_PATH . 'includes' ];
			$terminal_file = ESG_PLUGIN_PUBLIC_PATH . 'essential-grid.class.php';
		}

		$priority_files = [
			ESG_PLUGIN_PUBLIC_PATH . 'includes/Exception/EssentialGridException.php',
		];
		$skip_directories = [
			wp_normalize_path( ESG_PLUGIN_PUBLIC_PATH . 'includes/builders/elementor' ) . '/',
			wp_normalize_path( ESG_PLUGIN_PUBLIC_PATH . 'includes/builders/gutenberg' ) . '/',
		];

		$normalized_priority = [];
		foreach ( $priority_files as $priority ) {
			if ( file_exists( $priority ) ) {
				require_once $priority;
			}
		}

		foreach ( $directories as $directory ) {
			if ( ! is_dir( $directory ) ) {
				continue;
			}

			$iterator = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator(
					$directory,
					FilesystemIterator::SKIP_DOTS
				)
			);

			$files = [];
			foreach ( $iterator as $file ) {
				if ( $file->isFile() && strtolower( $file->getExtension() ) === 'php' ) {
					$normalized_file = wp_normalize_path( $file->getPathname() );
					foreach ( $skip_directories as $skip_dir ) {
						if ( strpos( $normalized_file, $skip_dir ) === 0 ) {
							continue 2;
						}
					}
					$files[] = $file->getPathname();
				}
			}

			sort( $files, SORT_NATURAL | SORT_FLAG_CASE );

			foreach ( $files as $file ) {
				require_once $file;
			}
		}

		if ( file_exists( $terminal_file ) ) {
			require_once $terminal_file;
		}
	}

	public function esg_on_plugins_loaded_public() {
		Essential_Grid_Adminbar::get_instance();
		Essential_Grid_Image_Optimization::get_instance();
		Essential_Grid_Post_Type::get_instance();
		Essential_Grid_Wpml::get_instance();
		Essential_Grid_Wpseo::get_instance();
		Essential_Grid_Woocommerce::get_instance();
		Essential_Grid_Builders::get_instance();
		Essential_Grid_Page_Template::get_instance();
	}

	public function esg_on_plugins_loaded_admin() {
		Essential_Grid_Db::create_tables();

		$updates = new Essential_Grid_Plugin_Update( Essential_Grid_Db::get_version() );
		$updates->do_update_process();

		Essential_Grid_Assets::get_instance();
		Essential_Grid_Admin::get_instance();
	}

	public function esg_on_theme_setup() {
		Essential_Grid::get_instance();
		add_action( 'widgets_init', [ 'Essential_Grid', 'register_custom_sidebars' ] );
		add_action( 'widgets_init', [ 'Essential_Grid', 'register_custom_widget' ] );

		add_filter( 'the_content', [ 'Essential_Grid', 'fix_shortcodes' ] );
		add_filter( 'post_thumbnail_html', [ 'Essential_Grid', 'post_thumbnail_replace' ], 20, 5 );

		add_shortcode( 'ess_grid', [ 'Essential_Grid', 'register_shortcode' ] );
		add_shortcode( 'ess_grid_ajax_target', [ 'Essential_Grid', 'register_shortcode_ajax_target' ] );
		add_shortcode( 'ess_grid_nav', [ 'Essential_Grid', 'register_shortcode_filter' ] );
		add_shortcode( 'ess_grid_search', [ 'Essential_Grid_Search', 'register_shortcode_search' ] );

		if ( ! is_admin() ) {
			new Essential_Grid_Search();
		}
	}
}
