<?php

return;
defined('ABSPATH') || exit;

/**
 * Prevent WP canonical redirect from forcing English post_name when a native
 * product slug is used. Lets our 404 resolver handle routing instead.
 */
add_filter('redirect_canonical', function ($redirect_url, $requested_url) {
    // Skip admin/AJAX/REST/JSON
    if (is_admin() || wp_doing_ajax() || wp_is_json_request()) { return $redirect_url; }
    if (defined('REST_REQUEST') && REST_REQUEST) { return $redirect_url; }

    $path = (string) wp_parse_url((string) $requested_url, PHP_URL_PATH);
    if ($path === '') { return $redirect_url; }

    // Optional: respect custom Woo 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';

    // Extract segments, decode last segment
    $parts = array_values(array_filter(explode('/', trim($path, '/'))));
    if (empty($parts)) { return $redirect_url; }
    $last = urldecode(end($parts));

    // Quick structure check: /{lang?}/product/{slug}
    $is_product_like =
        (count($parts) >= 2 && strtolower($parts[0]) === strtolower($base)) ||
        (count($parts) >= 3 && preg_match('~^[a-z]{2}([_-][a-z0-9]+)?$~i', $parts[0]) && strtolower($parts[1]) === strtolower($base));
    if (!$is_product_like || $last === '') { return $redirect_url; }

    // Look up a product by any _rtl_slug_% meta == $last
global $wpdb;

$cache_key = 'reeid_rtl_slug_lookup_' . md5( $last );
$post_id = wp_cache_get( $cache_key, 'reeid' );

if ( false === $post_id ) {

    $like = $wpdb->esc_like('_rtl_slug_') . '%';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $post_id = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT p.ID
             FROM {$wpdb->postmeta} pm
             JOIN {$wpdb->posts} p ON p.ID = pm.post_id
             WHERE pm.meta_key LIKE %s
               AND pm.meta_value = %s
               AND p.post_type = 'product'
               AND p.post_status IN ('publish','private')
             LIMIT 1",
            $like,
            $last
        )
    );

    wp_cache_set( $cache_key, $post_id, 'reeid', HOUR_IN_SECONDS );
}

    // If this is a native product slug, CANCEL canonical redirect.
    if ($post_id > 0) {
        return false; // critical: prevents WP from rewriting to English post_name
    }

    return $redirect_url;
}, 10, 2);

/**
 * REEID: Woo inline products — force native slug in the browser URL.
 * If user/bot hits /{lang}/product/{EN-slug}/, 301 to /{lang}/product/{native-slug}/.
 */
add_action('template_redirect', function () {
    if ( is_admin() || wp_doing_ajax() || wp_is_json_request() ) { return; }
    if ( ! function_exists('is_singular') || ! is_singular('product') ) { return; }

    $pid = (int) get_queried_object_id();
    if ( $pid <= 0 ) { return; }

    // Only for inline/virtual language products
    $inline = get_post_meta( $pid, '_reeid_wc_inline_langs', true );
    if ( ! is_array( $inline ) || empty( $inline ) ) { return; }

    $req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
    $req_raw = $req_raw ? wp_unslash( $req_raw ) : '';
    if ( ! is_string($req_raw) || $req_raw === '' ) { return; }

    $path = (string) wp_parse_url( $req_raw, PHP_URL_PATH );
    if ( $path === '' ) { return; }
    $path = '/' . ltrim($path, '/');

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

    // Match "/{lang}/product/{slug}/"
    if ( ! preg_match( '#^/([a-z]{2}(?:-[a-z0-9]{2})?)/' . preg_quote($base, '#') . '/([^/]+)/?$#i', $path, $m ) ) {
        return;
    }

    $lang = strtolower( sanitize_key( (string) $m[1] ) );
    if ( $lang === '' || $lang === 'en' ) { return; }

    $req_slug = rawurldecode( (string) $m[2] );
    $en_slug  = (string) get_post_field( 'post_name', $pid );
    if ( $en_slug === '' ) { return; }

    // Only redirect when the request is using the EN slug
    if ( $req_slug !== $en_slug ) { return; }

    // Find native slug for that language
    $native = '';

    $tr = get_post_meta( $pid, '_reeid_wc_tr_' . $lang, true );
    if ( is_array($tr) && ! empty($tr['slug']) && is_string($tr['slug']) ) {
        $native = (string) $tr['slug'];
    } else {
        $rtl = get_post_meta( $pid, '_rtl_slug_' . $lang, true );
        if ( is_string($rtl) && $rtl !== '' ) {
            $native = (string) $rtl;
        }
    }

    if ( $native === '' || $native === $en_slug ) { return; }

    // Build redirect URL (percent-encode for header safety; browsers display native)
    $target = home_url( '/' . $lang . '/' . $base . '/' . rawurlencode($native) . '/' );

    $q = wp_parse_url( $req_raw, PHP_URL_QUERY );
    if ( is_string($q) && $q !== '' ) {
        $target .= '?' . $q;
    }

    wp_safe_redirect( $target, 301 );
    exit;
}, 1);

