<?php

/**
 * TranslatePress Integration
 *
 * Applies TranslatePress translations to badge HTML at render time.
 * All methods are no-ops when TranslatePress is inactive.
 *
 * TranslatePress automatically translates page-level HTML output, so
 * badges rendered directly in the page DOM (shop listing) are handled
 * without any extra work. This class handles explicit translation for
 * badge HTML that is injected via JavaScript (single product page).
 *
 * @package    custom-product-badge-for-woocommerce
 * @subpackage App\Multilingual
 * @since      1.3.1
 */

namespace CPBW\App\Multilingual;

class TranslatePress {

    /**
     * Whether TranslatePress is active.
     *
     * @return bool
     */
    public static function is_active() {
        return defined( 'TRP_PLUGIN_VERSION' );
    }

    /**
     * Boot: no hooks needed — TranslatePress translates page output automatically.
     * This method exists for consistency with the Wpml class.
     *
     * @return void
     */
    public static function init() {
        // TranslatePress processes the full page HTML output via an output buffer,
        // so badges rendered in the page DOM are translated automatically.
        // No additional hooks are required.
    }

    /**
     * Return badge_style translated for the current language via TranslatePress.
     *
     * Falls back to the original badge_style when TranslatePress is inactive
     * or its translation engine is unavailable.
     *
     * @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() ) {
            return $badge_style;
        }

        if ( ! class_exists( 'TRP_Translate_Press' ) ) {
            return $badge_style;
        }

        $trp = TRP_Translate_Press::get_trp_instance();

        if ( ! $trp ) {
            return $badge_style;
        }

        $translation_render = $trp->get_component( 'translation_render' );

        if ( ! $translation_render || ! method_exists( $translation_render, 'translate_page' ) ) {
            return $badge_style;
        }

        $translated = $translation_render->translate_page( $badge_style );

        return ! empty( $translated ) ? $translated : $badge_style;
    }
}
