<?php

declare(strict_types=1);

namespace SecurWP\Core;

use SecurWP\Includes\DataDirectoryProtection;
use SecurWP\Includes\SettingsStore;
use SecurWP\Modules\Hardening\Hardening;
use WP_Site;

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Fired during plugin activation and deactivation.
 *
 * This class defines all code necessary to run during the plugin's activation and deactivation.
 *
 * @since      1.0.0
 * @package    SecurWP
 * @subpackage SecurWP/Core
 * @author     SecurWP Team <support@securewp.net>
 */
class Installer {
	private const SCHEDULED_HOOKS = [
		'securwp_daily_scan_cron',
		'securwp_weekly_report_cron',
		'securwp_telemetry_heartbeat',
		'securwp_daily_event',
		'securwp_state_push',
		'securwp_keepalive',
		'securwp_state_dispatch',
		'securwp_state_dispatch_low',
		'securwp_state_notification_dispatch',
		'securwp_state_audit_dispatch',
		'securwp_scheduled_scan_job',
		'securwp_scan_cron_check',
		'securwp_scan_worker_fallback',
		'securwp_scanner_watchdog',
		'securwp_blocklist_sync',
		'securwp_geoip_update',
		'securwp_login_attempt_cleanup',
		'securwp_rate_limit_cleanup',
		'securwp_firewall_lockout_cleanup',
		'securwp_audit_log_cleanup',
		'securwp_db_migration_runner',
		'securwp_quarantine_purge',
		'securwp_firewall_log_cleanup',
		'securwp_firewall_waf_log_ingest',
		'securwp_email_digest',
		'securwp_fw_block_digest_send',
		'securwp_webhook_retry',
		'securwp_metrics_push',
		'securwp_cf_reconcile',
		'securwp_vulnerability_refresh',
		'securwp_command_execute',
		'securwp_server_rule_reconcile',
		'securwp_server_rule_maintenance',
		'securwp_server_rule_verify',
		'securwp_user_nicename_remediation',
	];
    public static function ensure_runtime_directories(): void {
        self::create_data_directory();
    }

    public static function ensure_file_states_table_schema(): void {
        self::create_file_states_table();
    }

    public static function ensure_two_factor_table_schema(): void {
        self::create_two_factor_table();
    }

    public static function ensure_two_factor_recovery_codes_table_schema(): void {
        self::create_two_factor_recovery_codes_table();
    }

    public static function ensure_two_factor_sessions_table_schema(): void {
        self::create_two_factor_sessions_table();
    }

    public static function ensure_audit_table_schema(): void {
        self::create_audit_table();
    }

    public static function ensure_login_attempts_table_schema(): void {
        self::create_login_attempts_table();
    }

    public static function ensure_firewall_events_table_schema(): void {
        self::create_firewall_events_table();
    }

    public static function ensure_command_queue_table_schema(): void {
        \SecurWP\Modules\Cloud\Services\CommandQueue::ensure_table();
    }

	/**
	 * Return every plugin-owned scheduled hook that may exist in WP-Cron or Action Scheduler.
	 *
	 * @return array<int,string>
	 */
	public static function scheduled_hooks(): array {
		return self::SCHEDULED_HOOKS;
	}

	/**
	 * Remove a scheduled hook from both WP-Cron and Action Scheduler, including argument variants.
	 */
	public static function clear_scheduled_hook_everywhere( string $hook ): void {
		wp_clear_scheduled_hook( $hook );

		if ( function_exists( '_get_cron_array' ) ) {
			$crons = _get_cron_array();
			if ( is_array( $crons ) ) {
				foreach ( $crons as $timestamp => $cron_hooks ) {
					if ( ! isset( $cron_hooks[ $hook ] ) || ! is_array( $cron_hooks[ $hook ] ) ) {
						continue;
					}

					foreach ( $cron_hooks[ $hook ] as $event ) {
						$args = [];
						if ( is_array( $event ) && isset( $event['args'] ) && is_array( $event['args'] ) ) {
							$args = $event['args'];
						}

						wp_unschedule_event( (int) $timestamp, $hook, $args );
					}
				}
			}
		}

		if ( function_exists( 'as_unschedule_all_actions' ) ) {
			as_unschedule_all_actions( $hook );
		}
	}

	/**
	 * Activation hook.
	 *
	 * Code to run on plugin activation.
	 * This is typically used to set up default options, create database tables,
	 * schedule cron jobs, etc.
	 *
	 * @since    1.0.0
	 */
	public static function activate( bool $network_wide = false ): void {
		if ( is_multisite() && $network_wide ) {
			self::provision_network_sites();
			return;
		}

		self::provision_current_site( 'activation' );
	}

	/**
	 * Provision plugin storage for a newly created multisite site.
	 *
	 * @param WP_Site             $new_site New site instance.
	 * @param array<string,mixed> $args     Site initialization arguments.
	 */
	public static function initialize_new_site( WP_Site $new_site, array $args = [] ): void {
		unset( $args );

		if ( ! is_multisite() ) {
			return;
		}

		$blog_id = isset( $new_site->blog_id ) ? (int) $new_site->blog_id : 0;
		if ( $blog_id <= 0 ) {
			return;
		}

		self::provision_site( $blog_id, 'site_init' );
	}

    /**
     * Persist the canonical hardening baseline so default security posture is
     * explicit even before the first manual settings save.
     */
    private static function seed_hardening_defaults(): void {
        $defaults = Hardening::get_default_settings();
        $stored   = SettingsStore::get( SettingsStore::COL_HARDENING );
        $stored   = is_array( $stored ) ? $stored : [];
        $merged   = wp_parse_args( $stored, $defaults );

        if ( $merged !== $stored ) {
            SettingsStore::save( SettingsStore::COL_HARDENING, $merged );
        }
    }

	private static function cleanup_dead_legacy_options(): void {
		foreach ( self::DEAD_LEGACY_OPTIONS as $option ) {
			delete_option( $option );
		}
	}

	/**
	 * Deactivation hook.
	 *
	 * Code to run on plugin deactivation.
	 * This is typically used to clean up options, remove cron jobs, etc.
	 * Data removal should ideally be handled in an uninstall script.
	 *
	 * @since    1.0.0
	 */
	public static function deactivate() {
		// Fire notification before cleanup (modules are loaded via plugins_loaded).
		do_action( 'securwp_plugin_deactivating' );

		foreach ( self::scheduled_hooks() as $hook ) {
			self::clear_scheduled_hook_everywhere( $hook );
		}

		// Remove the auto_prepend_file WAF hook before the plugin is deleted.
		if ( class_exists( '\SecurWP\Modules\Firewall\ExtendedProtection\Manager' ) ) {
			\SecurWP\Modules\Firewall\ExtendedProtection\Manager::uninstall();
		}

		// Remove server config rules (.htaccess markers / nginx conf).
		\SecurWP\Includes\ServerConfigWriter::remove();

		// Flush rewrite rules
		flush_rewrite_rules();
	}

	/**
	 * Provision the current site with plugin-owned schema and default posture.
	 */
	private static function provision_current_site( string $runner ): void {
		self::ensure_runtime_directories();

		self::create_queue_table();
		self::create_task_queue_table();
		self::create_audit_table();
		self::create_scan_status_table();
		self::create_settings_table();
		self::create_request_nonces_table();

		self::create_file_states_table();
		self::create_cloud_jobs_table();
		self::create_hash_cache_table();
		self::create_file_index_table();

		self::create_issues_table();
		self::create_ignored_issues_table();
		self::create_scan_runs_table();
		self::create_issue_instances_table();
		\SecurWP\Modules\Scanner\Repository\QuarantineRepository::ensure_table();

		self::create_two_factor_table();
		self::create_two_factor_recovery_codes_table();
		self::create_two_factor_sessions_table();
		self::create_login_attempts_table();
		self::create_rate_limits_table();
		self::create_blocklist_table();
		self::ensure_command_queue_table_schema();
		self::ensure_firewall_events_table_schema();

		\SecurWP\Includes\SettingsStore::maybe_migrate();
		self::cleanup_dead_legacy_options();
		self::seed_hardening_defaults();
		\SecurWP\Modules\Firewall\Blocklist\BlocklistService::maybe_migrate_from_state();
		\SecurWP\Modules\Firewall\FirewallLogger::reset_table_state();

		\SecurWP\Core\Database\MigrationManager::sync_registry_state( $runner );

		$hardening = Hardening::get_saved_settings();
		if ( ! empty( $hardening['rename_login_url_enabled'] ) ) {
			flush_rewrite_rules();
		}
	}

	/**
	 * Provision every site on the network during network activation.
	 */
	private static function provision_network_sites(): void {
		$page = 1;

		do {
			$site_ids = get_sites(
				[
					'fields'                 => 'ids',
					'number'                 => 100,
					'paged'                  => $page,
					'update_site_cache'      => false,
					'update_site_meta_cache' => false,
				]
			);

			if ( empty( $site_ids ) ) {
				break;
			}

			foreach ( $site_ids as $site_id ) {
				self::provision_site( (int) $site_id, 'network_activation' );
			}

			$page++;
		} while ( count( $site_ids ) === 100 );
	}

	/**
	 * Provision a specific multisite blog in isolation.
	 */
	private static function provision_site( int $blog_id, string $runner ): void {
		if ( $blog_id <= 0 ) {
			return;
		}

		switch_to_blog( $blog_id );
		try {
			SettingsStore::reset_cache();
			\SecurWP\Modules\Firewall\FirewallLogger::reset_table_state();
			self::provision_current_site( $runner );
		} finally {
			SettingsStore::reset_cache();
			\SecurWP\Modules\Firewall\FirewallLogger::reset_table_state();
			restore_current_blog();
		}
	}

	/**
	 * Create the scan queue table.
	 */
	private static function create_queue_table() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'securwp_scan_queue';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id bigint(20) NOT NULL AUTO_INCREMENT,
			job_id varchar(64) NOT NULL,
			scan_type varchar(50) NOT NULL,
			source varchar(20) DEFAULT 'local',
			status varchar(20) NOT NULL,
			processed_count int(11) DEFAULT 0,
			total_count int(11) DEFAULT 0,
			cloud_stats longtext DEFAULT NULL,
			component_status longtext DEFAULT NULL,
			token_bucket_tokens int(10) UNSIGNED DEFAULT 20,
			cloud_error_count int(10) UNSIGNED DEFAULT 0,
			malware_signature_version varchar(20) DEFAULT NULL COMMENT 'Current signature version for this scan',
			next_run_at int(11) DEFAULT 0,
			last_dispatch_at int(11) DEFAULT 0,
			task_runner_lease_token varchar(64) DEFAULT '',
			task_runner_lease_until int(11) NOT NULL DEFAULT 0,
			last_ping int(11) DEFAULT 0,
			created_at int(11) NOT NULL,
			updated_at int(11) NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY job_id (job_id),
			KEY status (status),
			KEY created_at (created_at)
		) $charset_collate;";

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

	/**
	 * Create the durable scanner task queue table.
	 */
	private static function create_task_queue_table() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'securwp_task_queue';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			scan_id varchar(64) NOT NULL,
			task_type varchar(40) NOT NULL,
			status varchar(20) NOT NULL DEFAULT 'pending',
			payload longtext DEFAULT NULL,
			result longtext DEFAULT NULL,
			available_at int(11) NOT NULL DEFAULT 0,
			lease_until int(11) NOT NULL DEFAULT 0,
			attempts tinyint unsigned NOT NULL DEFAULT 0,
			max_attempts tinyint unsigned NOT NULL DEFAULT 5,
			priority tinyint unsigned NOT NULL DEFAULT 100,
			created_at int(11) NOT NULL,
			updated_at int(11) NOT NULL,
			dedupe_key varchar(64) DEFAULT NULL,
			PRIMARY KEY  (id),
			KEY idx_claim (scan_id, status, available_at, priority),
			KEY idx_scan_type (scan_id, task_type, status),
			KEY idx_lease (status, lease_until),
			UNIQUE KEY idx_dedupe (scan_id, dedupe_key)
		) $charset_collate;";

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

    /**
     * Create the audit log table.
     */
    private static function create_audit_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_audit_log';
        $charset_collate = $wpdb->get_charset_collate();

        // Production-ready: Indexed by user, event, time
        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            event varchar(50) NOT NULL,
            message text NOT NULL,
            user_id bigint(20) NOT NULL DEFAULT 0,
            ip_address varchar(45) NOT NULL DEFAULT '',
            level varchar(20) NOT NULL DEFAULT 'info',
            category varchar(32) NOT NULL DEFAULT 'general',
            meta longtext NOT NULL,
            created_at int(11) DEFAULT 0 NOT NULL,
            PRIMARY KEY  (id),
            KEY event (event),
            KEY user_id (user_id),
            KEY created_at (created_at),
            KEY category (category)
        ) $charset_collate;";

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

    /**
     * Create file_states table for FSM-based scanner (v2.1).
     *
     * This table is EPHEMERAL - stores state for the current scan only.
     * Permanent cache lives in the signed hash cache table.
     */
    private static function create_file_states_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_file_states';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            scan_id varchar(64) NOT NULL COMMENT 'scan_xxx UUID from scan_queue',
            file_path varchar(512) NOT NULL COMMENT 'Relative path from ABSPATH',
            file_hash varchar(64) DEFAULT NULL COMMENT 'SHA-256 hash',
            file_size bigint(20) UNSIGNED DEFAULT NULL,
            state varchar(32) NOT NULL DEFAULT 'discovered',
            file_type varchar(32) NOT NULL,
            cloud_job_id varchar(64) DEFAULT NULL COMMENT 'Intel Engine job ID',
            upload_attempt int(10) UNSIGNED DEFAULT 0,
            hash_status varchar(32) DEFAULT 'unknown' COMMENT 'Cloud hash check result',
            scanned_with_signature varchar(20) DEFAULT NULL COMMENT 'Malware signature version',
            error_code varchar(32) DEFAULT NULL,
            error_message text DEFAULT NULL,
            scan_result longtext DEFAULT NULL COMMENT 'Serialized scan result payload (optional)',
            skip_reason varchar(50) DEFAULT NULL COMMENT 'Reason file was skipped (e.g. credit_exhausted)',
            created_at int(10) UNSIGNED NOT NULL,
            updated_at int(10) UNSIGNED NOT NULL,
            PRIMARY KEY  (id),
            KEY idx_scan_id (scan_id),
            KEY idx_state (state),
            KEY idx_scan_state_created (scan_id, state, created_at),
            KEY idx_scan_created (scan_id, created_at),
            KEY idx_file_path (file_path(191)),
            KEY idx_file_hash (file_hash),
            KEY idx_cloud_job (cloud_job_id),
            KEY idx_hash_status (hash_status),
            KEY idx_signature (scanned_with_signature),
            UNIQUE KEY uk_scan_file (scan_id, file_path(191))
        ) $charset_collate;";

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

	/**
	 * Create scan settings table for scanner configuration.
	 */
	private static function create_settings_table() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'securwp_settings';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id bigint(20) NOT NULL AUTO_INCREMENT,
			settings longtext NOT NULL,
			cloud_settings longtext NULL,
			firewall longtext NULL,
			hardening longtext NULL,
			global_settings longtext NULL,
			twofa longtext NULL,
			headers longtext NULL,
			notifications longtext NULL,
			cloudflare longtext NULL,
			branding longtext NULL,
			state longtext NULL,
			created_at int(11) NOT NULL,
			updated_at int(11) NOT NULL,
			PRIMARY KEY (id)
		) $charset_collate;";

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

	/**
	 * Create request nonce table for inbound C2 replay protection.
	 */
	private static function create_request_nonces_table() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'securwp_request_nonces';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			site_token varchar(128) NOT NULL,
			nonce varchar(128) NOT NULL,
			request_id varchar(128) NOT NULL,
			created_at int(10) unsigned NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY uk_site_nonce (site_token, nonce),
			UNIQUE KEY uk_site_request (site_token, request_id),
			KEY idx_created (created_at)
		) $charset_collate;";

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


    /**
     * Create cloud_jobs table for tracking Intel Engine scan jobs (v2.1).
     */
    private static function create_cloud_jobs_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_cloud_jobs';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            job_id varchar(64) NOT NULL,
            scan_id varchar(64) NOT NULL,
            status varchar(32) NOT NULL DEFAULT 'queued',
            error_message text DEFAULT NULL,
            retry_count int(10) UNSIGNED DEFAULT 0,
            max_retries int(10) UNSIGNED DEFAULT 3,
            created_at int(10) UNSIGNED NOT NULL,
            submitted_at int(10) UNSIGNED DEFAULT NULL,
            completed_at int(10) UNSIGNED DEFAULT NULL,
            timeout_at int(10) UNSIGNED DEFAULT NULL,
            last_poll_at int(10) UNSIGNED DEFAULT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY uk_job_id (job_id),
            KEY idx_scan_id (scan_id),
            KEY idx_scan_status (scan_id, status),
            KEY idx_status (status),
            KEY idx_timeout (timeout_at)
        ) $charset_collate;";

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


    /**
     * Create scan_status table for logging scan activity.
     */
    private static function create_scan_status_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_scan_status';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            scan_id varchar(64) NOT NULL,
            ctime varchar(20) NOT NULL COMMENT 'Microtime with decimal precision',
            level int(10) UNSIGNED DEFAULT 1 COMMENT '1=info, 2=warning, 3=error',
            type varchar(32) NOT NULL DEFAULT 'info',
            message text NOT NULL,
            created_at int(10) UNSIGNED DEFAULT 0 NOT NULL,
            PRIMARY KEY  (id),
            KEY idx_scan_id (scan_id),
            KEY idx_ctime (ctime),
            KEY idx_level (level)
        ) $charset_collate;";

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

    /**
     * Create minimal signed hash cache table (v2.2).
     *
     * Verdicts:
     * - verified: repo-verified content (not tied to signature version)
     * - safe: signature-verified content (invalidated on signature updates)
     */
    private static function create_hash_cache_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_hash_cache';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            file_hash varchar(64) NOT NULL COMMENT 'SHA-256 hash (hex)',
            verdict varchar(16) NOT NULL COMMENT 'verified|safe',
            last_seen_at int(10) UNSIGNED NOT NULL COMMENT 'Unix timestamp',
            proof varbinary(128) NOT NULL COMMENT 'Signed proof blob (v1)',
            PRIMARY KEY (file_hash),
            KEY idx_verdict (verdict),
            KEY idx_last_seen (last_seen_at)
        ) $charset_collate;";

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

    /**
     * Create the two-factor authentication table.
     */
    private static function create_two_factor_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_two_factor';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            user_id bigint(20) UNSIGNED NOT NULL,
            totp_secret text DEFAULT NULL,
            setup_email_code_hash varchar(255) DEFAULT NULL,
            setup_email_attempts int(10) UNSIGNED NOT NULL DEFAULT 0,
            setup_email_sent_at int(10) UNSIGNED DEFAULT NULL,
            setup_email_delivered tinyint(1) NOT NULL DEFAULT 0,
            method varchar(10) NOT NULL DEFAULT 'totp',
            is_enabled tinyint(1) NOT NULL DEFAULT 0,
            confirmed_at int(10) UNSIGNED DEFAULT NULL,
            last_used_at int(10) UNSIGNED DEFAULT NULL,
            remember_token varchar(64) DEFAULT NULL,
            remember_expires int(10) UNSIGNED DEFAULT NULL,
            created_at int(10) UNSIGNED NOT NULL,
            updated_at int(10) UNSIGNED NOT NULL,
            PRIMARY KEY (user_id)
        ) $charset_collate;";

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

    /**
     * Create the hashed recovery-code table for 2FA.
     */
    private static function create_two_factor_recovery_codes_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_two_factor_recovery_codes';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id bigint(20) UNSIGNED NOT NULL,
            code_hash varchar(255) NOT NULL,
            batch_id varchar(36) NOT NULL,
            created_at int(10) UNSIGNED NOT NULL,
            used_at int(10) UNSIGNED DEFAULT NULL,
            PRIMARY KEY (id),
            KEY idx_user_active (user_id, used_at),
            KEY idx_batch_id (batch_id)
        ) $charset_collate;";

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

    /**
     * Create the DB-backed pre-auth 2FA session table.
     */
    private static function create_two_factor_sessions_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_two_factor_sessions';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            token_hash varchar(64) NOT NULL,
            user_id bigint(20) UNSIGNED NOT NULL,
            method varchar(12) NOT NULL,
            notice_code varchar(40) NOT NULL DEFAULT '',
            redirect_to text DEFAULT NULL,
            remember tinyint(1) NOT NULL DEFAULT 0,
            fail_count int(10) UNSIGNED NOT NULL DEFAULT 0,
            email_code_hash varchar(255) DEFAULT NULL,
            email_attempts int(10) UNSIGNED NOT NULL DEFAULT 0,
            email_sent_at int(10) UNSIGNED DEFAULT NULL,
            email_delivered tinyint(1) NOT NULL DEFAULT 0,
            expires_at int(10) UNSIGNED NOT NULL,
            created_at int(10) UNSIGNED NOT NULL,
            updated_at int(10) UNSIGNED NOT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY uk_token_hash (token_hash),
            KEY idx_expires_at (expires_at),
            KEY idx_user_id (user_id)
        ) $charset_collate;";

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

    /**
     * Create the login attempt counter table.
     *
     * Keeps failed-login counters in a plugin-owned table so lockout logic
     * remains correct on hosts that use persistent object caches.
     */
    private static function create_login_attempts_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_login_attempts';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            subject_type varchar(10) NOT NULL,
            subject_hash varchar(64) NOT NULL,
            first_attempt_at int(10) UNSIGNED NOT NULL,
            last_attempt_at int(10) UNSIGNED NOT NULL,
            attempt_count int(10) UNSIGNED NOT NULL DEFAULT 1,
            expires_at int(10) UNSIGNED NOT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY uk_subject (subject_type, subject_hash),
            KEY idx_expires_at (expires_at),
            KEY idx_last_attempt_at (last_attempt_at)
        ) $charset_collate;";

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

    /**
     * Create the rate limits table for sliding window counters.
     */
    private static function create_rate_limits_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_rate_limits';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            ip_hash varchar(64) NOT NULL,
            hit_type varchar(20) NOT NULL,
            minute_bucket int(10) UNSIGNED NOT NULL,
            hits int(10) UNSIGNED NOT NULL DEFAULT 1,
            PRIMARY KEY (id),
            UNIQUE KEY uk_ip_type_minute (ip_hash, hit_type, minute_bucket),
            KEY idx_bucket (minute_bucket)
        ) $charset_collate;";

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

    /**
     * Create the community blocklist table for indexed IP lookups.
     */
    private static function create_blocklist_table() {
        global $wpdb;

        $table_name      = $wpdb->prefix . 'securwp_blocklist';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            host varchar(45) NOT NULL,
            type varchar(10) NOT NULL DEFAULT 'ip',
            source varchar(20) NOT NULL DEFAULT 'cloud',
            created_at int(10) UNSIGNED NOT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY uk_host (host),
            KEY idx_type (type),
            KEY idx_source (source)
        ) $charset_collate;";

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

    /**
     * Create the firewall events log table.
     *
     * Records every blocked request with full context for dashboard analytics,
     * live traffic feed, and security auditing. Provisioned during activation,
     * site initialization, and database migrations.
     */
    public static function create_firewall_events_table(): void {
        global $wpdb;

        $table           = $wpdb->prefix . 'securwp_firewall_events';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            event_time int(11) unsigned NOT NULL,
            ip_address varchar(45) NOT NULL DEFAULT '',
            request_uri varchar(500) NOT NULL DEFAULT '',
            http_method varchar(10) NOT NULL DEFAULT '',
            http_status smallint(5) unsigned NOT NULL DEFAULT 403,
            attack_type varchar(100) NOT NULL DEFAULT '',
            user_agent varchar(500) NOT NULL DEFAULT '',
            user_id bigint(20) unsigned NOT NULL DEFAULT 0,
            blog_id bigint(20) unsigned NOT NULL DEFAULT 1,
            PRIMARY KEY  (id),
            KEY idx_event_time (event_time),
            KEY idx_ip_address (ip_address(20)),
            KEY idx_attack_type (attack_type(20)),
            KEY idx_ip_time (ip_address(20), event_time),
            KEY idx_blog_time (blog_id, event_time)
        ) $charset_collate;";

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

    /**
     * Create the data directory for WAF config, GeoIP database, etc.
     */
    private static function create_data_directory() {
        $data_dir = DataDirectoryProtection::get_data_dir_path();
        DataDirectoryProtection::ensure_local_protection( $data_dir );

        // Create GeoIP subdirectory
        $geoip_dir = $data_dir . '/geoip';
        DataDirectoryProtection::ensure_local_protection( $geoip_dir );

        // Create audit logs subdirectory
        $logs_dir = $data_dir . '/logs';
        DataDirectoryProtection::ensure_local_protection( $logs_dir );

        // Create scan logs subdirectory
        $scan_logs_dir = $data_dir . '/scan-logs';
        DataDirectoryProtection::ensure_local_protection( $scan_logs_dir );

        // Create quarantine subdirectory
        $quarantine_dir = $data_dir . '/quarantine';
        DataDirectoryProtection::ensure_local_protection( $quarantine_dir );

        self::cleanup_retired_firewall_directory( $data_dir . '/firewall' );
    }

    /**
     * Remove the deprecated cloud firewall rules directory when it only
     * contains boilerplate protection files from older versions.
     */
    private static function cleanup_retired_firewall_directory( string $firewall_dir ): void {
        if ( ! is_dir( $firewall_dir ) ) {
            return;
        }

        $entries = @scandir( $firewall_dir );
        if ( ! is_array( $entries ) ) {
            return;
        }

        $entries = array_values(
            array_diff(
                $entries,
                [ '.', '..', '.htaccess', 'index.php' ]
            )
        );

        if ( ! empty( $entries ) ) {
            return;
        }

        $htaccess = trailingslashit( $firewall_dir ) . '.htaccess';
        $index    = trailingslashit( $firewall_dir ) . 'index.php';

        if ( is_file( $htaccess ) ) {
            wp_delete_file( $htaccess );
        }

        if ( is_file( $index ) ) {
            wp_delete_file( $index );
        }

        @rmdir( $firewall_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
    }

    /**
     * Create file index table for persistent enumeration (v2.5).
     */
    private static function create_file_index_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_file_index';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            scan_id varchar(64) NOT NULL,
            stack longtext DEFAULT NULL,
            total_files int(10) UNSIGNED NOT NULL DEFAULT 0,
            is_complete tinyint(1) NOT NULL DEFAULT 0,
            created_at int(10) UNSIGNED NOT NULL,
            updated_at int(10) UNSIGNED NOT NULL,
            PRIMARY KEY  (scan_id),
            KEY idx_complete (is_complete),
            KEY idx_updated (updated_at)
        ) $charset_collate;";

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

    /**
     * Create issues table for scanner findings (v2.3).
     */
    private static function create_issues_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_issues';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            issue_hash varchar(64) NOT NULL,
            scan_id varchar(64) DEFAULT NULL,
            type varchar(50) NOT NULL,
            severity varchar(20) DEFAULT 'medium',
            status varchar(50) NOT NULL,
            file_path text DEFAULT NULL,
            message text DEFAULT NULL,
            data longtext DEFAULT NULL,
            is_ignored tinyint(1) DEFAULT 0,
            resolved_at int(11) NOT NULL DEFAULT 0,
            first_seen_at int(11) NOT NULL DEFAULT 0,
            last_seen_at int(11) NOT NULL DEFAULT 0,
            created_at int(11) NOT NULL,
            updated_at int(11) NOT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY issue_hash (issue_hash),
            KEY scan_id (scan_id),
            KEY type (type),
            KEY is_ignored (is_ignored),
            KEY idx_active (is_ignored, resolved_at)
        ) $charset_collate;";

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

    /**
     * Create ignored issues table (v2.3).
     */
    private static function create_ignored_issues_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_ignored_issues';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            issue_hash varchar(64) NOT NULL,
            ignored_at int(11) NOT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY issue_hash (issue_hash)
        ) $charset_collate;";

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

    /**
     * Create scan runs table for immutable execution history (v2.3).
     */
    private static function create_scan_runs_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_scan_runs';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            scan_id varchar(64) NOT NULL,
            config longtext DEFAULT NULL,
            component_status longtext DEFAULT NULL,
            started_at int(11) NOT NULL,
            finished_at int(11) DEFAULT 0,
            PRIMARY KEY  (id),
            UNIQUE KEY scan_id (scan_id)
        ) $charset_collate;";

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

    /**
     * Create issue instances table for staging and occurrence history (v2.3).
     */
    private static function create_issue_instances_table() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'securwp_issue_instances';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            issue_hash varchar(64) NOT NULL,
            scan_run_id varchar(64) NOT NULL,
            type varchar(50) DEFAULT NULL,
            severity varchar(20) DEFAULT NULL,
            status varchar(50) DEFAULT NULL,
            file_path text DEFAULT NULL,
            message text DEFAULT NULL,
            evidence longtext DEFAULT NULL,
            created_at int(11) NOT NULL,
            PRIMARY KEY  (id),
            KEY issue_ref (issue_hash, scan_run_id)
        ) $charset_collate;";

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

}
