<?php
/**
 * Plugin Activation Class
 *
 * @package SHOPEXPLORER\Inc
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Inc;

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

/**
 * Activation class
 *
 * @since 1.0.0
 */
class SHOPEX_Activate {

	/**
	 * Activate the plugin
	 *
	 * @since 1.0.0
	 */
	public static function activate() {
		// Check requirements
		self::check_requirements();

		// Create database tables if needed
		self::create_tables();

		// Set default options
		self::set_default_options();

		// Schedule cron jobs
		self::schedule_cron_jobs();

		// Create frontend dashboard page
		self::create_dashboard_page();

		// Set activation redirect flag
		add_option( 'shopex_activation_redirect', true );

		// Flush rewrite rules
		flush_rewrite_rules();
	}

	/**
	 * Check plugin requirements
	 *
	 * @since 1.0.0
	 */
	private static function check_requirements() {
		// Check PHP version
		$min_php_version = '7.4';
		if ( version_compare( PHP_VERSION, $min_php_version, '<' ) ) {
			add_action( 'admin_notices', function () use ( $min_php_version ) {
				?>
				<div class="notice notice-error">
					<p>
						<?php
						printf(
							/* translators: %s: Minimum required PHP version */
							esc_html__( 'Shop Explorer requires PHP version %s or higher.', 'shop-explorer' ),
							esc_html( $min_php_version )
						);
						?>
					</p>
				</div>
				<?php
			});
			return;
		}

		// Check WordPress version
		$min_wp_version = '6.0';
		if ( version_compare( get_bloginfo( 'version' ), $min_wp_version, '<' ) ) {
			deactivate_plugins( SHOPEX_BASENAME );
			wp_die(
				sprintf(
					/* translators: %s: Minimum required WordPress version */
					esc_html__( 'Shop Explorer requires WordPress version %s or higher.', 'shop-explorer' ),
					esc_html( $min_wp_version )
				)
			);
		}

		// Check if WooCommerce is active - handled in main plugin file now
		// This check is redundant but kept for safety

		// Check WooCommerce version
		$min_wc_version = '8.0.0';
		if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, $min_wc_version, '<' ) ) {
			deactivate_plugins( SHOPEX_BASENAME );
			wp_die(
				sprintf(
					/* translators: 1: Minimum required WooCommerce version, 2: Current WooCommerce version */
					esc_html__( 'Shop Explorer requires WooCommerce version %1$s or higher. You are running version %2$s.', 'shop-explorer' ),
					esc_html( $min_wc_version ),
					esc_html( WC_VERSION )
				)
			);
		}
	}

	/**
	 * Create database tables
	 *
	 * @since 1.0.0
	 */
	private static function create_tables() {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		// Sync log table
		$sync_log_table = $wpdb->prefix . 'shopex_sync_log';
		$sync_log_sql = "CREATE TABLE $sync_log_table (
			id bigint(20) NOT NULL AUTO_INCREMENT,
			sync_type varchar(50) NOT NULL,
			operation varchar(50) NOT NULL,
			item_id bigint(20) NOT NULL,
			status varchar(20) NOT NULL,
			message text,
			sync_time datetime DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY sync_type (sync_type),
			KEY item_id (item_id),
			KEY sync_time (sync_time)
		) $charset_collate;";

		// Configuration table
		$config_table = $wpdb->prefix . 'shopex_config';
		$config_sql = "CREATE TABLE $config_table (
			id bigint(20) NOT NULL AUTO_INCREMENT,
			config_key varchar(100) NOT NULL,
			config_value longtext,
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY config_key (config_key)
		) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sync_log_sql );
		dbDelta( $config_sql );

		// Create WooCommerce Analytics tables
		self::create_analytics_tables();

		// Update database version
		update_option( 'shopex_db_version', SHOPEX_VERSION );
	}

	/**
	 * Create WooCommerce Analytics tables
	 *
	 * @since 1.0.0
	 */
	private static function create_analytics_tables() {
		// Load WooAnalyticsTables class
		if ( ! class_exists( 'SHOPEXPLORER\\Database\\WooAnalyticsTables' ) ) {
			require_once SHOPEX_PATH . 'inc/Database/WooAnalyticsTables.php';
		}

		$analytics_tables = new \SHOPEXPLORER\Database\WooAnalyticsTables();
		$analytics_tables->create_tables();
	}

	/**
	 * Set default options
	 *
	 * @since 1.0.0
	 */
	private static function set_default_options() {
		// Set plugin version
		update_option( 'shopex_version', SHOPEX_VERSION );

		// Set default configuration using ConfigurationManager
		if ( class_exists( 'SHOPEXPLORER\\Core\\SHOPEX_ConfigurationManager' ) ) {
			$config_manager = new \SHOPEXPLORER\Core\SHOPEX_ConfigurationManager();
			// Default settings are automatically initialized in the constructor
		}

		// Set installation date
		if ( ! get_option( 'shopex_installed_date' ) ) {
			update_option( 'shopex_installed_date', current_time( 'mysql' ) );
		}

		// Initialize frontend dashboard settings
		if ( ! get_option( 'shop_explorer_frontend_settings' ) ) {
			update_option( 'shop_explorer_frontend_settings', [
				'orders_management' => [
					'enabled' => false,
					'default_statuses' => [],
					'custom_statuses' => [],
					'filter_settings' => [],
					'filter_sections' => [],
				],
				'products_management' => [
					'enabled' => false,
				],
				'customer_management' => [
					'enabled' => false,
				],
			] );
		}
	}

	/**
	 * Schedule cron jobs
	 *
	 * @since 1.0.0
	 */
	private static function schedule_cron_jobs() {
		// Schedule sync cron job
		if ( ! wp_next_scheduled( 'shopex_sync_cron' ) ) {
			wp_schedule_event( time(), 'hourly', 'shopex_sync_cron' );
		}

		// Schedule cleanup cron job
		if ( ! wp_next_scheduled( 'shopex_cleanup_cron' ) ) {
			wp_schedule_event( time(), 'daily', 'shopex_cleanup_cron' );
		}
	}

	/**
	 * Create frontend dashboard page
	 *
	 * @since 1.0.0
	 */
	private static function create_dashboard_page() {
		// Initialize FrontendDashboard to create the page and add rewrite rules
		if ( ! class_exists( 'ShopExplorer\\FrontendDashboard' ) ) {
			require_once SHOPEX_PATH . 'inc/FrontendDashboard.php';
		}

		$frontend_dashboard = new \ShopExplorer\FrontendDashboard( SHOPEX_FILE );
		$frontend_dashboard->activate();
	}
}
