<?php
/**
 * REEID Switcher Helpers (SAFE)
 * Extracted from Section 48 without affecting existing switcher logic.
 * NO UI, NO shortcode, NO injections — helpers only.
 */

defined('ABSPATH') || exit;

/* --------------------------------------------------------------------------
 * Normalize language code
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_lang_normalize_10')) {
    function reeid_lang_normalize_10($val)
    {
        $val = strtolower(substr(trim((string)$val), 0, 10));
        return preg_match('/^[a-z]{2}([-_][a-z0-9]{2})?$/i', $val) ? $val : '';
    }
}

/* --------------------------------------------------------------------------
 * Current request language from URL (cookie-agnostic)
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_current_request_lang')) {
    function reeid_current_request_lang(): string
    {
        $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);

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

        // Fallback to plugin default option (no hardcoding)
        foreach ([
            (string) get_option('reeid_default_language'),
            (string) get_option('reeid_lang_default'),
            (string) get_option('reeid_lang'),
            'en',
        ] as $c) {
            $c = reeid_lang_normalize_10($c);
            if ($c !== '') return $c;
        }

        return 'en';
    }
}

/* --------------------------------------------------------------------------
 * Find the canonical source post of a translation network
 * (Used by generic map switchers; SAFE and non-intrusive)
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_find_source_post_id')) {
    function reeid_find_source_post_id($seed = null, $front = 0)
    {
        global $wp_query;

        if ($seed instanceof WP_Post) {
            $src = (int) $seed->ID;
        } elseif (is_numeric($seed)) {
            $src = (int) $seed;
        } elseif (isset($wp_query) && is_object($wp_query)) {
            $qo  = method_exists($wp_query, 'get_queried_object') ? $wp_query->get_queried_object() : null;
            $src = ($qo instanceof WP_Post) ? (int)$qo->ID : (int)$front;
        } else {
            $src = (int)$front;
        }

        if ($src <= 0) {
            return 0;
        }

        $visited  = [];
        $hops     = 0;
        $max_hops = 50;

        while ($hops < $max_hops) {
            if (isset($visited[$src])) break;
            $visited[$src] = true;

            $parent = get_post_meta($src, '_reeid_translation_source', true);
            if (empty($parent)) break;

            $parent = (int)$parent;
            if ($parent <= 0 || $parent === $src) break;

            $parent_post = get_post($parent);
            if (! ($parent_post instanceof WP_Post)) break;

            $src = $parent;
            $hops++;
        }

        return (int)$src;
    }
}

/* --------------------------------------------------------------------------
 * Build language-prefixed URL for generic pages
 * SAFE: does NOT override existing switcher logic
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_build_lang_prefixed_url')) {
    function reeid_build_lang_prefixed_url($url, $lang, $default)
    {
        $lang    = reeid_lang_normalize_10($lang);
        $default = reeid_lang_normalize_10($default);

        if ($lang === '' || $lang === $default) {
            return $url;
        }

        $parts = wp_parse_url($url);
        $path  = isset($parts['path']) ? (string)$parts['path'] : '/';

        // Prevent double prefixing
        if (preg_match('#^/' . preg_quote($lang, '#') . '(/|$)#', $path)) {
            $rebuilt = user_trailingslashit(home_url($path));
        } else {
            $prefixed = '/' . $lang . $path;
            $rebuilt  = user_trailingslashit(home_url($prefixed));
        }

        // Preserve query+fragment
        if (! empty($parts['query'])) {
            $rebuilt .= '?' . $parts['query'];
        }
        if (! empty($parts['fragment'])) {
            $rebuilt .= '#' . $parts['fragment'];
        }

        return $rebuilt;
    }
}

/* --------------------------------------------------------------------------
 * Finalize items for switcher:
 * - ensure default language present
 * - dedupe by code
 * - hide only the CURRENT language (from URL), not the default blindly
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_switcher_finalize_items')) {
    function reeid_switcher_finalize_items(array $items, string $default): array
    {
        $default = reeid_lang_normalize_10($default ?: 'en');
        $current = function_exists('reeid_current_request_lang')
            ? reeid_current_request_lang()
            : $default;

        // Normalize codes to lowercase and ensure structure
        $norm = [];
        foreach ($items as $it) {
            $code = isset($it['code']) ? reeid_lang_normalize_10($it['code']) : '';
            if ($code === '') continue;
            $norm[] = [
                'code' => $code,
                'pid'  => isset($it['pid']) ? (int)$it['pid'] : 0,
                'url'  => isset($it['url']) ? (string)$it['url'] : '',
            ];
        }
        $items = $norm;

        // Ensure default is present
        $haveDefault = false;
        foreach ($items as $it) {
            if ($it['code'] === $default) { $haveDefault = true; break; }
        }
        if (! $haveDefault) {
            // Best effort: if a URL for default is not known here, use homepage/post permalinks
            $url = home_url('/');
            $items[] = ['code' => $default, 'pid' => 0, 'url' => $url];
        }

        // Dedupe by code (keep first)
        $seen = [];
        $items = array_values(array_filter($items, function($it) use (&$seen) {
            $c = $it['code'];
            if (isset($seen[$c])) return false;
            $seen[$c] = true;
            return true;
        }));

        // Hide only the CURRENT language (keep default unless it's also current)
        $items = array_values(array_filter($items, function($it) use ($current) {
            return $it['code'] !== $current;
        }));

        return $items;
    }
}

/* --------------------------------------------------------------------------
 * Woo Inline: Build product permalink using inline native slug
 * (USED by existing product inline switcher logic)
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_switcher_product_permalink')) {

    function reeid_switcher_product_permalink($post, $lang) {

        $product_id = is_object($post) ? (int) $post->ID : (int) $post;
        if ($product_id <= 0) {
            return get_permalink($post);
        }

        $lang = strtolower(sanitize_key((string) $lang));
        if ($lang === '') {
            return get_permalink($product_id);
        }

        /* ==========================================================
         * 🔒 CRITICAL FIX:
         * Default SOURCE language must NEVER be prefixed
         * ========================================================== */
        $source_lang = get_option('reeid_translation_source_lang', '');
        $source_lang = is_string($source_lang) ? strtolower($source_lang) : '';

        if ($source_lang !== '' && $lang === $source_lang) {
            // Always return canonical product URL
            return get_permalink($product_id);
        }

        /* ==========================================================
         * WooCommerce product base
         * ========================================================== */
        $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());

/* ==========================================================
 * 1) Woo inline translation slug (PRIORITY)
 * ========================================================== */
$tr = get_post_meta($product_id, "_reeid_wc_tr_" . $lang, true);
if (is_array($tr) && !empty($tr['slug'])) {
    $native = trim((string) $tr['slug']);
    if ($native !== '') {
        return "{$home}/{$lang}/{$base}/" . rawurlencode($native) . "/";
    }
}

/* ==========================================================
 * Woo inline switcher safety:
 * Do not fall back to legacy _rtl_slug_ unless a real Woo
 * translation packet exists. Packet slug is handled above.
 * ========================================================== */
$mkey = '_rtl_slug_' . $lang;

        /* ==========================================================
         * Unicode-safe slugify
         * ========================================================== */
        $make_slug = static function (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);
            $slug = strtolower($slug);
            return trim($slug, '-');
        };

        
        /* ==========================================================
         * 4) Stored inline translation slug
         * ========================================================== */
        $tr = get_post_meta($product_id, "_reeid_wc_tr_" . $lang, true);
        if (is_array($tr) && isset($tr['slug']) && is_string($tr['slug'])) {
            $s = trim($tr['slug']);
            if ($s !== '') {
                if ((string) get_post_meta($product_id, $mkey, true) === '') {
                    update_post_meta($product_id, $mkey, $s);
                }
                return "{$home}/{$lang}/{$base}/{$s}/";
            }
        }

        /* ==========================================================
         * 2) Saved translated title meta
         * ========================================================== */
        $title_meta_key_full = '_reeid_title_' . $lang;
        $title_meta_key_base = '_reeid_title_' . preg_replace('~^([a-z]{2}).*$~', '$1', $lang);

        foreach ([$title_meta_key_full, $title_meta_key_base] as $title_meta_key) {
            $title_meta = (string) get_post_meta($product_id, $title_meta_key, true);
            if ($title_meta !== '') {
                $gen = $make_slug($title_meta);
                if ($gen !== '') {
                    update_post_meta($product_id, $mkey, $gen);
                    return "{$home}/{$lang}/{$base}/{$gen}/";
                }
            }
        }

/* ==========================================================
 * 3) Inline helper (forced context)
 * ========================================================== */
$translated = '';

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

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

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

    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);
    }
} finally {
    if ($__OLD_LANG_COOKIE === null) { unset($_COOKIE['site_lang']); }
    else { $_COOKIE['site_lang'] = $__OLD_LANG_COOKIE; }

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

if ($translated !== '') {
    $gen = $make_slug($translated);
    if ($gen !== '') {
        update_post_meta($product_id, $mkey, $gen);
        return "{$home}/{$lang}/{$base}/{$gen}/";
    }
}

        /* ==========================================================
         * 5) Last-resort fallback
         * ========================================================== */
        $post_name = (string) get_post_field('post_name', $product_id);
        if ($post_name !== '') {
            return "{$home}/{$lang}/{$base}/{$post_name}/";
        }

        return get_permalink($product_id);
    }
}


/* --------------------------------------------------------------------------
 * Inline product items collector (product → list of languages + URLs)
 * Supports your existing URL rewrite system
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_switcher_collect_product_inline_items')) {
    function reeid_switcher_collect_product_inline_items($post, $default)
    {
        $items = [];
        $post_id = (int)($post instanceof WP_Post ? $post->ID : 0);
        if ($post_id <= 0) return $items;

        $inline_raw = get_post_meta( $post_id, '_reeid_wc_inline_langs', true );
$inline     = is_array( $inline_raw ) ? $inline_raw : array();
$default    = reeid_lang_normalize_10( $default );

$codes = array_unique(
    array_filter(
        array_map(
            'reeid_lang_normalize_10',
            $inline
        )
    )
);

/*
 * Woo inline source of truth:
 * only expose languages that have a real _reeid_wc_tr_{lang} packet.
 * This prevents stale _reeid_langs / _reeid_translation_map data from creating
 * broken /lang/original-product-slug links after Pro/Free mixed usage.
 */
$codes = array_values(
    array_filter(
        $codes,
        static function ( $code ) use ( $post_id ) {
            if ( '' === $code ) {
                return false;
            }

            $packet = get_post_meta( $post_id, '_reeid_wc_tr_' . $code, true );

            return is_array( $packet )
                && (
                    ! empty( $packet['title'] )
                    || ! empty( $packet['content'] )
                    || ! empty( $packet['excerpt'] )
                    || ! empty( $packet['attributes'] )
                );
        }
    )
);


        foreach ($codes as $code) {
            $items[] = [
                'code' => $code,
                'url'  => reeid_switcher_product_permalink($post, $code),
                'pid'  => $post_id,
            ];
        }
// 🔒 Ensure SOURCE language points to REAL product (no /en/)
if ($default) {
    $items[] = [
        'code' => $default,
        'url'  => get_permalink($post_id),
        'pid'  => $post_id,
    ];
}

        // Finalize: keep default, hide only current, dedupe
        return reeid_switcher_finalize_items($items, $default);
    }
}

/* --------------------------------------------------------------------------
 * Generic pages collector (for non-product posts) — hardened
 * ----------------------------------------------------------------------- */
if ( ! function_exists( 'reeid_switcher_collect_generic_items' ) ) {
    function reeid_switcher_collect_generic_items( $post, $default, $front ) {
        $items = [];
        if ( ! ( $post instanceof WP_Post ) ) return $items;

        // Normalize default once
        $default = reeid_lang_normalize_10( $default ?: 'en' );

        // Find network source
        $src = (int) reeid_find_source_post_id( $post, (int) $front );
        if ( $src <= 0 ) $src = (int) $post->ID; // safety

        // Map: lang => post_id (ensure default->source)
        $map = (array) get_post_meta( $src, '_reeid_translation_map', true );
        $map[ $default ] = $src;

        foreach ( $map as $code => $pid ) {
            $pid = absint( $pid );
            if ( ! $pid || get_post_status( $pid ) !== 'publish' ) continue;

            $lang = strtolower( (string) ( get_post_meta( $pid, '_reeid_translation_lang', true ) ?: $code ) );

            // Homepage logic
            if ( $pid === (int) $front ) {
                if ( $lang === $default ) {
                    // Point default language to the *real* front page permalink,
                    // not bare "/" — avoids “empty front” in some setups.
                    $url = get_permalink( $front );
                } else {
                    // Non-default languages keep a clean /{lang}/ root
                    $url = home_url( "/{$lang}/" );
                }
            } else {
                // Non-home pages: add /{lang}/ prefix when needed
                $perma = get_permalink( $pid );
                if ( function_exists( 'reeid_build_lang_prefixed_url' ) ) {
                    $url = reeid_build_lang_prefixed_url( $perma, $lang, $default );
                } else {
                    $url = $perma;
                }
            }

            $items[] = [
                'code' => $lang,
                'pid'  => $pid,
                'url'  => $url,
            ];
        }

        // Ensure default language is present (some maps omit it)
        $haveDefault = false;
        foreach ( $items as $it ) {
            if ( ! empty( $it['code'] ) && $it['code'] === $default ) { $haveDefault = true; break; }
        }
        if ( ! $haveDefault && get_post_status( $src ) === 'publish' ) {
            $url = ( $src === (int) $front ) ? get_permalink( $front )
                 : ( function_exists( 'reeid_build_lang_prefixed_url' )
                        ? reeid_build_lang_prefixed_url( get_permalink( $src ), $default, $default )
                        : get_permalink( $src ) );
            $items[] = [
                'code' => $default,
                'pid'  => (int) $src,
                'url'  => $url,
            ];
        }

        // Deduplicate by code (keep first)
        $seen = [];
        $items = array_values( array_filter( $items, function( $it ) use ( &$seen ) {
            $c = $it['code'] ?? '';
            if ( $c === '' || isset( $seen[ $c ] ) ) return false;
            $seen[ $c ] = true;
            return true;
        } ) );

        // Final safety: never return empty — at least default current page
        if ( empty( $items ) ) {
            $items[] = [
                'code' => $default,
                'pid'  => (int) $post->ID,
                'url'  => get_permalink( $post->ID ),
            ];
        }

        return $items;
    }
}

/* --------------------------------------------------------------------------
 * Current language detection for Woo Inline product pages (legacy helper)
 * ----------------------------------------------------------------------- */
if (! function_exists('reeid_current_lang_for_product')) {
    function reeid_current_lang_for_product($default)
    {
        if (function_exists('reeid_wc_resolve_lang_strong')) {
            $l = (string)reeid_wc_resolve_lang_strong();
            if ($l) return strtolower(substr($l, 0, 10));
        }

        if (! empty($_COOKIE['site_lang'])) {
            $ck = sanitize_text_field(wp_unslash($_COOKIE['site_lang']));
            return strtolower(substr($ck, 0, 10));
        }

        return strtolower(substr($default, 0, 10));
    }
}
