<?php
/**
 * One-time migration: set autoload=off for plugin options that were saved with autoload on.
 *
 * Reduces payload and time for {@see wp_load_alloptions()} (core query on every request).
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

/**
 * Migrates legacy autoload flags for WP PowerSuite-owned options.
 */
final class OptionAutoloadMigration {

	private const FLAG_OPTION = 'wp_powersuite_autoload_fix_v1';

	/**
	 * Run once on init when the flag is not set.
	 */
	public static function maybe_run(): void {
		if ( wp_installing() ) {
			return;
		}
		if ( get_option( self::FLAG_OPTION, '' ) === '1' ) {
			return;
		}

		self::run();
	}

	/**
	 * Set autoload=off for plugin-owned options in the current site's options table.
	 *
	 * Safe to call from activation; skips work when already completed.
	 */
	public static function run(): void {
		if ( get_option( self::FLAG_OPTION, '' ) === '1' ) {
			return;
		}

		global $wpdb;
		$names = self::option_names();
		if ( $names === [] ) {
			update_option( self::FLAG_OPTION, '1', false );
			return;
		}

		$in = implode( ',', array_fill( 0, count( $names ), '%s' ) );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- placeholders match $names count
		$sql = "UPDATE {$wpdb->options} SET autoload = 'no' WHERE autoload IN ('yes','on','auto-on','auto') AND option_name IN ({$in})";
		$wpdb->query( $wpdb->prepare( $sql, ...$names ) );

		wp_cache_delete( 'alloptions', 'options' );
		update_option( self::FLAG_OPTION, '1', false );
	}

	/**
	 * @return list<string>
	 */
	private static function option_names(): array {
		$names = [
			'wp_powersuite_settings',
			'wp_powersuite_opb_pages',
			'wp_powersuite_coming_soon_maintenance_subscribers',
			'wpps_code_snippet_settings',
			'wpps_cs_error_logging',
			'wpps_redirects_db_version',
			'wpps_forms_rewrite_flushed',
			'tl_secret_key',
			'wp_powersuite_admin_menu_organizer_config',
			'wp_powersuite_delete_on_uninstall',
			'wp_powersuite_deactivation_feedback',
			'wp_powersuite_deactivation_feedback_log',
			'wp_powersuite_lic_email',
			'wp_powersuite_license_status',
			'WPPowerSuitePremium_lic_Key',
			'WPPowerSuitePremium_lic_email',
		];

		if ( class_exists( 'W_P_Power_Suite_Premium_Base', false ) ) {
			foreach ( [ 'wp_powersuite_lic_key', 'WPPowerSuitePremium_lic_Key' ] as $lic_base ) {
				$k = \W_P_Power_Suite_Premium_Base::get_lic_key_param( $lic_base );
				if ( is_string( $k ) && $k !== '' ) {
					$names[] = $k;
				}
			}
		}

		$extra = apply_filters( 'wp_powersuite_autoload_off_option_names', [] );
		if ( is_array( $extra ) && $extra !== [] ) {
			foreach ( $extra as $one ) {
				if ( is_string( $one ) && $one !== '' ) {
					$names[] = $one;
				}
			}
		}

		$names = array_values( array_unique( $names ) );
		return $names;
	}
}
