<?php if ( ! defined( 'ABSPATH' ) ) {exit;} // Exit if accessed directly.

/**
 * Multilingual compatibility.
 */

class Codevz_Multilang {

	use Codevz_Plus_Instance;

	public function __construct() {

		// Compatibility for Polylang.
		if ( function_exists( 'pll_languages_list' ) ) { 
			add_action( 'wpml_loaded', '__return_true', 10, 0 );
			do_action( 'wpml_loaded' );
		}

		add_action( 'init', [ $this, 'register_strings_multilang' ], 20 );

	}

	public function register_strings_multilang() {

		$theme_options = get_option( 'codevz_theme_options' );
		if ( empty( $theme_options ) ) {
			return;
		}

		$this->register_recursive( $theme_options, '[codevz_theme_options]' );
	}

	public function register_recursive( $array, $prefix ) {
	    $skip_keys = [ 'css_out', 'icon_type', 'image_type', 'site_color_sec', 'site_color', 'css' ];

	    foreach ( $array as $key => $value ) {
	        if ( in_array( $key, $skip_keys, true ) ) {
	        	continue;
	        }

	        if ( is_array( $value ) ) {
	            $current_prefix = $prefix . '[' . $key . ']';
	            $this->register_recursive( $value, $current_prefix );
	        } else if ( is_string( $value ) ) {
	            $trim = trim( $value );

	            if ( $trim === '' || is_numeric( $trim ) || in_array( strtolower( $trim ), [ 'true','false' ], true ) ) {
	            	continue;
	            }
	            if ( ! preg_match( '/^\s*(float|font-family|content|icon)\s*:/i', $trim ) && strpos( $trim, ':' ) !== false && strpos( $trim, ';' ) !== false ) {
	            	continue;
	            }

	            // Final key
	            $final_key = $prefix . $key;

	            // WPML
	            if ( function_exists( 'icl_register_string' ) ) {
	                icl_register_string( 'admin_texts_codevz_theme_options', $final_key, $value );
	            }
	            // Polylang
	            if ( function_exists( 'pll_register_string' ) ) {
	                pll_register_string( $final_key, $value, 'admin_texts_codevz_theme_options' );
	            }
	        }
	    }
	}

}

Codevz_Multilang::instance();