<?php
/**
 * String translation view.
 *
 * @var array $data Data for the view.
 *
 * @package WPR_Translate
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
// Initialize view-scoped caches and normalized data.
$wpr_translate_domain_option_cache = array();
$strings        = isset( $data['strings'] ) && is_array( $data['strings'] ) ? $data['strings'] : array();
$languages      = isset( $data['languages'] ) && is_array( $data['languages'] ) ? $data['languages'] : array();
$filters        = isset( $data['filters'] ) && is_array( $data['filters'] ) ? $data['filters'] : array();
$domains        = isset( $data['domains'] ) && is_array( $data['domains'] ) ? $data['domains'] : array();
$pagination     = isset( $data['pagination'] ) && is_array( $data['pagination'] ) ? $data['pagination'] : array();
$page_title     = isset( $data['page_title'] ) && '' !== $data['page_title'] ? $data['page_title'] : __( 'String Translation', 'wpr-translate' );
$page_desc      = isset( $data['page_description'] ) && '' !== $data['page_description'] ? $data['page_description'] : __( 'Scan your theme and active plugins for gettext strings, then translate them across all languages.', 'wpr-translate' );
$page_slug      = isset( $data['page_slug'] ) && '' !== $data['page_slug'] ? $data['page_slug'] : 'wpr-translate-strings';
$default_language_code = isset( $data['default_language_code'] ) ? $data['default_language_code'] : '';
$form_action            = isset( $data['form_action'] ) ? $data['form_action'] : admin_url( 'admin.php?page=wpr-translate-strings' );
$range_start            = isset( $data['range_start'] ) ? (int) $data['range_start'] : 0;
$range_end              = isset( $data['range_end'] ) ? (int) $data['range_end'] : 0;
$displayed              = isset( $data['displayed'] ) ? (int) $data['displayed'] : count( $strings );
$status_filter = isset( $filters['status'] ) ? $filters['status'] : 'all';
$search_term   = isset( $filters['search'] ) ? $filters['search'] : '';
$domain_filter = isset( $filters['domain'] ) ? $filters['domain'] : '';
$current_page = isset( $pagination['current_page'] ) ? (int) $pagination['current_page'] : 1;
$total_pages  = isset( $pagination['total_pages'] ) ? (int) $pagination['total_pages'] : 1;
$total_items  = isset( $pagination['total'] ) ? (int) $pagination['total'] : count( $strings );
$admin_option_domain = sanitize_key( (string) get_option( 'wpr_translate_theme_admin_strings_domain', '' ) );
?>
<div class="wrap wpr-translate-admin">
    <h1><?php echo esc_html( $page_title ); ?></h1>
    <?php settings_errors( 'wpr_translate_strings' ); ?>
    <div class="wpr-card wpr-string-scan">
        <p class="wpr-string-scan-description"><?php echo esc_html( $page_desc ); ?></p>
        <div class="wpr-string-actions">
            <form method="post">
                <?php wp_nonce_field( 'wpr_translate_scan_strings', 'wpr_translate_scan_nonce' ); ?>
                <p>
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e( 'Scan for translations', 'wpr-translate' ); ?>
                    </button>
                </p>
            </form>
            <form method="post">
                <?php wp_nonce_field( 'wpr_translate_generate_files', 'wpr_translate_generate_nonce' ); ?>
                <p>
                    <button type="submit" class="button button-secondary">
                        <?php esc_html_e( 'Generate translation files', 'wpr-translate' ); ?>
                    </button>
                </p>
            </form>
            <form method="post">
                <?php wp_nonce_field( 'wpr_translate_reset_strings', 'wpr_translate_reset_nonce' ); ?>
                <p>
                    <button type="submit" class="button button-secondary">
                        <?php esc_html_e( 'Clear stored translations', 'wpr-translate' ); ?>
                    </button>
                </p>
            </form>
        </div>
        <div class="wpr-string-auto-translate">
            <label for="wpr-string-auto-translate-language" class="wpr-string-auto-translate-label"><?php esc_html_e( 'Automatic translate strings', 'wpr-translate' ); ?></label>
            <div class="wpr-string-auto-translate-row">
                <select id="wpr-string-auto-translate-domain">
                    <option value=""><?php esc_html_e( 'All domains', 'wpr-translate' ); ?></option>
                    <?php foreach ( $domains as $context_value => $label ) : ?>
                        <option value="<?php echo esc_attr( $context_value ); ?>" <?php selected( $domain_filter, $context_value ); ?>><?php echo esc_html( $label ); ?></option>
                    <?php endforeach; ?>
                </select>
                <select id="wpr-string-auto-translate-language">
                    <option value=""><?php esc_html_e( 'Select language', 'wpr-translate' ); ?></option>
                    <?php foreach ( $languages as $language ) : ?>
                        <?php
                        $code = isset( $language['code'] ) ? strtolower( sanitize_key( $language['code'] ) ) : '';
                        $name = isset( $language['name'] ) ? sanitize_text_field( $language['name'] ) : strtoupper( $code );
                        if ( '' === $code || $code === strtolower( sanitize_key( $default_language_code ) ) ) {
                            continue;
                        }
                        ?>
                        <option value="<?php echo esc_attr( $code ); ?>"><?php echo esc_html( $name ); ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="button" class="button button-secondary" id="wpr-string-auto-translate-button"><?php esc_html_e( 'Automatic Translate', 'wpr-translate' ); ?></button>
            </div>
            <div id="wpr-string-auto-translate-status" class="wpr-string-auto-translate-status"></div>
        </div>
        <div class="wpr-string-actions-note wpr-hidden">
            <?php esc_html_e( 'Please generate the translation files after you made all the changes. Otherwise the new translations will not be loaded.', 'wpr-translate' ); ?>
        </div>
    </div>
    <div class="wpr-card wpr-string-filters">
        <form method="get" class="wpr-string-filter-form">
            <input type="hidden" name="page" value="<?php echo esc_attr( $page_slug ); ?>" />
            <div class="wpr-filter-row">
                <label for="wpr-filter-status"><?php esc_html_e( 'Show', 'wpr-translate' ); ?></label>
                <select id="wpr-filter-status" name="status">
                    <option value="all" <?php selected( 'all', $status_filter ); ?>><?php esc_html_e( 'All strings', 'wpr-translate' ); ?></option>
                    <option value="untranslated" <?php selected( 'untranslated', $status_filter ); ?>><?php esc_html_e( 'Not translated strings', 'wpr-translate' ); ?></option>
                    <option value="translated" <?php selected( 'translated', $status_filter ); ?>><?php esc_html_e( 'Translated strings', 'wpr-translate' ); ?></option>
                </select>
                <label for="wpr-filter-search"><?php esc_html_e( 'Search', 'wpr-translate' ); ?></label>
                <input type="search" id="wpr-filter-search" name="s" value="<?php echo esc_attr( $search_term ); ?>" placeholder="<?php esc_attr_e( 'Search strings...', 'wpr-translate' ); ?>" />
                <label for="wpr-filter-domain"><?php esc_html_e( 'Domain', 'wpr-translate' ); ?></label>
                <select id="wpr-filter-domain" name="domain">
                    <option value="" <?php selected( '', $domain_filter ); ?>><?php esc_html_e( 'All domains', 'wpr-translate' ); ?></option>
                    <?php foreach ( $domains as $context_value => $label ) : ?>
                        <option value="<?php echo esc_attr( $context_value ); ?>" <?php selected( $context_value, $domain_filter ); ?>><?php echo esc_html( $label ); ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="button">
                    <?php esc_html_e( 'Filter', 'wpr-translate' ); ?>
                </button>
            </div>
        </form>
    </div>
    <div class="wpr-card">
        <?php if ( empty( $strings ) ) : ?>
            <p><?php esc_html_e( 'No strings found for the selected filters.', 'wpr-translate' ); ?></p>
        <?php else : ?>
            <?php if ( $total_items > 0 && $displayed > 0 ) : ?>
                <div class="wpr-string-results-meta">
                    <div class="wpr-string-count">
                        <?php
                        echo esc_html(
                            sprintf(
                                /* translators: 1: starting item number, 2: ending item number, 3: total results count */
                                __( 'Showing %1$d–%2$d of %3$d strings', 'wpr-translate' ),
                                $range_start,
                                $range_end,
                                $total_items
                            )
                        );
                        ?>
                    </div>
                </div>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url( $form_action ); ?>" class="wpr-string-bulk-form">
                <?php wp_nonce_field( 'wpr_translate_delete_strings', 'wpr_translate_delete_nonce' ); ?>
                <input type="hidden" name="strings_page" value="<?php echo esc_attr( $current_page ); ?>" />
                <div class="wpr-strings-grid">
                    <div class="wpr-strings-row wpr-strings-header">
                        <div class="wpr-strings-cell wpr-cell-select">
                            <input type="checkbox" id="cb-select-all-1" />
                        </div>
                        <div class="wpr-strings-cell wpr-cell-domain"><?php esc_html_e( 'Domain', 'wpr-translate' ); ?></div>
                        <div class="wpr-strings-cell wpr-cell-original"><?php esc_html_e( 'String', 'wpr-translate' ); ?></div>
                        <?php foreach ( $languages as $language ) :
                            $code = isset( $language['code'] ) ? $language['code'] : '';
                            if ( '' === $code ) {
                                continue;
                            }
                            ?>
                            <div class="wpr-strings-cell wpr-cell-language" data-language="<?php echo esc_attr( $code ); ?>"><?php echo esc_html( strtoupper( $code ) ); ?></div>
                        <?php endforeach; ?>
                    </div>
                    <?php foreach ( $strings as $string ) :
                        $context     = isset( $string['context'] ) ? (string) $string['context'] : '';
                        $name        = isset( $string['name'] ) ? (string) $string['name'] : '';
                        $domain      = isset( $string['domain_label'] ) ? $string['domain_label'] : '';
                        $value       = isset( $string['value'] ) ? $string['value'] : '';
                        $display_val = trim( (string) $value );
                        $use_live_option_default = ( '' !== $admin_option_domain && sanitize_key( $context ) === $admin_option_domain );
                        if ( $use_live_option_default && ! array_key_exists( $context, $wpr_translate_domain_option_cache ) ) {
                            $option_value = get_option( $context, array() );
                            if ( ! is_array( $option_value ) ) {
                                $option_value = array();
                            }
                            $wpr_translate_domain_option_cache[ $context ] = $option_value;
                        }
                        $context_defaults = array();
                        if ( $use_live_option_default && isset( $wpr_translate_domain_option_cache[ $context ] ) ) {
                            $context_defaults = $wpr_translate_domain_option_cache[ $context ];
                        }
                        $default_language_value = wpr_translate_admin_get_option_value_by_path( $context_defaults, $name );
                        // Keep empty values blank for translation inputs but show the key label in the list.
                        // Add sidebar labels for widget instance strings when available.
                        $sidebar_label = isset( $string['sidebar_label'] ) ? sanitize_text_field( $string['sidebar_label'] ) : '';
                        $display_label_source = $name;
                        $display_label        = $display_label_source;
                        if ( '' !== $sidebar_label ) {
                            $display_label = sprintf( '%s (%s)', $display_label_source, $sidebar_label );
                        }
                        $translations = isset( $string['translations'] ) && is_array( $string['translations'] ) ? $string['translations'] : array();
                        $payload      = array(
                            'context' => $context,
                            'name'    => $name,
                        );
                        $encoded_value = wp_json_encode( $payload );
                        if ( false !== $encoded_value ) {
                            $encoded_value = base64_encode( $encoded_value );
                        } else {
                            $encoded_value = '';
                        }
                        $aria_label_source = trim( (string) $value );
                        if ( '' === $aria_label_source ) {
                            $aria_label_source = $domain ? $domain : $name;
                        }
                        ?>
                        <div class="wpr-strings-row" data-context="<?php echo esc_attr( $context ); ?>" data-name="<?php echo esc_attr( $name ); ?>">
                            <div class="wpr-strings-cell wpr-cell-select">
                                <input type="checkbox" name="strings[]" value="<?php echo esc_attr( $encoded_value ); ?>" aria-label="<?php echo esc_attr( sprintf( __( 'Select string %s', 'wpr-translate' ), $aria_label_source ) ); ?>" />
                            </div>
                            <div class="wpr-strings-cell wpr-cell-domain"><?php echo esc_html( $domain ); ?></div>
                            <div class="wpr-strings-cell wpr-cell-original">
                                <div class="wpr-string-value"><?php echo esc_html( $display_label ); ?></div>
                            </div>
                            <?php foreach ( $languages as $language ) :
                                $code = isset( $language['code'] ) ? $language['code'] : '';
                                if ( '' === $code ) {
                                    continue;
                                }
                                $translation = isset( $translations[ $code ] ) ? $translations[ $code ] : '';
                                $is_default  = ( $code === $default_language_code );
                                if ( $is_default ) {
                                    if ( $use_live_option_default ) {
                                        // Keep admin-option strings synced with the current live option value.
                                        $translation = (string) $default_language_value;
                                    } else {
                                        // For gettext/widget domains, show the source string value as default language.
                                        $translation = (string) $value;
                                    }
                                }
                                $status_label = 'translated';
                                if ( ! $is_default ) {
                                    $plain_translation = trim( wp_strip_all_tags( (string) $translation ) );
                                    if ( '' === $plain_translation ) {
                                        $status_label = 'untranslated';
                                    }
                                }
                                $language_label = isset( $language['name'] ) ? $language['name'] : '';
                                if ( '' === $language_label ) {
                                    $language_label = strtoupper( $code );
                                }
                                $textarea_aria_label = sprintf(
                                    /* translators: 1: language label, 2: source string */
                                    __( '%1$s translation for %2$s', 'wpr-translate' ),
                                    $language_label,
                                    $aria_label_source
                                );
                                $language_class = 'wpr-language-' . sanitize_html_class( $code );
                                ?>
                                <div class="wpr-strings-cell wpr-cell-translation <?php echo esc_attr( $language_class ); ?>" data-language="<?php echo esc_attr( $code ); ?>" data-status="<?php echo esc_attr( $status_label ); ?>">
                                    <textarea
                                        class="wpr-translation-input"
                                        data-context="<?php echo esc_attr( $context ); ?>"
                                        data-name="<?php echo esc_attr( $name ); ?>"
                                        data-language="<?php echo esc_attr( $code ); ?>"
                                        rows="3"
                                        placeholder="<?php esc_attr_e( 'Enter translation…', 'wpr-translate' ); ?>"
                                        aria-label="<?php echo esc_attr( $textarea_aria_label ); ?>"
                                    ><?php echo esc_textarea( $translation ); ?></textarea>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endforeach; ?>
                    <div class="wpr-strings-row wpr-strings-footer">
                        <div class="wpr-strings-cell wpr-cell-select">
                            <input type="checkbox" id="cb-select-all-2" />
                        </div>
                        <div class="wpr-strings-cell wpr-cell-domain" aria-hidden="true"></div>
                        <div class="wpr-strings-cell wpr-cell-original" aria-hidden="true"></div>
                        <?php foreach ( $languages as $language ) :
                            $code = isset( $language['code'] ) ? $language['code'] : '';
                            if ( '' === $code ) {
                                continue;
                            }
                            ?>
                            <div class="wpr-strings-cell wpr-cell-language" data-language="<?php echo esc_attr( $code ); ?>" aria-hidden="true"></div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="wpr-string-bulk-actions">
                    <button type="submit" class="button button-secondary">
                        <?php esc_html_e( 'Delete selected translations', 'wpr-translate' ); ?>
                    </button>
                </div>
            </form>
            <?php
            $pagination_links = array();
            if ( $total_pages > 1 ) {
                $pagination_args = array(
                    'page' => 'wpr-translate-strings',
                );
                if ( 'all' !== $status_filter ) {
                    $pagination_args['status'] = $status_filter;
                }
                if ( '' !== $search_term ) {
                    $pagination_args['s'] = $search_term;
                }
                if ( '' !== $domain_filter ) {
                    $pagination_args['domain'] = $domain_filter;
                }
                $base_url = add_query_arg( $pagination_args, admin_url( 'admin.php' ) );
                $pagination_links = paginate_links(
                    array(
                        'base'      => add_query_arg( 'strings_page', '%#%', $base_url ),
                        'format'    => '',
                        'current'   => max( 1, $current_page ),
                        'total'     => max( 1, $total_pages ),
                        'type'      => 'array',
                        'prev_text' => __( 'Previous', 'wpr-translate' ),
                        'next_text' => __( 'Next', 'wpr-translate' ),
                    )
                );
            }
            ?>
            <?php if ( ! empty( $pagination_links ) ) : ?>
                <div class="wpr-pagination">
                    <?php foreach ( $pagination_links as $link ) : ?>
                        <span class="wpr-pagination-item"><?php echo wp_kses_post( $link ); ?></span>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

