<?php
/**
 * Upgrades Handler.
 *
 * @author     ThemeFusion
 * @copyright  (c) Copyright by ThemeFusion
 * @link       https://avada.com
 * @package    Avada
 * @subpackage Core
 */

// Do not allow directly accessing this file.
if ( ! defined( 'ABSPATH' ) ) {
	exit( 'Direct script access denied.' );
}

/**
 * Handle migrations for Avada 7.15.6
 *
 * @since 7.15.6
 */
class Avada_Upgrade_7156 extends Avada_Upgrade_Abstract {

	/**
	 * The version.
	 *
	 * @access protected
	 * @since 7.15.6
	 * @var string
	 */
	protected $version = '7.15.6';

	/**
	 * An array of all available languages.
	 *
	 * @static
	 * @access private
	 * @since 7.15.6
	 * @var array
	 */
	private static $available_languages = [];

	/**
	 * The actual migration process.
	 *
	 * @access protected
	 * @since 7.15.6
	 * @return void
	 */
	protected function migration_process() {
		$available_languages       = Fusion_Multilingual::get_available_languages();
		self::$available_languages = ( ! empty( $available_languages ) ) ? $available_languages : [ '' ];

		$this->migrate_options();
	}

	/**
	 * Migrate options.
	 *
	 * @since 7.15.6
	 * @access protected
	 */
	protected function migrate_options() {
		$available_langs = self::$available_languages;

		$options = get_option( $this->option_name, [] );
		$options = $this->migrate_bar_button_action( $options );

		update_option( $this->option_name, $options );

		foreach ( $available_langs as $language ) {

			// Skip langs that are already done.
			if ( '' === $language ) {
				continue;
			}

			$options = get_option( $this->option_name . '_' . $language, [] );
			$options = $this->migrate_bar_button_action( $options );

			update_option( $this->option_name . '_' . $language, $options );
		}
	}

	/**
	 * Migrate the legacy "Privacy Bar Button Save On Click" switch into the new
	 * "Privacy Bar Primary Button Action" radio-button-set.
	 *
	 * Legacy switch values:
	 *   '0' / unset → button dismisses the collapsed bar  → 'dismiss'
	 *   '1'         → button saves the pre-selected types → 'save'
	 *
	 * @access private
	 * @since 7.15.6
	 * @param array $options The Global Options array.
	 * @return array         The updated Global Options array.
	 */
	private function migrate_bar_button_action( $options ) {

		// Only migrate a legacy switch value; leave new values untouched.
		if ( ! isset( $options['privacy_bar_button_save'] ) ) {
			return $options;
		}

		$value = $options['privacy_bar_button_save'];

		// Already migrated to one of the new string values.
		if ( in_array( $value, [ 'dismiss', 'save', 'contextual' ], true ) ) {
			return $options;
		}

		$options['privacy_bar_button_save'] = ( '1' === (string) $value ) ? 'save' : 'dismiss';

		return $options;
	}
}
