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

/**
 * Map language-prefixed root (/da/) to translated front page.
 * WP-core safe, repo-safe.
 */
add_action( 'parse_request', function ( $wp ) {

    if ( is_admin() || wp_doing_ajax() ) {
        return;
    }

    $req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );

    if ( ! is_string( $req_raw ) || $req_raw === '' ) {
        return;
    }

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

    if ( ! is_string( $parsed_path ) ) {
        return;
    }

    $path = trim( $parsed_path, '/' );

    // Only "/xx" or "/xx/"
    if ( ! preg_match( '~^([a-z]{2})(?:/)?$~', $path, $m ) ) {
        return;
    }

    $lang = $m[1];

$cache_key = 'reeid_front_page_lang_' . $lang;
$page_id = wp_cache_get( $cache_key, 'reeid' );

if ( false === $page_id ) {
$posts = get_posts(
    array(
        'post_type'      => 'page',
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- required translation lookup by language meta; result is cached above
        'meta_key'       => '_reeid_translation_lang',
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- required translation lookup by language meta; result is cached above
        'meta_value'     => $lang,
        'post_status'    => 'publish',
        'numberposts'    => 1,
        'no_found_rows'  => true,
        'fields'         => 'ids',
    )
);

    $page_id = ! empty( $posts[0] ) ? (int) $posts[0] : 0;

    wp_cache_set( $cache_key, $page_id, 'reeid', HOUR_IN_SECONDS );
}
if ( $page_id <= 0 ) {
    return;
}
    // Inject into main query
    $wp->query_vars = array(
        'page_id' => $page_id,
    );

    // Force correct conditional flags
    add_action(
        'wp',
        function () use ( $page_id ) {
            global $wp_query;

            $wp_query->is_page       = true;
            $wp_query->is_singular   = true;
            $wp_query->is_front_page = true;
            $wp_query->is_home       = false;

            $wp_query->queried_object_id = $page_id;
            $wp_query->queried_object    = get_post( $page_id );
        },
        0
    );

}, 1 );


/**
 * Override page_on_front for language-prefixed roots (/da/)
 * WITHOUT recursion.
 */
add_filter( 'option_page_on_front', function ( $front_id ) {

    if ( is_admin() || wp_doing_ajax() ) {
        return $front_id;
    }

    $req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );

    if ( ! is_string( $req_raw ) || $req_raw === '' ) {
        return $front_id;
    }

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

    if ( ! is_string( $parsed_path ) ) {
        return $front_id;
    }

    $path = trim( $parsed_path, '/' );

    // Match "/xx" or "/xx/"
    if ( ! preg_match( '~^([a-z]{2})(?:/)?$~', $path, $m ) ) {
        return $front_id;
    }

    global $wpdb;

    $lang = sanitize_key( strtolower( $m[1] ) );

    // 🔒 SAFE: direct meta lookup, cached, no WP_Query, no recursion

$cache_key = 'reeid_lang_page_' . $lang;
$page_id   = wp_cache_get( $cache_key, 'reeid' );

if ( false === $page_id ) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Safe prepared lookup, cached above
    $page_id = (int) $wpdb->get_var(
        $wpdb->prepare(
            "
            SELECT post_id
            FROM {$wpdb->postmeta}
            WHERE meta_key = '_reeid_translation_lang'
              AND meta_value = %s
            LIMIT 1
            ",
            $lang
        )
    );

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

    return $page_id ?: $front_id;

}, 1 );