<?php
defined('ABSPATH') || exit;

/**
 * Build a product URL for a given target language:
 * - If _rtl_slug_{lang} exists, use it as the slug (native-script).
 * - Else fall back to the product’s English post_name under the lang prefix (no 404).
 * - Respects WooCommerce custom product base.
 */
if (!function_exists('reeid_get_product_url_for_lang')) {
    function reeid_get_product_url_for_lang(int $product_id, string $lang): string {
        $lang = strtolower(sanitize_key($lang));
        if ($lang === '') { $lang = 'en'; }

        // WooCommerce product base (default 'product')
        $wc_permalinks = get_option('woocommerce_permalinks', []);
        $base = is_array($wc_permalinks) && !empty($wc_permalinks['product_base'])
            ? trim((string) $wc_permalinks['product_base'], '/')
            : 'product';

        $home = untrailingslashit(home_url());
        $native = (string) get_post_meta($product_id, '_rtl_slug_' . $lang, true);

        if ($native !== '') {
            // Native-script slug already persisted → use it
            return "{$home}/{$lang}/{$base}/" . rawurlencode($native) . "/";
        }

        // Fallback to English post_name (never 404)
        $post_name = (string) get_post_field('post_name', $product_id);
        if ($post_name === '') {
            // last resort: get_permalink (will include EN slug)
            $en = get_permalink($product_id);
            // Prepend lang if needed
            $path = (string) wp_parse_url($en, PHP_URL_PATH);
            return "{$home}/{$lang}" . rtrim($path, '/') . '/';
        }

        return "{$home}/{$lang}/{$base}/{$post_name}/";
    }
}
