<?php

/**
 * WPML Integration
 *
 * Registers badge text strings with WPML String Translation and applies
 * translations at render time. All methods are no-ops when WPML is inactive.
 *
 * @package    custom-product-badge-for-woocommerce
 * @subpackage App\Multilingual
 * @since      1.3.1
 */

namespace CPBW\App\Multilingual;

class Wpml {

    /**
     * WPML String Translation context — matches the plugin text domain.
     */
    const CONTEXT = 'custom-product-badge-for-woocommerce';

    /**
     * Whether WPML core + String Translation are both active.
     *
     * @return bool
     */
    public static function is_active() {
        return defined( 'ICL_SITEPRESS_VERSION' ) && function_exists( 'icl_register_string' );
    }

    /**
     * Boot: register existing badge strings once WPML is ready.
     * Skips entirely when WPML is not active.
     *
     * @return void
     */
    public static function init() {
        if ( ! self::is_active() ) {
            return;
        }

        add_action( 'init', [ __CLASS__, 'register_all_badge_strings' ], 20 );
    }

    /**
     * Register every badge's visible text string with WPML.
     *
     * @return void
     */
    public static function register_all_badge_strings() {
        global $wpdb;

        $table  = $wpdb->prefix . 'cpbw_badges';
        $badges = $wpdb->get_results( "SELECT id, badge_settings FROM {$table}", ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        if ( empty( $badges ) ) {
            return;
        }

        foreach ( $badges as $badge ) {
            self::register_badge_strings( $badge );
        }
    }

    /**
     * Register a single badge's text string with WPML.
     *
     * @param array $badge Row from the DB: needs at least id and badge_settings.
     * @return void
     */
    public static function register_badge_strings( $badge ) {
        if ( empty( $badge['id'] ) ) {
            return;
        }

        $text = self::get_badge_text( $badge );

        if ( empty( $text ) ) {
            return;
        }

        icl_register_string( self::CONTEXT, 'badge_text_' . (int) $badge['id'], $text );
    }

    /**
     * Return badge_style with the translated text substituted in.
     *
     * Returns the original badge_style unchanged when WPML is inactive or
     * no translation exists for the current language.
     *
     * @param array $badge_config Badge row from BadgeHelper::get_badges_for_apply().
     * @return string Badge HTML ready for output.
     */
    public static function translate_badge_style( $badge_config ) {
        $badge_style = maybe_unserialize( $badge_config['badge_style'] );

        if ( ! self::is_active() || empty( $badge_config['id'] ) ) {
            return $badge_style;
        }

        $original_text = self::get_badge_text( $badge_config );

        if ( empty( $original_text ) ) {
            return $badge_style;
        }

        $translated_text = apply_filters(
            'wpml_translate_single_string',
            $original_text,
            self::CONTEXT,
            'badge_text_' . (int) $badge_config['id']
        );

        if ( $translated_text !== $original_text && ! empty( $translated_text ) ) {
            $badge_style = str_replace( $original_text, $translated_text, $badge_style );
        }

        return $badge_style;
    }

    /**
     * Extract the visible text from badge_settings['text'].
     *
     * Returns empty string for image/countdown badges that carry no text.
     *
     * @param array $badge Badge row.
     * @return string Badge text, or empty string if not available.
     */
    private static function get_badge_text( $badge ) {
        if ( empty( $badge['badge_settings'] ) ) {
            return '';
        }

        $settings = maybe_unserialize( $badge['badge_settings'] );

        if ( ! is_array( $settings ) || empty( $settings['text'] ) ) {
            return '';
        }

        return $settings['text'];
    }
}
