<?php
/**
 * Main Shop Explorer Plugin Class
 *
 * @package ShopExplorer\Core
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Core;

use SHOPEXPLORER\Inc\SHOPEX_AdminDashboard;
use SHOPEXPLORER\Inc\SHOPEX_Enqueue;
use SHOPEXPLORER\Api\SHOPEX_RestApiController;
use SHOPEXPLORER\Core\SHOPEX_ConfigurationManager;

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

/**
 * Main Shop Explorer class
 *
 * @since 1.0.0
 */
class SHOPEX_ShopExplorer {

	/**
	 * Plugin instance
	 *
	 * @var SHOPEX_ShopExplorer
	 */
	private static $instance = null;

	/**
	 * Configuration manager instance
	 *
	 * @var SHOPEX_ConfigurationManager
	 */
	private $config_manager;

	/**
	 * Logger instance
	 *
	 * @var SHOPEX_Logger
	 */
	private $logger;

	/**
	 * Loaded modules
	 *
	 * @var array
	 */
	private $modules = [];

	/**
	 * Get plugin instance
	 *
	 * @return SHOPEX_ShopExplorer
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor
	 */
	private function __construct() {
		$this->init_hooks();
		$this->load_dependencies();
		$this->init_modules();
	}

	/**
	 * Initialize WordPress hooks
	 */
	private function init_hooks() {
		add_action( 'admin_init', [ $this, 'check_requirements' ] );
		add_action( 'rest_api_init', [ $this, 'init_rest_api' ] );
	}

	/**
	 * Load plugin dependencies
	 */
	private function load_dependencies() {
		// Load configuration manager
		require_once SHOPEX_PATH . 'inc/Core/ConfigurationManager.php';
		$this->config_manager = new SHOPEX_ConfigurationManager();

		// Load other core classes as needed
		$this->load_core_classes();

		// Set up log cleanup hook
		add_action( 'shopex_log_cleanup', [ $this->logger, 'cleanup_old_logs' ] );
	}

	/**
	 * Load core classes
	 */
	private function load_core_classes() {
		$core_classes = [
			'inc/AdminDashboard.php',
			'inc/Enqueue.php',
			'inc/Exceptions/ShopExplorerException.php',
			'inc/Exceptions/ConfigurationException.php',
			'inc/Exceptions/SyncException.php',
			'inc/Api/RestApiController.php',
			'inc/Admin/SettingsManager.php',
		];

		// Load module classes
		$module_classes = [
			'inc/Modules/OrderManager.php',
			'inc/Modules/ProductManager.php',
			'inc/Modules/OrderSyncManager.php',
			'inc/Modules/ProductSyncManager.php',
			'inc/Database/DatabaseManager.php',
			'inc/Models/OrderDataModel.php',
			'inc/Models/ProductDataModel.php',
			'inc/Models/SyncDataModel.php',
		];

		$core_classes = array_merge( $core_classes, $module_classes );

		foreach ( $core_classes as $class_file ) {
			$file_path = SHOPEX_PATH . $class_file;
			if ( file_exists( $file_path ) ) {
				require_once $file_path;
			}
		}
	}

	/**
	 * Initialize plugin modules
	 */
	private function init_modules() {
		// Initialize admin dashboard
		if ( is_admin() ) {
			$this->modules['admin_dashboard'] = new SHOPEX_AdminDashboard();
		}

		// Initialize asset enqueuing
		$enqueue = new SHOPEX_Enqueue();
		$enqueue->register();
		$this->modules['enqueue'] = $enqueue;

		// Initialize AJAX handlers
		if ( class_exists( 'SHOPEXPLORER\\Inc\\Ajax\\SHOPEX_Ajax' ) ) {
			require_once SHOPEX_PATH . 'inc/Ajax/Ajax.php';
			$this->modules['ajax'] = new \SHOPEXPLORER\Inc\Ajax\SHOPEX_Ajax();
		}

		// Initialize frontend dashboard
		if ( ! class_exists( 'ShopExplorer\\FrontendDashboard' ) ) {
			require_once SHOPEX_PATH . 'inc/FrontendDashboard.php';
		}
		$this->modules['frontend_dashboard'] = new \ShopExplorer\FrontendDashboard( SHOPEX_FILE );

		// Initialize custom fields display
		if ( ! class_exists( 'SHOPEXPLORER\\SHOPEX_CustomFieldsDisplay' ) ) {
			require_once SHOPEX_PATH . 'inc/CustomFieldsDisplay.php';
		}
		$this->modules['custom_fields'] = new \SHOPEXPLORER\SHOPEX_CustomFieldsDisplay();

		// Register product_brand taxonomy
		add_action( 'init', [ $this, 'register_product_brand_taxonomy' ], 0 );

		// Initialize Ajax handlers
		if ( ! class_exists( 'ShopExplorer\\Ajax\\SHOPEX_AjaxHandler' ) ) {
			require_once SHOPEX_PATH . 'inc/Ajax/AjaxHandler.php';
		}
		$this->modules['ajax_handler'] = new \ShopExplorer\Ajax\SHOPEX_AjaxHandler();

		// Initialize Cart Abandonment Tracker
		if ( ! class_exists( 'SHOPEXPLORER\\Ajax\\SHOPEX_CartAbandonmentTracker' ) ) {
			require_once SHOPEX_PATH . 'inc/Ajax/CartAbandonmentTracker.php';
		}
		$this->modules['cart_abandonment_tracker'] = new \SHOPEXPLORER\Ajax\SHOPEX_CartAbandonmentTracker();

		// Load additional modules based on configuration
		$this->load_conditional_modules();
	}

	/**
	 * Load modules based on configuration
	 */
	private function load_conditional_modules() {
		// Load order management module if enabled
		if ( $this->is_database_mode_enabled() ) {
			$this->load_management_modules();
		}
	}

	/**
	 * Load management modules (orders, products)
	 */
	private function load_management_modules() {
		// This will be implemented in later tasks
		// For now, just set a flag that modules are ready to be loaded
		$this->modules['management_ready'] = true;
	}

	/**
	 * Load multivendor module
	 */
	private function load_multivendor_module() {
		// This will be implemented in later tasks
		$this->modules['multivendor_ready'] = true;
	}

	/**
	 * Initialize REST API
	 */
	public function init_rest_api() {
		$api_controller = new SHOPEX_RestApiController();
		$api_controller->register_routes();
		$this->modules['rest_api'] = $api_controller;
	}

	/**
	 * Check plugin requirements
	 */
	public function check_requirements() {
		// Check WooCommerce version
		if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, SHOPEX_MIN_WC_VERSION, '<' ) ) {
			add_action( 'admin_notices', function () {
				echo '<div class="notice notice-error"><p>';
				printf(
					/* translators: %s: is the product id */
					esc_html__( 'Shop Explorer requires WooCommerce version %1$s or higher. You are running version %2$s.', 'shop-explorer' ),
					esc_html( SHOPEX_MIN_WC_VERSION ),
					esc_html( WC_VERSION )
				);
				echo '</p></div>';
			});
		}
	}

	/**
	 * Register product_brand taxonomy
	 */
	public function register_product_brand_taxonomy() {
		register_taxonomy(
			'product_brand',
			'product',
			array(
				'label' => __( 'Brands', 'shop-explorer' ),
				'labels' => array(
					'name' => __( 'Brands', 'shop-explorer' ),
					'singular_name' => __( 'Brand', 'shop-explorer' ),
					'menu_name' => __( 'Brands', 'shop-explorer' ),
					'all_items' => __( 'All Brands', 'shop-explorer' ),
					'edit_item' => __( 'Edit Brand', 'shop-explorer' ),
					'view_item' => __( 'View Brand', 'shop-explorer' ),
					'update_item' => __( 'Update Brand', 'shop-explorer' ),
					'add_new_item' => __( 'Add New Brand', 'shop-explorer' ),
					'new_item_name' => __( 'New Brand Name', 'shop-explorer' ),
					'search_items' => __( 'Search Brands', 'shop-explorer' ),
					'popular_items' => __( 'Popular Brands', 'shop-explorer' ),
					'separate_items_with_commas' => __( 'Separate brands with commas', 'shop-explorer' ),
					'add_or_remove_items' => __( 'Add or remove brands', 'shop-explorer' ),
					'choose_from_most_used' => __( 'Choose from most used brands', 'shop-explorer' ),
					'not_found' => __( 'No brands found', 'shop-explorer' ),
				),
				'public' => true,
				'hierarchical' => false,
				'show_ui' => true,
				'show_in_menu' => false,
				'show_in_nav_menus' => true,
				'show_in_rest' => true,
				'show_tagcloud' => true,
				'show_in_quick_edit' => true,
				'show_admin_column' => true,
				'rewrite' => array(
					'slug' => 'brand',
					'with_front' => true,
					'hierarchical' => false,
				),
			)
		);
	}

	/**
	 * Check if database mode is enabled
	 *
	 * @return bool
	 */
	public function is_database_mode_enabled() {
		return $this->config_manager->is_database_mode_enabled();
	}



	/**
	 * Get configuration manager
	 *
	 * @return SHOPEX_ConfigurationManager
	 */
	public function get_config_manager() {
		return $this->config_manager;
	}

	/**
	 * Get loaded modules
	 *
	 * @return array
	 */
	public function get_modules() {
		return $this->modules;
	}


	/**
	 * Prevent cloning
	 */
	private function __clone() {}

	/**
	 * Prevent unserialization
	 */
	public function __wakeup() {
		return false;
	}
}
