<?php
namespace AtomicSlider;

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

/**
 * Plugin class.
 *
 * The main class that initiates and runs the addon.
 *
 * @since 1.0.0
 */
final class Plugin {

	/**
	 * Plugin directory path
	 */
	private $plugin_dir;

	/**
	 * Main plugin file
	 */
	private $plugin_file;

	/**
	 * Addon Version
	 * 
	 * @return string
	 * @deprecated
	 *
	 */
	public function get_version() {
		return ATOMSL_VER;
	}

	/**
	 * Minimum Elementor Version
	 *
	 * @since 1.0.0
	 * @var string Minimum Elementor version required to run the addon.
	 */
	const MINIMUM_ELEMENTOR_VERSION = '3.20.0';

	/**
	 * Minimum PHP Version
	 *
	 * @since 1.0.0
	 * @var string Minimum PHP version required to run the addon.
	 */
	const MINIMUM_PHP_VERSION = '7.4';

	/**
	 * Instance
	 *
	 * @since 1.0.0
	 * @access private
	 * @static
	 * @var \AtomicSlider\Plugin 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.0
	 * @access public
	 * @static
	 * @return \AtomicSlider\Plugin An instance of the class.
	 */
	public static function instance() {

		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();

			/**
			 * Atomic Slider loaded.
			 *
			 * Fires when Atomic Slider was fully loaded and instantiated.
			 *
			 * @since 1.0.0
			 */
			do_action( 'atomic-slider/loaded' );
		}
		return self::$_instance;

	}

	/**
	 * Constructor
	 *
	 * Perform some compatibility checks to make sure basic requirements are meet.
	 * If all compatibility checks pass, initialize the functionality.
	 *
	 * @since 1.0.0
	 * @access public
	 */
	public function __construct() {
		// Set plugin directory path and find main plugin file
		$this->plugin_dir = dirname(__DIR__);
		$this->plugin_file = $this->find_plugin_file();

		if ( $this->is_compatible() ) {
			add_action( 'elementor/init', [ $this, 'init' ] );
		}

		$this->_includes();

	}

	/**
	 * Find the main plugin file
	 */
	private function find_plugin_file() {
		$plugin_dir = $this->plugin_dir;
		$files = glob($plugin_dir . '/*.php');
		
		foreach ($files as $file) {
			$content = file_get_contents($file);
			if (strpos($content, 'Plugin Name:') !== false) {
				return $file;
			}
		}
		
		// Fallback to the directory name
		return $plugin_dir . '/' . basename($plugin_dir) . '.php';
	}

	/**
	 * Compatibility Checks
	 *
	 * Checks whether the site meets the addon requirement.
	 *
	 * @since 1.0.0
	 * @access public
	 */
	public function is_compatible(): bool {

		// Check for required PHP version
		if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
			add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
			return false;
		}

		return true;

	}

	/**
     * Widgets Categories
     */

	 function add_elementor_widget_categories( $elements_manager ) {

        $elements_manager->add_category(
            'atomic-slider',
            [
                'title' => esc_html__( 'Atomic Slider', 'atomic-slider' ),
                'icon' => 'fa fa-plug',
            ]
        );
    
    }


	private function _includes() {

		// Dynamic Select control
		require_once ( dirname( __FILE__ ) . '/controls/select-input/dynamic-select-input-module.php' );
		require_once ( dirname( __FILE__ ) . '/controls/select-input/dynamic-select.php' );
		
		// Group Query Control
		require_once ( dirname( __FILE__ ) . '/controls/group-query/group-control-query.php' );
		
		// Global Controls
		require_once ( dirname( __FILE__ ) . '/traits/global-widget-controls.php' );
		require_once ( dirname( __FILE__ ) . '/traits/global-widget-functions.php' );
		require_once ( dirname( __FILE__ ) . '/traits/global-swiper-controls.php' );
	}

	/**
	 * Initialize
	 *
	 * Load the addons functionality only after Elementor is initialized.
	 *
	 * Fired by `elementor/init` action hook.
	 *
	 * @since 1.0.0
	 * @access public
	 */
	public function init(): void {

		add_action( 'elementor/widgets/register', [ $this, 'register_widgets' ] );

        add_action( 'elementor/frontend/after_register_styles', [ $this, 'register_frontend_styles' ] );
		add_action( 'elementor/frontend/after_register_scripts', [ $this, 'register_frontend_scripts' ] );

		add_action( 'elementor/frontend/after_enqueue_styles', [ $this, 'enqueue_frontend_styles' ] );
		add_action( 'elementor/editor/after_enqueue_styles', [ $this, 'enqueue_editor_styles' ] );
		add_action( 'elementor/frontend/after_enqueue_scripts', [ $this, 'enqueue_frontend_scripts' ] );

        add_action( 'elementor/elements/categories_registered', [ $this, 'add_elementor_widget_categories' ] );

		add_action('admin_init', [$this, 'enqueue_admin_styles']);
		add_action('admin_enqueue_scripts', [$this, 'atomsl_admin_scripts']);
	}

	/**
	 * Register Widgets
	 *
	 * Load widgets files and register new Elementor widgets.
	 *
	 * Fired by `elementor/widgets/register` action hook.
	 *
	 * @param \Elementor\Widgets_Manager $widgets_manager Elementor widgets manager.
	 */
	public function register_widgets( $widgets_manager ) {
		// Get the widgets directory path
		$widgets_dir = __DIR__ . '/widgets/';
		
		// Get all PHP files in the widgets directory
		$widget_files = glob($widgets_dir . '*.php');
		
		// Get the active widget options - use a special default to distinguish "never set" from "explicitly empty"
		$widget_options = get_option('atomic-slider-widgets', null);
		
		// Check if options were explicitly set (not null means it exists in DB, even if empty array)
		$options_exist = ($widget_options !== null);
		
		// If options don't exist at all, register all widgets (fallback for first time)
		// If options exist (even if empty), only register explicitly enabled widgets
		$register_all = !$options_exist;
		
		// Register widgets dynamically
		foreach ($widget_files as $file) {
			// Get the filename without extension
			$filename = basename($file, '.php');
			
			// Convert filename to widget key (e.g., 'accordion.php' -> 'accordion')
			$widget_key = $filename;
			
			// Check if this widget should be registered
			// Only register if: (options never set) OR (widget key exists and has truthy value)
			if ($register_all || (isset($widget_options[$widget_key]) && !empty($widget_options[$widget_key]))) {
				// Include the widget file
				require_once $file;
				
				// Try to determine the class name from the file
				$class_name = $this->get_widget_class_from_file($file);
				
				if ($class_name && class_exists($class_name)) {
					try {
						$widgets_manager->register(new $class_name());
					} catch (\Exception $e) {
						// Log error but continue with other widgets
						error_log('Failed to register widget: ' . $class_name . ' - ' . $e->getMessage());
					}
				}
			}
		}
	}
	
	/**
	 * Get widget class name from file
	 *
	 * @param string $file Widget file path
	 * @return string|false Class name or false if not found
	 */
	private function get_widget_class_from_file($file) {
		// Read the file content
		$content = file_get_contents($file);
		
		// Look for class definition pattern - more flexible regex
		if (preg_match('/class\s+(\w+)\s+extends\s+[\\\]?Elementor[\\\]?Widget_Base/', $content, $matches)) {
			$class_name = $matches[1];
			
			// Get the namespace if it exists
			if (preg_match('/namespace\s+([^;]+);/', $content, $namespace_matches)) {
				$namespace = trim($namespace_matches[1]);
				return $namespace . '\\' . $class_name;
			}
			
			// If no namespace, return just the class name
			return $class_name;
		}
		
		return false;
	}

    /**
     * Registering Custom Scripts & Styles
     */

    public function register_frontend_styles(): void {
		$direction_suffix = is_rtl() ? '.rtl' : '';
		
		// Get the widgets directory path
		$widgets_dir = __DIR__ . '/widgets/';
		
		// Get all PHP files in the widgets directory
		$widget_files = glob($widgets_dir . '*.php');
		
		// Get the active widget options - use null to distinguish "never set" from "explicitly empty"
		$widget_options = get_option('atomic-slider-widgets', null);
		
		// Check if options were explicitly set
		$options_exist = ($widget_options !== null);
		
		// If no options are set, register all widget styles (fallback)
		$register_all = !$options_exist;
		
		// Debug: Log style registration info
		error_log('Registering styles for ' . count($widget_files) . ' widgets. Register all: ' . ($register_all ? 'true' : 'false'));
		
		// Register widget styles dynamically
		foreach ($widget_files as $file) {
			// Get the filename without extension
			$filename = basename($file, '.php');
			
			// Convert filename to widget key (e.g., 'accordion.php' -> 'accordion')
			$widget_key = $filename;
			
			// Check if this widget should have its styles registered
			if ($register_all || (isset($widget_options[$widget_key]) && !empty($widget_options[$widget_key]))) {
				// Generate the CSS file name
				$css_file_name = 'asa-' . str_replace('_', '-', $widget_key);
				$css_file_path = 'assets/css/' . $css_file_name . $direction_suffix . '.css';
				$css_file_url = plugins_url($css_file_path, $this->plugin_file);
				
				// Check if the CSS file exists before registering
				$css_file_full_path = $this->plugin_dir . '/' . $css_file_path;
				if (file_exists($css_file_full_path)) {
					wp_register_style($css_file_name, $css_file_url, [], ATOMSL_VER);
					error_log('Registered style: ' . $css_file_name . ' - ' . $css_file_url);
				} else {
					error_log('CSS file not found: ' . $css_file_full_path);
				}
			}
		}
	}

	public function register_frontend_scripts(): void {

		wp_register_script( 'asa-site', plugins_url( 'assets/js/asa-site.js', $this->plugin_file ), ['jquery'], ATOMSL_VER, true );

		// Register vendor scripts in proper order
		wp_register_script( 'super-flow', plugins_url( 'assets/js/vendor/super-flow.min.js', $this->plugin_file ), [], ATOMSL_VER, true );
		
		// Get the widgets directory path
		$widgets_dir = __DIR__ . '/widgets/';
		
		// Get all PHP files in the widgets directory
		$widget_files = glob($widgets_dir . '*.php');
		
		// Get the active widget options - use null to distinguish "never set" from "explicitly empty"
		$widget_options = get_option('atomic-slider-widgets', null);
		
		// Check if options were explicitly set
		$options_exist = ($widget_options !== null);
		
		// If no options are set, register all widget scripts (fallback)
		$register_all = !$options_exist;
		
		// Register widget scripts dynamically
		foreach ($widget_files as $file) {
			// Get the filename without extension
			$filename = basename($file, '.php');
			
			// Convert filename to widget key (e.g., 'accordion.php' -> 'accordion')
			$widget_key = $filename;
			
			// Check if this widget should have its scripts registered
			if ($register_all || (isset($widget_options[$widget_key]) && !empty($widget_options[$widget_key]))) {
				// Generate the JS file name
				$js_file_name = 'asa-' . str_replace('_', '-', $widget_key);
				$js_file_path = 'assets/js/widgets/' . $js_file_name . '.min.js';
				$js_file_url = plugins_url($js_file_path, $this->plugin_file);
				
				// Check if the JS file exists before registering
				$js_file_full_path = $this->plugin_dir . '/' . $js_file_path;
				if (file_exists($js_file_full_path)) {
					// Determine dependencies based on widget type
					$dependencies = ['jquery'];
					
					// Add specific dependencies for certain widgets
					//if (in_array($widget_key, ['image_stack', 'interactive_links'])) {
					//	$dependencies[] = 'popper';
					//}
					
					wp_register_script($js_file_name, $js_file_url, $dependencies, ATOMSL_VER, true);
				}
			}
		}
	}

	public function enqueue_frontend_scripts(): void {

		wp_enqueue_script( 'asa-site' );
		
		// These need to be enqueued in the proper order
		wp_enqueue_script( 'popper' );
	}

	public function enqueue_frontend_styles(): void {
		$direction_suffix = is_rtl() ? '.rtl' : '';

		
		wp_register_style( 'asa-site', plugins_url( 'assets/css/asa-site' . $direction_suffix . '.css', $this->plugin_file ), [], ATOMSL_VER );
		//wp_register_style( 'uikit', plugins_url( 'assets/css/asa-uikit' . $direction_suffix . '.css', $this->plugin_file ), [], ATOMSL_VER );

		//wp_enqueue_style( 'uikit' );
		wp_enqueue_style( 'asa-site' );

		wp_enqueue_style( 'elementor-icons' );
	}

	public function enqueue_editor_styles() {
		$direction_suffix = is_rtl() ? '.rtl' : '';

		wp_register_style( 'asa-editor', plugins_url( 'assets/css/asa-editor' . $direction_suffix . '.css', $this->plugin_file ), [], ATOMSL_VER );

		wp_enqueue_style( 'asa-editor' );
	}

	public function enqueue_admin_styles() {
		$direction_suffix = is_rtl() ? '.rtl' : '';

		wp_register_style( 'asa-admin', plugins_url( 'assets/css/asa-admin' . $direction_suffix . '.css', $this->plugin_file ), [], ATOMSL_VER );

		wp_enqueue_style( 'asa-admin' );
	}

	public function atomsl_admin_scripts() {
		wp_enqueue_script( 'asa-admin-js', plugins_url( 'assets/js/asa-admin.js', $this->plugin_file ), ['jquery'], ATOMSL_VER, true );

		// Localize script to pass data from PHP to JavaScript
		wp_localize_script('asa-admin-js', 'atomicSlider', [
			'security' => wp_create_nonce('atomicslider_save_widgets_nonce'),
			'ajaxurl' => admin_url('admin-ajax.php'),
			'i18n' => [
				'errorMessage' => __('An error occurred while saving. Please try again.', 'atomic-slider')
			]
		]);
	}

}