<?php
/**
 * Front-end debug logging helpers.
 *
 * @package WPR_Translate
 */

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

/**
 * Log the current front-end language and resolved IDs on each page load.
 *
 * @return void
 */
function wpr_translate_log_frontend_language_state() {
    if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
        return;
    }

    if ( function_exists( 'wpr_translate_language_router_is_rest_request' ) && wpr_translate_language_router_is_rest_request() ) {
        return;
    }

    if ( wp_is_json_request() ) {
        return;
    }

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

    $language_code = '';

    if ( function_exists( 'wpr_translate_get_current_language' ) ) {
        $language = wpr_translate_get_current_language();

        if ( is_array( $language ) && ! empty( $language['code'] ) ) {
            $language_code = sanitize_key( $language['code'] );
        }
    }

    $post_id = 0;

    if ( function_exists( 'is_singular' ) && is_singular() ) {
        $post_id = get_queried_object_id();
    }

    $translated_id = 0;

    if ( $post_id && '' !== $language_code && function_exists( 'wpr_translate_resolve_translated_post_id' ) ) {
        $translated_id = (int) wpr_translate_resolve_translated_post_id( $post_id, $language_code );
    }

    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';

    wpr_translate_debug_log(
        'Front-end language state.',
        array(
            'language_code' => $language_code,
            'post_id'       => $post_id,
            'translated_id' => $translated_id,
            'request_uri'   => $request_uri,
        )
    );
}

add_action( 'wp', 'wpr_translate_log_frontend_language_state', 20 );
