<?php
/**
 * Upgrade shims from 1.x and compat development installs.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Migration
 */
class Rsmspark_Content_Widgets_Migration {

	/**
	 * @return void
	 */
	public static function init() {
		if ( ! class_exists( 'Rsmspark_Migration', false ) ) {
			// Still register upgrade hook when suite migration shim is absent.
		} else {
			Rsmspark_Migration::map_options(
				array(
					'rsmspark_content_widgets_settings'             => array(
						'rsmspark_cw_compat_settings',
						'rsmspark_content_widgets_options',
						'rsmspark_cw_settings',
					),
					'rsmspark_content_widgets_license_data'         => array(
						'rsmspark_cw_license_data',
						'rsmspark_cw_compat_license_data',
						'rsmspark_content_widgets_license_data_legacy',
					),
					'rsmspark_content_widgets_license_validated_at' => array(
						'rsmspark_cw_license_validated_at',
						'rsmspark_cw_compat_license_validated_at',
					),
					'rsmspark_content_widgets_license_last_result'  => array(
						'rsmspark_cw_license_last_result',
						'rsmspark_cw_compat_license_last_result',
					),
				)
			);

			Rsmspark_Migration::map_admin_pages(
				array(
					'rsmspark-content-widgets-compat' => 'admin.php?page=' . RSMSPARK_CONTENT_WIDGETS_SLUG,
				)
			);
		}

		add_action( 'init', array( __CLASS__, 'maybe_upgrade' ), 25 );
	}

	/**
	 * One-time activation tasks.
	 *
	 * @return void
	 */
	public static function run_activation() {
		self::init();

		if ( class_exists( 'Rsmspark_Migration', false ) ) {
			Rsmspark_Migration::migrate_options();
		}

		if ( class_exists( 'Rsmspark_Content_Widgets_Settings', false ) ) {
			Rsmspark_Content_Widgets_Settings::merge_registry_widgets();
		}

		update_option( 'rsmspark_content_widgets_version', RSMSPARK_CONTENT_WIDGETS_VERSION, false );
	}

	/**
	 * Run incremental upgrades when the plugin version changes.
	 *
	 * @return void
	 */
	public static function maybe_upgrade() {
		$stored_version = (string) get_option( 'rsmspark_content_widgets_version', '' );

		if ( '' !== $stored_version && version_compare( $stored_version, RSMSPARK_CONTENT_WIDGETS_VERSION, '>=' ) ) {
			return;
		}

		if ( class_exists( 'Rsmspark_Content_Widgets_Settings', false ) ) {
			Rsmspark_Content_Widgets_Settings::merge_registry_widgets();
		}

		update_option( 'rsmspark_content_widgets_version', RSMSPARK_CONTENT_WIDGETS_VERSION, false );
	}
}
