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

/**
 * REEID native slug API for products.
 * - Try saved meta (_rtl_slug_{lang})
 * - Else: derive from translated title (meta first, then inline helper), persist, return.
 * - Unicode-safe slugify.
 * - NO language hardcoding. $lang is provided by caller.
 */
if (!function_exists('reeid_build_native_slug')) {
    function reeid_build_native_slug(string $title): string {
        $slug = trim($title);
        $slug = preg_replace('~\s+~u', '-', $slug);
        $slug = preg_replace('~[^_\-\p{L}\p{N}]+~u', '', $slug);
        $slug = preg_replace('~\-{2,}~', '-', $slug);
        return trim($slug, '-');
    }
}

/**
 * Get (and optionally create) a native slug for a product/language.
 * @return string Native slug (unencoded), or '' if unavailable.
 */
if (!function_exists('reeid_native_slug_for_lang')) {
    function reeid_native_slug_for_lang(int $product_id, string $lang, bool $persist = true): string {
        if ($product_id <= 0) return '';
        $lang = strtolower(sanitize_key($lang));
        if ($lang === '' || $lang === 'en') return ''; // EN uses post_name

        $mkey = '_rtl_slug_' . $lang;

        // 1) Existing meta
        $saved = (string) get_post_meta($product_id, $mkey, true);
        if ($saved !== '') return $saved;

        // 2) Title meta (if stored)
        $tkey  = '_reeid_title_' . $lang;
        $tmeta = (string) get_post_meta($product_id, $tkey, true);
        if ($tmeta !== '') {
            $gen = reeid_build_native_slug($tmeta);
            if ($gen !== '' && $persist) {
                update_post_meta($product_id, $mkey, $gen);
            }
            return $gen;
        }

        // 3) Inline helper (runtime) — best effort
        $translated = '';
        if (function_exists('reeid_wc_inline_title_short')) {
            $translated = (string) reeid_wc_inline_title_short($product_id, $lang);
        } elseif (function_exists('reeid_wc_inline_title')) {
            $translated = (string) reeid_wc_inline_title($product_id, $lang);
        } elseif (function_exists('reeid_inline_title_for_lang')) {
            $translated = (string) reeid_inline_title_for_lang($product_id, $lang);
        }

        if ($translated !== '') {
            $gen = reeid_build_native_slug($translated);
            if ($gen !== '' && $persist) {
                update_post_meta($product_id, $mkey, $gen);
            }
            return $gen;
        }

        // 4) Nothing available
        return '';
    }
}
