<?php
if (!defined('ABSPATH')) exit;

class W5E_I18n
{
    const DOMAIN = 'woo-5e';

    public static function setup()
    {
        add_action('plugins_loaded', [__CLASS__, 'load_textdomain']);
    }

    public static function load_textdomain()
    {
        load_plugin_textdomain(
            self::DOMAIN,
            false,
            dirname(W5E_BASENAME) . '/languages'
        );
    }

    public static function register_shipping_title($title, $instance_id = 0)
    {
        if ($title === '') {
            return;
        }
        self::register_string(self::shipping_title_key($instance_id), $title);
    }

    public static function translate_shipping_title($title, $instance_id = 0)
    {
        if ($title === '') {
            return $title;
        }
        return self::translate_string($title, self::shipping_title_key($instance_id));
    }

    private static function shipping_title_key($instance_id)
    {
        $instance_id = absint($instance_id);
        return $instance_id ? 'shipping_title_' . $instance_id : 'shipping_title';
    }

    private static function register_string($name, $value)
    {
        if ($value === '') {
            return;
        }

        do_action('wpml_register_single_string', self::DOMAIN, $name, $value);

        if (function_exists('pll_register_string')) {
            pll_register_string($name, $value, 'Woo 5E Shipping');
        }
    }

    private static function translate_string($value, $name)
    {
        if ($value === '') {
            return $value;
        }

        if (has_filter('wpml_translate_single_string')) {
            $translated = apply_filters('wpml_translate_single_string', $value, self::DOMAIN, $name);
            if (is_string($translated) && $translated !== '') {
                return $translated;
            }
        }

        if (function_exists('pll__')) {
            $translated = pll__($value);
            if (is_string($translated) && $translated !== '') {
                return $translated;
            }
        }

        return $value;
    }
}
