<?php
/**
 * Column rendering for the admin post list translations UI.
 *
 * @package WPR_Translate
 */

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

/**
 * Adds the language column to the posts table.
 *
 * @param array $columns Existing column list.
 *
 * @return array
 */
function wpr_translation_register_language_column( $columns ) {
    if ( isset( $columns['wpr_language'] ) ) {
        // Column already registered.
        return $columns;
    }

    $label = __( 'Language', 'wpr-translate' );

    // Preserve the checkbox column at the top if it exists.
    if ( isset( $columns['cb'] ) ) {
        $checkbox = $columns['cb'];
        unset( $columns['cb'] );

        return array_merge(
            array(
                'cb'            => $checkbox,
                'wpr_language' => $label,
            ),
            $columns
        );
    }

    return array_merge(
        array( 'wpr_language' => $label ),
        $columns
    );
}

/**
 * Adds the translations column to the posts table.
 *
 * @param array $columns Existing column list.
 *
 * @return array
 */
function wpr_translation_register_translations_column( $columns ) {
    // Translation links are rendered in the language column.
    return $columns;
}

/**
 * Outputs the column content.
 *
 * @param string $column  Current column key.
 * @param int    $post_id Current post ID.
 */
function wpr_translation_render_translations_column( $column, $post_id ) {
    if ( 'wpr_translations' !== $column ) {
        // Only render the translations column here.
        return;
    }

    $languages = wpr_translation_get_active_languages();

    if ( empty( $languages ) ) {
        // No languages configured.
        return;
    }

    $post_type    = get_post_type( $post_id );
    $element_type = wpr_translation_get_element_type( $post_type );

    // Fetch the translation group for this post.
    $translations     = wpr_translation_get_translation_group( $post_id, $element_type );
    $translation_map  = $translations['translations'];
    $current_language = $translations['source_language'];

    if ( ! in_array( $post_id, $translation_map, true ) ) {
        // Ensure the current post appears in the translation map.
        if ( ! $current_language ) {
            $current_language = wpr_translation_get_default_language_code( $languages );
        }

        if ( $current_language ) {
            $translation_map[ $current_language ] = $post_id;
        }
    }

    $active_map = array();

    foreach ( $translation_map as $language_code => $translated_post_id ) {
        if ( wpr_translation_is_translation_post_available( $translated_post_id ) ) {
            // Keep only available translations.
            $active_map[ $language_code ] = (int) $translated_post_id;
        }
    }

    $items = array();

    foreach ( $languages as $language ) {
        $code       = $language['code'];
        $label_name = ! empty( $language['name'] ) ? $language['name'] : strtoupper( $code );

        if ( isset( $active_map[ $code ] ) ) {
            // Provide a view link for existing translations.
            $target_post_id = (int) $active_map[ $code ];
            $view_link      = function_exists( 'wpr_translation_get_post_language_permalink' ) ? wpr_translation_get_post_language_permalink( $target_post_id, $code ) : '';

            if ( $view_link ) {
                $items[] = sprintf(
                    '<a href="%1$s" class="wpr-translation-link wpr-translation-link-view" title="%3$s">%2$s</a>',
                    esc_url( $view_link ),
                    esc_html( sprintf( __( 'View %s', 'wpr-translate' ), strtolower( $code ) ) ),
                    esc_attr( $label_name )
                );
            }

            continue;
        }

        // Build an add-translation link for missing translations.
        $url = wp_nonce_url(
            add_query_arg(
                array(
                    'action'   => 'wpr_add_translation',
                    'post_id'  => $post_id,
                    'language' => $code,
                ),
                admin_url( 'admin.php' )
            ),
            wpr_translation_get_translation_nonce_action( $post_id, $code )
        );

        /* translators: %s: language code. */
        $label   = sprintf( __( 'Add %s', 'wpr-translate' ), strtolower( $code ) );
        $items[] = sprintf(
            '<a href="%1$s" class="wpr-translation-link wpr-translation-link-add">%2$s</a>',
            esc_url( $url ),
            esc_html( $label )
        );
    }

    if ( empty( $items ) ) {
        // Nothing to show.
        return;
    }

    $rows = array();

    foreach ( $items as $item ) {
        $rows[] = '<div class="wpr-translation-item">' . $item . '</div>';
    }

    echo '<div class="wpr-translation-links">' . implode( '', $rows ) . '</div>';
}

/**
 * Outputs the language column content.
 *
 * @param string $column  Current column key.
 * @param int    $post_id Current post ID.
 */
function wpr_translation_render_language_column( $column, $post_id ) {
    if ( 'wpr_language' !== $column ) {
        // Only render the language column here.
        return;
    }

    $post = get_post( $post_id );

    if ( ! $post ) {
        // Missing post means unknown language.
        echo esc_html__( 'Unknown', 'wpr-translate' );
        return;
    }

    // Resolve the stored language code for the row.
    $language_code = wpr_translation_resolve_post_language_code( $post_id, $post->post_type );

    if ( '' === $language_code ) {
        // Fall back to default language when missing.
        $default_language = function_exists( 'wpr_translate_get_default_language' ) ? wpr_translate_get_default_language() : null;

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

    $language_name = '';
    $flag_code     = '';

    if ( '' !== $language_code && function_exists( 'wpr_translate_get_language' ) ) {
        $language_data = wpr_translate_get_language( $language_code );

        if ( is_array( $language_data ) ) {
            if ( ! empty( $language_data['name'] ) ) {
                $language_name = sanitize_text_field( $language_data['name'] );
            }

            if ( ! empty( $language_data['flag'] ) ) {
                $flag_code = sanitize_key( $language_data['flag'] );
            }
        }
    }

    if ( '' === $flag_code && '' !== $language_code ) {
        // Fall back to using the language code when no explicit flag mapping exists.
        $flag_code = sanitize_key( $language_code );
    }

    if ( '' === $language_name && '' !== $language_code ) {
        // Use uppercase code when no name is configured.
        $language_name = strtoupper( $language_code );
    }

    if ( '' === $language_name ) {
        // Fallback label when no language is set.
        $language_name = esc_html__( 'Unassigned', 'wpr-translate' );
    }

    $flag_url = '';

    if ( '' !== $flag_code && defined( 'WPR_TRANSLATE_URL' ) ) {
        // Build the flag image URL.
        $flag_url = esc_url_raw( WPR_TRANSLATE_URL . 'assets/img/flags/4x3/' . $flag_code . '.svg' );
    }

    $flag_alt = sprintf( __( '%s flag', 'wpr-translate' ), $language_name );

    echo '<div class="wpr-language-column">';
    echo '<div class="wpr-language-column-top">';

    if ( '' !== $flag_url ) {
        printf(
            '<div class="wpr-language-column-flag"><img src="%1$s" alt="%2$s" width="18" height="14" loading="lazy" decoding="async" /></div>',
            esc_url( $flag_url ),
            esc_attr( $flag_alt )
        );
    }

    printf(
        '<div class="wpr-language-column-label">%s</div>',
        esc_html( $language_name )
    );

    echo '</div>';

    ob_start();
    wpr_translation_render_translations_column( 'wpr_translations', $post_id );
    $translations_markup = trim( (string) ob_get_clean() );

    if ( '' !== $translations_markup ) {
        // Print translation links under the language label.
        echo $translations_markup; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    if ( function_exists( 'wpr_translation_render_post_title_links_payload' ) ) {
        // Store title links markup for JS placement under the title column.
        wpr_translation_render_post_title_links_payload( $post_id );
    }

    echo '</div>';
}
