<?php
/**
 * Shared helpers supporting SEO tag generation.
 */

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

/**
 * Prepare canonical and alternate URLs from a translation group.
 */
function wpr_translate_seo_prepare_group_urls( $translations, $source_code, $fallback_id, $languages, $resolve_callback, $fallback_callback ) {
    // Normalize the translation map to ensure consistent keys.
    $translations = wpr_translate_seo_normalize_translation_map( $translations );
    $source_id    = wpr_translate_seo_pick_translation_id( $translations, $source_code );

    if ( ! $source_id ) {
        // Fall back to the supplied element ID when no translation exists.
        $source_id = $fallback_id;
    }

    // Resolve the canonical URL for the source language.
    $canonical = call_user_func( $resolve_callback, $source_id, $source_code );

    if ( '' === $canonical ) {
        // Use the fallback callback when the resolver returns empty.
        $canonical = call_user_func( $fallback_callback, $source_id );
    }

    if ( '' === $canonical ) {
        // No canonical URL can be resolved.
        return array( 'canonical' => '', 'alternates' => array() );
    }

    // Seed alternates with the canonical URL.
    $alternates = array( 'x-default' => $canonical );

    foreach ( $languages as $language ) {
        if ( empty( $language['code'] ) ) {
            continue;
        }

        // Compute the target language identifiers.
        $code      = sanitize_key( $language['code'] );
        $hreflang  = wpr_translate_seo_get_hreflang_value( $language );
        $target_id = wpr_translate_seo_pick_translation_id( $translations, $code );
        $url       = '';

        if ( $target_id ) {
            // Resolve the URL for the target translation.
            $url = call_user_func( $resolve_callback, $target_id, $code );

            if ( '' === $url ) {
                $url = call_user_func( $fallback_callback, $target_id );
            }
        }

        if ( '' === $url ) {
            // Fallback to the canonical URL when no translation is resolved.
            $url = $canonical;
        }

        if ( '' === $hreflang || '' === $url ) {
            continue;
        }

        $alternates[ $hreflang ] = $url;
    }

    return array( 'canonical' => $canonical, 'alternates' => $alternates );
}

/**
 * Normalise translation map keys for lookups.
 */
function wpr_translate_seo_normalize_translation_map( $map ) {
    $normalized = array();

    if ( ! is_array( $map ) ) {
        // Return empty array for invalid input.
        return $normalized;
    }

    foreach ( $map as $code => $id ) {
        $key = sanitize_key( $code );

        if ( '' === $key ) {
            continue;
        }

        // Store integer IDs for consistent access.
        $normalized[ $key ] = (int) $id;
    }

    return $normalized;
}

/**
 * Locate a translation ID in the map.
 */
function wpr_translate_seo_pick_translation_id( $translations, $language_code ) {
    $language_code = sanitize_key( $language_code );

    if ( '' === $language_code ) {
        // No language code means no translation can be resolved.
        return 0;
    }

    return empty( $translations[ $language_code ] ) ? 0 : (int) $translations[ $language_code ];
}

/**
 * Resolve a translated post permalink.
 */
function wpr_translate_seo_get_post_url( $post_id, $language_code ) {
    $post_id       = absint( $post_id );
    $language_code = sanitize_key( $language_code );

    if ( ! $post_id ) {
        // Invalid post ID.
        return '';
    }

    if ( function_exists( 'wpr_translation_get_post_language_permalink' ) && '' !== $language_code ) {
        // Try the translation-aware permalink first.
        $url = wpr_translation_get_post_language_permalink( $post_id, $language_code );

        if ( '' !== $url ) {
            return $url;
        }
    }

    return get_permalink( $post_id );
}

/**
 * Resolve a translated term permalink.
 */
function wpr_translate_seo_get_term_url( $term_id, $taxonomy ) {
    $term_id  = absint( $term_id );
    $taxonomy = sanitize_key( $taxonomy );

    if ( ! $term_id || '' === $taxonomy ) {
        // Invalid term inputs.
        return '';
    }

    // Build the term link using core helpers.
    $link = get_term_link( $term_id, $taxonomy );

    return ( $link && ! is_wp_error( $link ) ) ? $link : '';
}

/**
 * Build the hreflang value for a language payload.
 */
function wpr_translate_seo_get_hreflang_value( $language ) {
    if ( empty( $language ) || ! is_array( $language ) ) {
        // No language payload means no hreflang value.
        return '';
    }

    if ( ! empty( $language['locale'] ) ) {
        // Prefer locale when present.
        return strtolower( str_replace( '_', '-', $language['locale'] ) );
    }

    if ( ! empty( $language['code'] ) ) {
        // Fall back to the language code.
        return strtolower( $language['code'] );
    }

    if ( ! empty( $language['slug'] ) ) {
        // Use the slug as a final fallback.
        return strtolower( $language['slug'] );
    }

    return '';
}

/**
 * Return the default language descriptor.
 */
function wpr_translate_seo_get_default_language( $languages ) {
    foreach ( $languages as $language ) {
        if ( ! empty( $language['is_default'] ) ) {
            // Return the explicitly configured default language.
            return $language;
        }
    }

    // Fall back to the first language entry.
    return empty( $languages[0] ) ? array() : $languages[0];
}
