<?php
/**
 * Plugin Activator
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Core;

/**
 * Handles plugin activation and deactivation
 */
class Activator {

	/**
	 * Plugin activation
	 *
	 * @param bool $network_wide Whether the plugin is being network-activated.
	 */
	public static function activate( $network_wide = false ) {
		// CDT-04: custom tables are site-prefixed; network activation is unsupported.
		if ( is_multisite() && $network_wide ) {
			wp_die(
				esc_html__( 'SEOvault AI cannot be network-activated. Please activate it on each site individually.', 'seovault-ai' ),
				esc_html__( 'Network activation not supported', 'seovault-ai' ),
				array( 'back_link' => true )
			);
		}

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

		// Preserve existing connector site key if available
		self::migrate_site_key();

		// Flush rewrite rules for llms.txt and sitemap. Activation usually runs
		// after init, so register sitemap rules explicitly before flushing.
		if ( class_exists( '\SEOvaultSEO\Sitemap\Router' ) && \SEOvaultSEO\Core\Options::is_sitemap_enabled() ) {
			\SEOvaultSEO\Sitemap\Router::register();
			if ( class_exists( '\SEOvaultSEO\Sitemap\Manager' ) ) {
				\SEOvaultSEO\Sitemap\Manager::clear_rewrite_heal_flag();
			}
		}
		flush_rewrite_rules();

		// Set activation transient for notice
		set_transient( 'seovaultseo_activated', true, 5 );

		// Register Local SEO CPT and flush rewrite rules.
		if ( class_exists( '\SEOvaultSEO\LocalSEO\PostType' ) ) {
			\SEOvaultSEO\LocalSEO\PostType::register_post_type();
			\SEOvaultSEO\LocalSEO\PostType::register_taxonomy();
		}

		// Create 404 monitor database table
		\SEOvaultSEO\Monitor404\Db::create_table();

		// Create redirect manager database table
		\SEOvaultSEO\RedirectManager\RedirectDb::create_table();

		// Create API audit log database table
		\SEOvaultSEO\Api\AuditLog::install_table();

		// NotFound (404 fallback / recovery) uses Options only — no custom tables.

		// Record plugin version so Upgrade::maybe_upgrade() no-ops until the next release.
		if ( defined( 'SEOVAULT_SEO_VERSION' ) ) {
			update_option( Upgrade::VERSION_OPTION, SEOVAULT_SEO_VERSION, false );
		}

		// Set redirect flag for onboarding/dashboard redirect
		update_option( 'seovaultseo_redirect_on_activation', 'yes', false );

		// Record installation timestamp for review notice eligibility
		if ( ! get_option( 'seovaultseo_installed_at' ) ) {
			add_option( 'seovaultseo_installed_at', time(), '', false );
		}

		// P7-010: ensure runtime options are not autoloaded (also covers existing installs on re-activate).
		self::maybe_disable_option_autoload();
	}

	/**
	 * Plugin deactivation
	 */
	public static function deactivate() {
		// CRON-001 / CRON-002: clear all sitemap rebuild events (recurring + single).
		if ( class_exists( '\SEOvaultSEO\Sitemap\Scheduler' ) ) {
			\SEOvaultSEO\Sitemap\Scheduler::unschedule();
		}

		// Flush rewrite rules to remove llms.txt rules
		flush_rewrite_rules();
	}

	/**
	 * One-time: force autoload=no for plugin options that may have been created with yes.
	 *
	 * WordPress < 6.6 ignores the $autoload arg on update_option for existing rows, so a
	 * direct options-table update is required for already-installed sites.
	 *
	 * @return void
	 */
	public static function maybe_disable_option_autoload() {
		if ( '1' === (string) get_option( 'seovaultseo_autoload_p7_010_done', '' ) ) {
			return;
		}

		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time migration; clears alloptions cache below.
		$wpdb->query(
			"UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name LIKE 'seovaultseo\_%' AND autoload NOT IN ('no', 'off', 'auto-off')"
		);

		wp_cache_delete( 'alloptions', 'options' );
		wp_cache_delete( 'notoptions', 'options' );
		add_option( 'seovaultseo_autoload_p7_010_done', '1', '', false );
	}

	/**
	 * Set default plugin options
	 */
	private static function set_default_options() {
		$defaults = array(
			'seovaultseo_output_mode'                 => 'auto',
			'seovaultseo_home_title'                  => '',
			'seovaultseo_home_description'            => '',
			'seovaultseo_title_template'              => '',
			'seovaultseo_description_template'        => '',
			'seovaultseo_default_social_image'        => '',
			'seovaultseo_default_author'              => 0,
			'seovaultseo_default_category'            => 0,
			'seovaultseo_connection_verified'         => 'no',
			'seovaultseo_llms_enabled'                => 'no',
			'seovaultseo_robots_policy'               => '',
			'seovaultseo_robots_custom_content'       => '',
			'seovaultseo_local_settings'              => array(
				'enabled'        => '',
				'unit_system'    => 'METRIC',
				'sl_num_results' => 10,
			),
			// Autopilot defaults.
			'seovaultseo_autopilot_enabled'           => 'yes',
			'seovaultseo_search_noindex'              => 'yes',
			'seovaultseo_date_archives_noindex'       => 'yes',
			'seovaultseo_attachment_noindex'          => 'yes',
			'seovaultseo_post_format_noindex'         => 'yes',
			'seovaultseo_empty_archives_noindex'      => 'yes',
			'seovaultseo_advanced_query_protection'   => 'yes',
			'seovaultseo_robots_max_snippet'          => -1,
			'seovaultseo_robots_max_image_preview'    => 'large',
			'seovaultseo_robots_max_video_preview'    => -1,
			'seovaultseo_og_enabled'                  => 'yes',
			'seovaultseo_twitter_enabled'             => 'yes',
			'seovaultseo_schema_enabled'              => 'yes',
			'seovaultseo_exclude_noindex_from_search' => 'yes',
			'seovaultseo_erase_on_uninstall'          => 'no',
		);

		foreach ( $defaults as $key => $value ) {
			if ( false === get_option( $key ) ) {
				add_option( $key, $value, '', false );
			}
		}

		// Schema Architecture V2: version + identity defaults; do not seed schemas catalogue.
		if ( class_exists( '\SEOvaultSEO\Schema\SchemaArchitectureSettings' ) ) {
			\SEOvaultSEO\Schema\SchemaArchitectureSettings::install_fresh_defaults();
		}
	}

	/**
	 * Migrate site key from existing connector if available
	 */
	private static function migrate_site_key() {
		// Check if old connector site key exists
		$old_key = get_option( 'seovaultai_site_key', '' );

		if ( ! empty( $old_key ) && ! get_option( 'seovaultseo_site_key' ) ) {
			// Preserve the existing site key
			add_option( 'seovaultseo_site_key', $old_key, '', false );

			// Preserve connection status
			$connected_at = get_option( 'seovaultai_connected_at', '' );
			if ( ! empty( $connected_at ) ) {
				update_option( 'seovaultseo_connected_at', $connected_at, false );
			}

			$verified = get_option( 'seovaultai_connection_verified', 'no' );
			update_option( 'seovaultseo_connection_verified', $verified, false );
		} elseif ( ! get_option( 'seovaultseo_site_key' ) ) {
			// Generate new site key if none exists
			$new_key = wp_generate_password( 40, false );
			add_option( 'seovaultseo_site_key', $new_key, '', false );
		}
	}
}
