<?php
/**
 * Migration: Global Values Per-Language Scoping
 *
 * Copies the single `boostbot_appearance_global_values` wp_option to
 * per-language variants: `boostbot_appearance_global_values_he`,
 * `boostbot_appearance_global_values_en`, etc.
 *
 * Idempotent: safe to run multiple times.
 *
 * @package BoostBot
 * @since   1.3.0
 */

// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BoostBot_Migration_Global_Values_Per_Language {

	private static $flag_key = 'boostbot_migration_global_values_per_language_done';

	/**
	 * Run the migration.
	 *
	 * @return bool
	 */
	public static function run(): bool {
		if ( '' !== get_option( self::$flag_key, '' ) ) {
			return true;
		}

		$legacy_values = get_option( 'boostbot_appearance_global_values', array() );

		if ( empty( $legacy_values ) || ! is_array( $legacy_values ) ) {
			update_option( self::$flag_key, current_time( 'mysql' ) );
			return true;
		}

		$languages = self::get_active_languages();

		foreach ( $languages as $lang ) {
			$option_key = 'boostbot_appearance_global_values_' . $lang;
			$existing   = get_option( $option_key, array() );

			// Only copy if the per-language option doesn't already exist
			if ( empty( $existing ) ) {
				update_option( $option_key, $legacy_values );
				BoostBot_Logger::info( "[Migration] Copied global values to {$option_key}" );
			}
		}

		update_option( self::$flag_key, current_time( 'mysql' ) );
		BoostBot_Logger::info( '[Migration] Global values per-language migration complete for languages: ' . implode( ', ', $languages ) );

		return true;
	}

	/**
	 * Get languages from the multilingual system.
	 *
	 * Merges Language Manager enabled languages with languages actually present
	 * in bots/presets DB tables to avoid missing orphaned data.
	 *
	 * @return array List of language codes.
	 */
	private static function get_active_languages(): array {
		$languages = array();

		if ( class_exists( 'BoostBot_Language_Manager' ) && method_exists( 'BoostBot_Language_Manager', 'get_instance' ) ) {
			try {
				$manager = BoostBot_Language_Manager::get_instance();
				if ( method_exists( $manager, 'get_enabled_languages' ) ) {
					$langs = $manager->get_enabled_languages();
					if ( ! empty( $langs ) && is_array( $langs ) ) {
						$languages = $langs;
					}
				}
			} catch ( \Throwable $e ) {
				BoostBot_Logger::warning( '[Migration] Could not get active languages via manager: ' . $e->getMessage() );
			}
		}

		global $wpdb;
		try {
			$bot_langs    = $wpdb->get_col( "SELECT DISTINCT language FROM {$wpdb->prefix}boostbot_bots WHERE language IS NOT NULL AND language != ''" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$preset_langs = $wpdb->get_col( "SELECT DISTINCT language FROM {$wpdb->prefix}boostbot_appearance_presets WHERE language IS NOT NULL AND language != ''" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$db_langs     = array_unique( array_merge( $bot_langs ?: array(), $preset_langs ?: array() ) );
			$languages    = array_unique( array_merge( $languages, $db_langs ) );
		} catch ( \Throwable $e ) {
			BoostBot_Logger::warning( '[Migration] Could not query languages from DB: ' . $e->getMessage() );
		}

		if ( empty( $languages ) ) {
			return array( 'he' );
		}

		if ( ! in_array( 'he', $languages, true ) ) {
			array_unshift( $languages, 'he' );
		}

		return $languages;
	}
}
