<?php
/**
 * Title column helpers for translated links on admin post lists.
 *
 * @package WPR_Translate
 */

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

/**
 * Builds front-end translation links for a post list title row.
 *
 * @param int $post_id Post identifier.
 *
 * @return string
 */
function wpr_translation_build_post_title_translation_links_markup( $post_id ) {
    $post_id = absint( $post_id );
    $post    = get_post( $post_id );

    if ( ! $post instanceof WP_Post ) {
        // Missing post data means nothing to render.
        return '';
    }

    $languages = wpr_translation_get_active_languages();

    if ( empty( $languages ) ) {
        // No language setup means no translation links.
        return '';
    }

    $element_type = wpr_translation_get_element_type( $post->post_type );
    $group        = wpr_translation_get_translation_group( $post_id, $element_type );
    $map          = isset( $group['translations'] ) && is_array( $group['translations'] ) ? $group['translations'] : array();
    $source_code  = isset( $group['source_language'] ) ? sanitize_key( $group['source_language'] ) : '';

    if ( empty( $map ) || '' === $source_code || ! isset( $map[ $source_code ] ) ) {
        // Missing translation map details.
        return '';
    }

    $source_post_id = (int) $map[ $source_code ];
    $rows           = array();

    if ( $source_post_id === $post_id ) {
        // Original post: render front-end links for translated posts.
        foreach ( $map as $language_code => $translated_post_id ) {
            $language_code      = sanitize_key( $language_code );
            $translated_post_id = (int) $translated_post_id;

            if ( $translated_post_id <= 0 || $translated_post_id === $post_id ) {
                continue;
            }

            if ( ! wpr_translation_is_translation_post_available( $translated_post_id ) ) {
                continue;
            }

            $translated_title = get_the_title( $translated_post_id );

            if ( '' === trim( (string) $translated_title ) ) {
                continue;
            }

            $frontend_url = '';

            if ( function_exists( 'wpr_translation_get_post_language_permalink' ) ) {
                $frontend_url = wpr_translation_get_post_language_permalink( $translated_post_id, $language_code );
            }

            if ( '' === $frontend_url ) {
                $frontend_url = get_permalink( $translated_post_id );
            }

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

            $label  = strtolower( $language_code ) . ': ' . $translated_title;
            $rows[] = sprintf(
                '<div class="wpr-title-translation-row"><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a></div>',
                esc_url( $frontend_url ),
                esc_html( $label )
            );
        }
    } else {
        // Translated post: render the source post front-end link.
        if ( ! wpr_translation_is_translation_post_available( $source_post_id ) ) {
            return '';
        }

        $source_title = get_the_title( $source_post_id );

        if ( '' === trim( (string) $source_title ) ) {
            return '';
        }

        $source_url = '';

        if ( function_exists( 'wpr_translation_get_post_language_permalink' ) ) {
            $source_url = wpr_translation_get_post_language_permalink( $source_post_id, $source_code );
        }

        if ( '' === $source_url ) {
            $source_url = get_permalink( $source_post_id );
        }

        if ( '' === $source_url ) {
            return '';
        }

        $rows[] = sprintf(
            '<div class="wpr-title-translation-row"><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a></div>',
            esc_url( $source_url ),
            esc_html( 'source: ' . $source_title )
        );
    }

    if ( empty( $rows ) ) {
        // Nothing to display.
        return '';
    }

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

/**
 * Prints hidden title links payload in the language column.
 *
 * @param int $post_id Post identifier.
 */
function wpr_translation_render_post_title_links_payload( $post_id ) {
    $post_id = absint( $post_id );
    $markup  = wpr_translation_build_post_title_translation_links_markup( $post_id );

    if ( '' === $markup ) {
        // Skip rows without front-end translation links.
        return;
    }

    printf(
        '<div class="wpr-title-translation-links-payload" data-post-id="%1$d" hidden>%2$s</div>',
        absint( $post_id ),
        wp_kses_post( $markup )
    );
}

/**
 * Moves title translation payloads under the title links in list tables.
 */
function wpr_translation_move_title_translation_links_under_title() {
    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

    if ( ! $screen instanceof WP_Screen || 'edit' !== $screen->base ) {
        // Only run on post list screens.
        return;
    }

    echo '<script>';
    echo 'document.addEventListener("DOMContentLoaded",function(){';
    echo 'document.querySelectorAll("tr[id^=\'post-\']").forEach(function(row){';
    echo 'var payload=row.querySelector("td.column-wpr_language .wpr-title-translation-links-payload");';
    echo 'if(!payload){return;}';
    echo 'var titleStrong=row.querySelector("td.column-title strong");';
    echo 'if(!titleStrong){return;}';
    echo 'if(row.querySelector("td.column-title .wpr-title-translation-links")){return;}';
    echo 'titleStrong.insertAdjacentHTML("afterend",payload.innerHTML);';
    echo '});';
    echo '});';
    echo '</script>';
}
add_action( 'admin_footer-edit.php', 'wpr_translation_move_title_translation_links_under_title' );
/**
 * Sets language ordering as the default sort on post list tables.
 *
 * @param WP_Query $query Current query.
 */
function wpr_translation_set_default_language_ordering( $query ) {
    if ( ! is_admin() || ! $query->is_main_query() ) {
        // Only run on the main admin query.
        return;
    }
    global $pagenow;
    if ( 'edit.php' !== $pagenow ) {
        // Only run on post list tables.
        return;
    }
    if ( isset( $_GET['orderby'] ) || $query->get( 'orderby' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        // Respect explicit orderby requests from the UI.
        return;
    }
    $post_type = $query->get( 'post_type' );
    if ( is_array( $post_type ) ) {
        $post_type = reset( $post_type );
    }
    if ( empty( $post_type ) ) {
        $post_type = 'post';
    }
    if ( 'attachment' === $post_type ) {
        // Skip media lists.
        return;
    }
    // Default to ordering by language code.
    $query->set( 'orderby', 'wpr_language' );
    $query->set( 'order', 'ASC' );
}
add_action( 'pre_get_posts', 'wpr_translation_set_default_language_ordering', 5 );
/**
 * Registers the language column as sortable.
 *
 * @param array $columns Sortable columns.
 *
 * @return array
 */
function wpr_translation_register_sortable_language_column( $columns ) {
    if ( isset( $columns['wpr_language'] ) ) {
        // Reuse the language column key for sorting.
        $columns['wpr_language'] = 'wpr_language';
    }

    return $columns;
}

/**
 * Applies SQL ordering by language code on post list screens.
 *
 * @param array    $clauses Query SQL clauses.
 * @param WP_Query $query   Current query.
 *
 * @return array
 */
function wpr_translation_apply_language_orderby_clause( $clauses, $query ) {
    if ( ! is_admin() || ! $query->is_main_query() ) {
        // Only sort the main admin query.
        return $clauses;
    }

    global $pagenow;

    if ( 'edit.php' !== $pagenow ) {
        // Only run on post list tables.
        return $clauses;
    }

    if ( 'wpr_language' !== $query->get( 'orderby' ) ) {
        // Apply only when language sorting is requested.
        return $clauses;
    }

    $post_type = $query->get( 'post_type' );

    if ( is_array( $post_type ) ) {
        $post_type = reset( $post_type );
    }

    if ( empty( $post_type ) ) {
        $post_type = 'post';
    }

    if ( 'attachment' === $post_type ) {
        // Attachments are excluded from translation sorting.
        return $clauses;
    }

    global $wpdb;

    $table       = $wpdb->prefix . 'wpestate_translation_translations';
    $element_type = wpr_translation_get_element_type( $post_type );
    $alias       = 'wpr_sort_language';

    if ( false === strpos( $clauses['join'], $alias ) ) {
        // Join translation rows for the current post type.
        $clauses['join'] .= $wpdb->prepare(
            " LEFT JOIN {$table} AS {$alias} ON ({$wpdb->posts}.ID = {$alias}.element_id AND {$alias}.element_type = %s)",
            $element_type
        );
    }

    $languages    = wpr_translation_get_active_languages();
    $default_code = sanitize_key( wpr_translation_get_default_language_code( $languages ) );
    $order        = strtoupper( (string) $query->get( 'order' ) );

    if ( 'DESC' !== $order ) {
        // Default to ascending alphabetical order.
        $order = 'ASC';
    }

    if ( '' === $default_code ) {
        $default_code = 'zzzz';
    }

    $language_sql      = "COALESCE(NULLIF({$alias}.language_code, ''), '" . esc_sql( $default_code ) . "')";
    $clauses['orderby'] = "{$language_sql} {$order}, {$wpdb->posts}.post_title {$order}";

    return $clauses;
}
add_filter( 'posts_clauses', 'wpr_translation_apply_language_orderby_clause', 10, 2 );
