<?php
/**
 * REEID — WooCommerce Language Runtime
 * Determines current language for frontend rendering.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
if ( ! function_exists( 'reeid_wc_current_lang' ) ) {

	function reeid_wc_current_lang(): string {

		static $lang = null;
		if ( $lang !== null ) {
			return $lang;
		}

		// 1) URL prefix: /my/, /ar/, /el/, etc.
		$req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );

		if ( is_string( $req_raw ) && $req_raw !== '' ) {

			$request_uri = wp_unslash( $req_raw );
			$path        = wp_parse_url( $request_uri, PHP_URL_PATH );

			if ( is_string( $path ) ) {
				$uri = trim( $path, '/' );
				$seg = strtolower( strtok( $uri, '/' ) );

				if ( preg_match( '/^[a-z]{2}(-[a-z]{2})?$/', $seg ) ) {
					return $lang = sanitize_key( $seg );
				}
			}
		}

		// 2) Cookie fallback
		$cookie_lang = filter_input( INPUT_COOKIE, 'site_lang', FILTER_UNSAFE_RAW );

		if ( is_string( $cookie_lang ) && $cookie_lang !== '' ) {
			$cookie_lang = sanitize_key( wp_unslash( $cookie_lang ) );
			return $lang = strtolower( $cookie_lang );
		}

		// 2.5) Inline WooCommerce product language (REEID)
		if ( is_singular( 'product' ) ) {
			global $post;

			if ( $post instanceof WP_Post ) {
				$langs = (array) get_post_meta(
					$post->ID,
					'_reeid_wc_inline_langs',
					true
				);

				if ( ! empty( $langs ) ) {

					// Prefer explicit request lang if present
					$get_lang = filter_input( INPUT_GET, 'lang', FILTER_UNSAFE_RAW );

					if ( is_string( $get_lang ) && $get_lang !== '' ) {
						$req = strtolower(
							sanitize_key( wp_unslash( $get_lang ) )
						);

						if ( in_array( $req, $langs, true ) ) {
							return $lang = $req;
						}
					}

					// Otherwise use first non-source language
					$source = strtolower(
						(string) get_option(
							'reeid_translation_source_lang',
							'en'
						)
					);

					foreach ( $langs as $l ) {
						$l = strtolower( (string) $l );
						if ( $l !== $source ) {
							return $lang = $l;
						}
					}
				}
			}
		}

        // 3) Default source language (plugin setting)
        return $lang = strtolower(
            (string) get_option(
                'reeid_translation_source_lang',
                'en'
            )
        );
    }
}

/**
 * ------------------------------------------------------------
 * Propagate REEID language into WP / WooCommerce runtime
 * (NO rewrites, NO redirects, NO DB writes)
 * ------------------------------------------------------------
 */
add_action(
    'parse_request',
    function ( $wp ) {

        if ( is_admin() || wp_doing_ajax() || ( function_exists( 'wp_is_json_request' ) && wp_is_json_request() ) ) {
            return;
        }

        if ( ! function_exists( 'reeid_wc_current_lang' ) ) {
            return;
        }

        $req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
        $uri     = is_string( $req_raw ) ? wp_unslash( $req_raw ) : '';
        $path    = (string) wp_parse_url( $uri, PHP_URL_PATH );

        // 🔒 IMPORTANT: do not touch the plain root "/"
        if ( $path === '/' || $path === '' ) {
            return;
        }

        $lang = reeid_wc_current_lang();
        if ( ! $lang ) {
            return;
        }

        // Only expose language when URL is explicitly prefixed
        if ( preg_match( '#^/[a-z]{2}(?:-[a-z]{2})?(/|$)#i', $path ) ) {
            $wp->query_vars['reeid_lang'] = $lang;
        }
    },
    1
);

// add_filter(
//     'redirect_canonical',
//     function ( $redirect_url, $requested_url ) {

//         // Only frontend
//         if ( is_admin() || wp_doing_ajax() ) {
//             return $redirect_url;
//         }

//         if ( ! function_exists( 'reeid_wc_current_lang' ) ) {
//             return $redirect_url;
//         }

//         $lang = reeid_wc_current_lang();
//         if ( ! $lang ) {
//             return $redirect_url;
//         }

// $source = strtolower(
//     (string) get_option('reeid_translation_source_lang', 'en')
// );

// /*
//  * CRITICAL:
//  * Do NOT inject source language into query vars
//  * when URL has no prefix.
//  */
// if ( $lang === $source ) {
//     return;
// }


//         $source = strtolower(
//             (string) get_option( 'reeid_translation_source_lang', 'en' )
//         );

//         // Do NOT block source language
//         if ( $lang === $source ) {
//             return $redirect_url;
//         }

//         // Only WooCommerce product URLs
//         if ( strpos( $requested_url, '/product/' ) === false ) {
//             return $redirect_url;
//         }

//         // 🚫 STOP WordPress from rewriting translated slugs
//         return false;

//     },
//     1,
//     2
// );

