<?php
/**
 * Plugin activator.
 *
 * @package KwiroAISalesAgent
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Kwiro_Activator
 *
 * Handles plugin activation: version checks, option creation, CRON scheduling.
 */
class Kwiro_Activator {

	/**
	 * Minimum PHP version required.
	 */
	const MIN_PHP_VERSION = '7.4';

	/**
	 * Minimum WordPress version required.
	 */
	const MIN_WP_VERSION = '5.8';

	/**
	 * Minimum WooCommerce version required.
	 */
	const MIN_WC_VERSION = '7.0';

	/**
	 * Run activation routine.
	 */
	public static function activate() {
		self::check_requirements();
		self::create_options();
		self::run_migrations();
		self::schedule_cron_events();
		self::set_activation_flag();
	}

	/**
	 * Activation housekeeping. Always runs on activate.
	 *
	 * Nukes short-lived transient state (backoff errors, JWT cache, sync lock)
	 * so every activation starts fresh. Store-identity options (api_key,
	 * store_id, public_key) are preserved so v1.0 → v1.1 upgrades don't
	 * orphan existing installs. Writes the current version to kwiro_version
	 * for future migrations.
	 */
	public static function run_migrations() {
		// v1.1.x → v1.2.0: prefix migration. Pre-1.2 installs stored options
		// under the legacy `aisales_*` prefix. Carry them over to `kwiro_*`
		// so reactivation under the new slug doesn't orphan API keys, store
		// IDs, sync history, etc. Migration is idempotent (skips if a kwiro_
		// option already exists) so re-running activate doesn't clobber
		// fresher data with stale legacy values.
		self::migrate_legacy_options();

		delete_transient( 'kwiro_register_backoff' );
		delete_transient( 'kwiro_jwt_token' );
		delete_transient( 'kwiro_sync_lock' );
		delete_transient( 'kwiro_link_status' );
		update_option( 'kwiro_version', KWIRO_VERSION );
	}

	/**
	 * Carry forward v1.1.x option data (`aisales_*`) onto the v1.2.x
	 * prefix (`kwiro_*`). Runs once on the first v1.2 activation; later
	 * activations are no-ops because kwiro_version is already set. Options
	 * that exist on both prefixes are left alone — newer wins.
	 */
	private static function migrate_legacy_options() {
		$legacy_to_new = array(
			'aisales_api_key'         => 'kwiro_api_key',
			'aisales_store_id'        => 'kwiro_store_id',
			'aisales_public_key'      => 'kwiro_public_key',
			'aisales_dashboard_token' => 'kwiro_dashboard_token',
			'aisales_settings'        => 'kwiro_settings',
			'aisales_sync_status'     => 'kwiro_sync_status',
			'aisales_user_consented'  => 'kwiro_user_consented',
			'aisales_version'         => 'kwiro_version',
		);

		foreach ( $legacy_to_new as $old_key => $new_key ) {
			$legacy = get_option( $old_key, null );
			if ( null === $legacy ) {
				continue;
			}
			if ( false === get_option( $new_key, false ) ) {
				update_option( $new_key, $legacy, false );
			}
			delete_option( $old_key );
		}

		// Migrate any v1.1.x scheduled CRON jobs to the v1.2.x hook names.
		$legacy_hooks = array(
			'aisales_batch_sync'       => 'kwiro_batch_sync',
			'aisales_weekly_full_sync' => 'kwiro_weekly_full_sync',
		);
		foreach ( $legacy_hooks as $old_hook => $new_hook ) {
			$next = wp_next_scheduled( $old_hook );
			if ( $next ) {
				wp_clear_scheduled_hook( $old_hook );
				if ( ! wp_next_scheduled( $new_hook ) ) {
					wp_schedule_event( $next, 'hourly', $new_hook );
				}
			}
		}
	}

	/**
	 * Check minimum version requirements.
	 *
	 * @throws \Exception If requirements are not met.
	 */
	public static function check_requirements() {
		if ( version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '<' ) ) {
			deactivate_plugins( KWIRO_PLUGIN_BASENAME );
			wp_die(
				sprintf(
					/* translators: %s: Required PHP version */
					esc_html__( 'Kwiro requires PHP %s or higher.', 'kwiro-ai-sales-agent' ),
					esc_html( self::MIN_PHP_VERSION )
				),
				esc_html__( 'Plugin Activation Error', 'kwiro-ai-sales-agent' ),
				array( 'back_link' => true )
			);
		}

		global $wp_version;
		if ( version_compare( $wp_version, self::MIN_WP_VERSION, '<' ) ) {
			deactivate_plugins( KWIRO_PLUGIN_BASENAME );
			wp_die(
				sprintf(
					/* translators: %s: Required WordPress version */
					esc_html__( 'Kwiro requires WordPress %s or higher.', 'kwiro-ai-sales-agent' ),
					esc_html( self::MIN_WP_VERSION )
				),
				esc_html__( 'Plugin Activation Error', 'kwiro-ai-sales-agent' ),
				array( 'back_link' => true )
			);
		}

		if ( ! defined( 'WC_VERSION' ) || version_compare( WC_VERSION, self::MIN_WC_VERSION, '<' ) ) {
			deactivate_plugins( KWIRO_PLUGIN_BASENAME );
			wp_die(
				sprintf(
					/* translators: %s: Required WooCommerce version */
					esc_html__( 'Kwiro requires WooCommerce %s or higher.', 'kwiro-ai-sales-agent' ),
					esc_html( self::MIN_WC_VERSION )
				),
				esc_html__( 'Plugin Activation Error', 'kwiro-ai-sales-agent' ),
				array( 'back_link' => true )
			);
		}
	}

	/**
	 * Create default plugin options.
	 */
	public static function create_options() {
		$default_settings = array(
			'widget_enabled'  => true,
			'widget_position' => 'bottom-right',
			'widget_color'    => '#1d1d1f',
			'powered_by'      => true,
			'welcome_message' => __( 'Hi! I can help you find the perfect product. What are you looking for?', 'kwiro-ai-sales-agent' ),
			'sync_interval'   => 'daily',
			'batch_size'      => 50,
		);

		add_option( 'kwiro_api_key', '' );
		add_option( 'kwiro_store_id', '' );
		add_option( 'kwiro_settings', $default_settings );
		add_option(
			'kwiro_sync_status',
			array(
				'last_sync'      => null,
				'products_count' => 0,
				'status'         => 'pending',
			)
		);
		add_option( 'kwiro_version', KWIRO_VERSION );
	}

	/**
	 * Schedule WP CRON events.
	 */
	public static function schedule_cron_events() {
		if ( ! wp_next_scheduled( 'kwiro_batch_sync' ) ) {
			wp_schedule_event( time(), 'hourly', 'kwiro_batch_sync' );
		}

		if ( ! wp_next_scheduled( 'kwiro_weekly_full_sync' ) ) {
			wp_schedule_event( time(), 'weekly', 'kwiro_weekly_full_sync' );
		}
	}

	/**
	 * Set a transient flag to trigger redirect after activation.
	 */
	public static function set_activation_flag() {
		set_transient( 'kwiro_activated', true, 30 );
	}
}
