<?php
/**
 * REEID — Native Slug Auto-seed (single, consolidated version)
 * - Seeds _rtl_slug_{lang} for Woo products.
 * - Order: stored translated title → inline title (forced context) → rendered title (final fallback).
 * - No hardcoded languages. No new files.
 */

defined('ABSPATH') || exit;

/* ───────────────────────── helpers ───────────────────────── */

if (!function_exists('reeid_ns_slugify_native')) {
    function reeid_ns_slugify_native(string $title): string {
    $s = trim(wp_strip_all_tags($title));
    $s = preg_replace('~\s+~u', '-', $s);              // whitespace -> dash
    $s = preg_replace('~[^_\-\p{L}\p{N}]+~u', '', $s); // keep letters/numbers/_/-
    $s = preg_replace('~\-{2,}~', '-', $s);            // collapse dashes
    $s = trim($s, '-');

    // NEW: lowercase (Unicode-safe when mbstring is available)
    $s = function_exists('mb_strtolower') ? mb_strtolower($s, 'UTF-8') : strtolower($s);

    return $s;
}
}

if (!function_exists('reeid_ns_active_langs')) {
    function reeid_ns_active_langs(): array {
        // Collect from existing plugin options (no hardcoding)
        $pool = [];
        foreach (['reeid_switcher_langs','reeid_active_languages','reeid_langs','reeid_wc_langs'] as $opt) {
            $v = get_option($opt);
            if (is_array($v)) {
                foreach ($v as $c) {
                    $c = strtolower(preg_replace('~[^a-z0-9-]~','',(string)$c));
                    if ($c && $c !== 'en') $pool[$c] = true;
                }
            }
        }
        return array_keys($pool);
    }
}

/**
 * Inline title with TEMP forced language context so helpers don’t return EN.
 */
if (!function_exists('reeid_ns_inline_title_forced')) {
    function reeid_ns_inline_title_forced(int $product_id, string $lang): string {
        $lang = strtolower(sanitize_key($lang));
        $out = '';

        $old_cookie = filter_input( INPUT_COOKIE, 'site_lang', FILTER_UNSAFE_RAW );
        $old_cookie = $old_cookie ? wp_unslash( $old_cookie ) : null;

        $old_get = filter_input( INPUT_GET, 'site_lang', FILTER_UNSAFE_RAW );
        $old_get = $old_get ? wp_unslash( $old_get ) : null;

        try {
            $_COOKIE['site_lang'] = $lang;
            $_GET['site_lang']    = $lang;

            if (function_exists('reeid_wc_inline_title_short')) {
                $out = (string) reeid_wc_inline_title_short($product_id, $lang);
            } elseif (function_exists('reeid_wc_inline_title')) {
                $out = (string) reeid_wc_inline_title($product_id, $lang);
            } elseif (function_exists('reeid_inline_title_for_lang')) {
                $out = (string) reeid_inline_title_for_lang($product_id, $lang);
            }
                } finally {
            if ( null === $old_cookie ) {
                unset( $_COOKIE['site_lang'] );
            } else {
                $_COOKIE['site_lang'] = $old_cookie;
            }

            if ( null === $old_get ) {
                unset( $_GET['site_lang'] );
            } else {
                $_GET['site_lang'] = $old_get;
            }
        }

        return $out;
    }
}

/**
 * Seed a single language slug for a product (id + lang).
 * - Normalizes lang (hi-IN -> hi, de-DE -> de) but probes meta with base/full.
 * - If _rtl_slug_{base} exists: no-op
 * - Else try stored translated title meta: _reeid_title_{full} OR _reeid_title_{base}
 * - Else use inline title helper with forced language context
 * - Else FINAL fallback: rendered title via the_title filters
 * - Saves to _rtl_slug_{base}. Returns true if saved.
 */
if (!function_exists('reeid_ns_seed_for_lang')) {
    // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
function reeid_ns_seed_for_lang(int $product_id, string $lang): bool {
        $product_id = (int) $product_id;
        if ($product_id <= 0) return false;

        $lang = strtolower(sanitize_key(trim((string)$lang)));
        if ($lang === '') return false;

        $base = preg_replace('~^([a-z]{2}).*$~', '$1', $lang);
        $full = $lang;
        $mkey = '_rtl_slug_' . $base;

        // Already seeded?
        if ((string) get_post_meta($product_id, $mkey, true) !== '') {
            return false;
        }

        // 1) Stored translated title meta (full, then base)
        foreach (['_reeid_title_' . $full, '_reeid_title_' . $base] as $tk) {
            $t = (string) get_post_meta($product_id, $tk, true);
            if ($t !== '') {
                $slug = reeid_ns_slugify_native($t);
                if ($slug !== '') {
                    update_post_meta($product_id, $mkey, $slug);
                    return true;
                }
            }
        }

        // 2) Inline title (forced ctx) — try base then full
        $t = reeid_ns_inline_title_forced($product_id, $base);
        if ($t === '' && $full !== $base) {
            $t = reeid_ns_inline_title_forced($product_id, $full);
        }
        if ($t !== '') {
            $slug = reeid_ns_slugify_native($t);
            if ($slug !== '') {
                update_post_meta($product_id, $mkey, $slug);
                return true;
            }
        }
        // 3) FINAL fallback — allowed only during save_post context
        if ( did_action( 'save_post_product' ) ) {
            $raw = (string) get_post_field( 'post_title', $product_id );

            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core hook.
            $title = (string) apply_filters( 'the_title', $raw, $product_id );
            $title = wp_strip_all_tags( $title );

            if ( '' !== $title ) {
                $slug = reeid_ns_slugify_native( $title );

                if ( '' !== $slug ) {
                    update_post_meta( $product_id, $mkey, $slug );
                    return true;
                }
            }
        }

        return false;
    }
}
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

/* ───────────── seed on save (editor / translation creation) ───────────── */

add_action('save_post_product', function ($post_id, $post) {
    if (wp_is_post_revision($post_id) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) return;
    if (!($post instanceof WP_Post) || $post->post_type !== 'product') return;

    // Global langs + per-product inline list
    $langs  = reeid_ns_active_langs();
    $inline = (array) get_post_meta($post_id, '_reeid_wc_inline_langs', true);
    foreach ($inline as $c) {
        $c = strtolower(preg_replace('~[^a-z0-9-]~','',(string)$c));
        if ($c && $c !== 'en' && !in_array($c, $langs, true)) $langs[] = $c;
    }

    foreach ($langs as $L) {
        reeid_ns_seed_for_lang($post_id, $L);
    }
}, 20, 2);

/* ───────────── seed at first frontend view (late) ─────────────
   Run late so inline title helpers and filters have data. */

add_action('template_redirect', function () {
    if (is_admin() || wp_doing_ajax() || (function_exists('wp_is_json_request') && wp_is_json_request())) return;
    if (!is_singular('product')) return;

    global $post;
    if (!($post instanceof WP_Post) || $post->post_type !== 'product') return;

    $pid = (int) $post->ID;

    // Resolve current request language from URL prefix only (cookie-agnostic)
    $uri = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
    $uri = (string) ( $uri ? wp_unslash( $uri ) : '' );

    $path = (string) wp_parse_url($uri, PHP_URL_PATH);
    $path = '/' . ltrim($path, '/');

    $lang = '';
    if (preg_match('~^/([a-z]{2}(?:-[a-z0-9]{2})?)(/|$)~i', $path, $m)) {
        $lang = strtolower($m[1]);
    }
    if ($lang === '') $lang = 'en';

    // Languages to seed: global options + per-product inline list
    $langs  = reeid_ns_active_langs();
    $inline = (array) get_post_meta($pid, '_reeid_wc_inline_langs', true);
    foreach ($inline as $c) {
        $c = strtolower(preg_replace('~[^a-z0-9-]~','',(string)$c));
        if ($c && $c !== 'en' && !in_array($c, $langs, true)) $langs[] = $c;
    }

    // 1) Seed current request language first (if not EN)
    $seeded_current = false;
    if ($lang !== 'en') {
        $seeded_current = reeid_ns_seed_for_lang($pid, $lang);
    }

    // 2) Opportunistically seed the rest
    foreach ($langs as $L) {
        if ($L === $lang) continue;
        reeid_ns_seed_for_lang($pid, $L);
    }

    // 3) If we just seeded current lang and URL still has EN slug, redirect once to native
    if ($seeded_current && $lang !== 'en') {
        $wc_permalinks = get_option('woocommerce_permalinks', []);
        $base = (is_array($wc_permalinks) && !empty($wc_permalinks['product_base']))
            ? trim((string) $wc_permalinks['product_base'], '/')
            : 'product';

        $mkey   = '_rtl_slug_' . preg_replace('~^([a-z]{2}).*$~', '$1', $lang);
        $native = (string) get_post_meta($pid, $mkey, true);

        if ($native !== '') {
            $en_slug = (string) get_post_field('post_name', $pid);
            if (preg_match('#^/' . preg_quote($lang,'#') . '/' . preg_quote($base,'#') . '/([^/]+)/?$#i', $path, $mm)) {
                $current = rawurldecode($mm[1]);
                if ($current === $en_slug) {
                    $target = home_url("/{$lang}/{$base}/" . rawurlencode($native) . "/");
                    if (rtrim($target,'/') !== rtrim(home_url($path),'/')) {
                        wp_safe_redirect($target, 302);
                        exit;
                    }
                }
            }
        }
    }
}, 999);
