<?php
/**
 * One-time copy of options from legacy `cf_` or `mccollab_` keys to `multicollab_` keys.
 *
 * @package commenting-feature
 */

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

/**
 * Migrates options from cf_* and mccollab_* to multicollab_*.
 *
 * @return void
 */
function multicollab_migrate_legacy_option_keys() {
	if ( get_option( 'multicollab_legacy_options_migrated_532', '' ) === '1' ) {
		return;
	}

	global $wpdb;

	$suffixes = array(
		'permissions',
		'admin_notif',
		'hide_editorial_column',
		'hide_floating_icons',
		'show_multicollab_sidebar',
		'give_alert_message',
		'show_infoboard',
		'welcome_dashboard_completed_tour',
		'opt_in',
	);

	foreach ( $suffixes as $suffix ) {
		$new_key = 'multicollab_' . $suffix;
		$exists  = $wpdb->get_var( $wpdb->prepare( "SELECT option_id FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $new_key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
		if ( $exists ) {
			continue;
		}
		foreach ( array( 'mccollab_' . $suffix, 'cf_' . $suffix ) as $old_key ) {
			$row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value, autoload FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $old_key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
			if ( $row ) {
				add_option( $new_key, maybe_unserialize( $row->option_value ), '', $row->autoload );
				break;
			}
		}
	}

	// Only clear legacy hook names; do not clear multicollab_* so active schedules are preserved.
	wp_clear_scheduled_hook( 'cf_free_plugin_usage_data' );
	wp_clear_scheduled_hook( 'mccollab_free_plugin_usage_data' );
	wp_clear_scheduled_hook( 'cf_daily_license_checker' );
	wp_clear_scheduled_hook( 'mccollab_daily_license_checker' );

	update_option( 'multicollab_legacy_options_migrated_532', '1', false );
	// Mark older migration flag so we do not re-run the broken same-key copy.
	if ( get_option( 'multicollab_legacy_options_migrated_530', '' ) !== '1' ) {
		update_option( 'multicollab_legacy_options_migrated_530', '1', false );
	}
}

add_action( 'plugins_loaded', 'multicollab_migrate_legacy_option_keys', 5 );
