<?php
/**
 * Language-Voice Mapping Section for PRO plugin
 * This file is included in the voices.php page when PRO is active
 * Supports both Weglot and WPML language integrations
 *
 * @link       https://mementor.no
 * @since      1.1.0
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS_Pro/admin/partials
 */

// Prevent direct access to this file
if (!defined('ABSPATH')) {
    exit;
}

// Check if Weglot integration is enabled
$weglot_enabled = get_option('mementor_tts_weglot_enabled', '0');
$weglot_plugin_active = function_exists('weglot_get_current_language');

// Check if WPML integration is enabled
$wpml_enabled = get_option('mementor_tts_wpml_enabled', '0');
$wpml_plugin_active = defined('ICL_SITEPRESS_VERSION');

// Determine which integrations are active
$has_weglot = $weglot_plugin_active && $weglot_enabled === '1';
$has_wpml = $wpml_plugin_active && $wpml_enabled === '1';
$has_any_integration = $has_weglot || $has_wpml;

// Get available languages from active integrations
$available_languages = array();
$original_language = '';
$active_integration_name = '';

// Weglot languages
if ($has_weglot) {
    $active_integration_name = 'Weglot';
    if (function_exists('weglot_get_original_language')) {
        $original_language = weglot_get_original_language();
        // Weglot returns a string for original language
        if (is_object($original_language) && method_exists($original_language, 'getInternalCode')) {
            $original_language = $original_language->getInternalCode();
        } elseif (is_object($original_language)) {
            $original_language = (string) $original_language;
        }
        // If it's already a string, use it as-is
    }
    if (function_exists('weglot_get_destination_languages')) {
        $dest_languages = weglot_get_destination_languages();
        // Weglot returns array of arrays with 'language_to' key
        if (is_array($dest_languages)) {
            foreach ($dest_languages as $lang) {
                if (is_array($lang) && isset($lang['language_to'])) {
                    // Weglot format: array with 'language_to' key
                    $available_languages[] = $lang['language_to'];
                } elseif (is_object($lang) && method_exists($lang, 'getInternalCode')) {
                    // Legacy object format
                    $available_languages[] = $lang->getInternalCode();
                } elseif (is_object($lang)) {
                    $available_languages[] = (string) $lang;
                } elseif (is_string($lang)) {
                    $available_languages[] = $lang;
                }
            }
        }
    }
    // Add original language first so it appears at the top of the table
    if (!empty($original_language) && !in_array($original_language, $available_languages)) {
        array_unshift($available_languages, $original_language);
    }
}

// WPML languages
if ($has_wpml) {
    if (empty($active_integration_name)) {
        $active_integration_name = 'WPML';
    } else {
        $active_integration_name .= ' + WPML';
    }

    $wpml_default_language = apply_filters('wpml_default_language', null);
    if (empty($original_language) && !empty($wpml_default_language)) {
        $original_language = $wpml_default_language;
    }

    $wpml_all_languages = apply_filters('wpml_active_languages', null, array('skip_missing' => 0));
    if (is_array($wpml_all_languages)) {
        foreach ($wpml_all_languages as $lang_code => $lang_info) {
            // Include all languages (including default) - skip only duplicates
            if (!in_array($lang_code, $available_languages)) {
                $available_languages[] = $lang_code;
            }
        }
    }

    // Ensure default language is first in the list
    if (!empty($original_language) && in_array($original_language, $available_languages)) {
        $available_languages = array_diff($available_languages, array($original_language));
        array_unshift($available_languages, $original_language);
    }
}

// Get saved language-voice mappings
$language_voice_mappings = get_option('mementor_tts_language_voice_mappings', array());

// Language name mapping (including common ISO codes)
$language_names = array(
    'en' => __('English', 'text-to-speech-tts'),
    'fr' => __('French', 'text-to-speech-tts'),
    'de' => __('German', 'text-to-speech-tts'),
    'es' => __('Spanish', 'text-to-speech-tts'),
    'it' => __('Italian', 'text-to-speech-tts'),
    'pt' => __('Portuguese', 'text-to-speech-tts'),
    'nl' => __('Dutch', 'text-to-speech-tts'),
    'no' => __('Norwegian', 'text-to-speech-tts'),
    'nb' => __('Norwegian Bokmål', 'text-to-speech-tts'),
    'nn' => __('Norwegian Nynorsk', 'text-to-speech-tts'),
    'sv' => __('Swedish', 'text-to-speech-tts'),
    'da' => __('Danish', 'text-to-speech-tts'),
    'fi' => __('Finnish', 'text-to-speech-tts'),
    'pl' => __('Polish', 'text-to-speech-tts'),
    'ru' => __('Russian', 'text-to-speech-tts'),
    'ja' => __('Japanese', 'text-to-speech-tts'),
    'zh' => __('Chinese', 'text-to-speech-tts'),
    'ko' => __('Korean', 'text-to-speech-tts'),
    'ar' => __('Arabic', 'text-to-speech-tts'),
    'hi' => __('Hindi', 'text-to-speech-tts'),
    'tr' => __('Turkish', 'text-to-speech-tts'),
    'el' => __('Greek', 'text-to-speech-tts'),
    'cs' => __('Czech', 'text-to-speech-tts'),
    'hu' => __('Hungarian', 'text-to-speech-tts'),
    'ro' => __('Romanian', 'text-to-speech-tts'),
    'bg' => __('Bulgarian', 'text-to-speech-tts'),
    'uk' => __('Ukrainian', 'text-to-speech-tts'),
    'hr' => __('Croatian', 'text-to-speech-tts'),
    'sk' => __('Slovak', 'text-to-speech-tts'),
    'id' => __('Indonesian', 'text-to-speech-tts'),
    'ms' => __('Malay', 'text-to-speech-tts'),
    'vi' => __('Vietnamese', 'text-to-speech-tts'),
    'th' => __('Thai', 'text-to-speech-tts'),
    'fil' => __('Filipino', 'text-to-speech-tts'),
    'ta' => __('Tamil', 'text-to-speech-tts'),
    'he' => __('Hebrew', 'text-to-speech-tts'),
    'ca' => __('Catalan', 'text-to-speech-tts'),
    'et' => __('Estonian', 'text-to-speech-tts'),
    'lv' => __('Latvian', 'text-to-speech-tts'),
    'lt' => __('Lithuanian', 'text-to-speech-tts'),
    'sl' => __('Slovenian', 'text-to-speech-tts'),
    'sr' => __('Serbian', 'text-to-speech-tts'),
    'mk' => __('Macedonian', 'text-to-speech-tts'),
    'sq' => __('Albanian', 'text-to-speech-tts'),
    'bs' => __('Bosnian', 'text-to-speech-tts'),
    'mt' => __('Maltese', 'text-to-speech-tts'),
    'ga' => __('Irish', 'text-to-speech-tts'),
    'cy' => __('Welsh', 'text-to-speech-tts'),
    'af' => __('Afrikaans', 'text-to-speech-tts'),
    'sw' => __('Swahili', 'text-to-speech-tts'),
    'bn' => __('Bengali', 'text-to-speech-tts'),
    'ur' => __('Urdu', 'text-to-speech-tts'),
    'fa' => __('Persian', 'text-to-speech-tts'),
);

// Try to get WPML native names for any missing languages
if ($has_wpml && is_array($wpml_all_languages)) {
    foreach ($wpml_all_languages as $lang_code => $lang_info) {
        if (!isset($language_names[$lang_code]) && isset($lang_info['native_name'])) {
            $language_names[$lang_code] = $lang_info['native_name'];
        }
    }
}

/**
 * Get language name from code
 */
function mementor_tts_get_language_name($code, $language_names) {
    return isset($language_names[$code]) ? $language_names[$code] : strtoupper($code);
}
?>

<!-- Language-Voice Mapping Section (PRO) -->
<div class="mementor-tts-section mementor-tts-full-width mementor-tts-language-voice-section" style="margin-top: 30px; margin-bottom: 30px;">
    <div class="mementor-tts-card-header mementor-tts-collapsible-header" data-target="language-voice-mapping-content" style="cursor: pointer;">
        <div class="mementor-tts-card-icon">
            <?php if ($has_weglot): ?>
            <img src="<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/images/icons/weglot.svg'); ?>" alt="Weglot" style="width: 24px; height: 24px;">
            <?php else: ?>
            <span class="dashicons dashicons-translation" style="font-size: 24px; width: 24px; height: 24px; color: #2b6cb0;"></span>
            <?php endif; ?>
        </div>
        <div class="mementor-tts-card-title">
            <h3>
                <?php esc_html_e('Language-Specific Voice Settings', 'text-to-speech-tts'); ?>
                <span class="mementor-tts-pro-label">PRO</span>
                <?php if ($has_weglot): ?>
                <span class="mementor-tts-status-badge" style="background-color: #d1fae5; color: #065f46; padding: 2px 8px; border-radius: 10px; font-size: 11px; margin-left: 10px;">
                    <?php esc_html_e('Weglot Active', 'text-to-speech-tts'); ?>
                </span>
                <?php endif; ?>
                <?php if ($has_wpml): ?>
                <span class="mementor-tts-status-badge" style="background-color: #dbeafe; color: #1e40af; padding: 2px 8px; border-radius: 10px; font-size: 11px; margin-left: 10px;">
                    <?php esc_html_e('WPML Active', 'text-to-speech-tts'); ?>
                </span>
                <?php endif; ?>
            </h3>
            <p><?php esc_html_e('Configure different voices for each language. When a multilingual integration is enabled, audio will be generated using the voice assigned to each language.', 'text-to-speech-tts'); ?></p>
        </div>
        <div class="mementor-tts-card-toggle" style="margin-left: auto; padding-right: 20px;">
            <span class="dashicons dashicons-arrow-down-alt2 mementor-tts-toggle-icon"></span>
        </div>
    </div>
    <div class="mementor-tts-card-content mementor-tts-collapsible-content" id="language-voice-mapping-content" style="display: none;">

        <?php if (!$has_any_integration): ?>
        <!-- No integration enabled notice -->
        <div class="mementor-tts-notice" style="background-color: #fef3c7; border: 1px solid #fcd34d; border-radius: 8px; padding: 15px 20px; margin-bottom: 20px; display: flex; gap: 15px; align-items: flex-start;">
            <span class="dashicons dashicons-info" style="color: #d97706; font-size: 24px; width: 24px; height: 24px;"></span>
            <div>
                <strong><?php esc_html_e('Multilingual Integration Required', 'text-to-speech-tts'); ?></strong>
                <p style="margin: 5px 0 10px; color: #92400e;">
                    <?php esc_html_e('To use language-specific voices, please enable Weglot or WPML integration in the Settings page.', 'text-to-speech-tts'); ?>
                </p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-settings')); ?>" class="button button-secondary">
                    <?php esc_html_e('Go to Settings', 'text-to-speech-tts'); ?>
                </a>
            </div>
        </div>
        <?php else: ?>

        <?php if (empty($available_languages)): ?>
        <!-- No languages configured -->
        <div class="mementor-tts-notice" style="background-color: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px; padding: 15px 20px; margin-bottom: 20px; display: flex; gap: 15px; align-items: flex-start;">
            <span class="dashicons dashicons-info" style="color: #3b82f6; font-size: 24px; width: 24px; height: 24px;"></span>
            <div>
                <strong><?php esc_html_e('No Languages Detected', 'text-to-speech-tts'); ?></strong>
                <p style="margin: 5px 0 10px; color: #64748b;">
                    <?php esc_html_e('Please configure your languages in your translation plugin first. Once configured, they will appear here for voice mapping.', 'text-to-speech-tts'); ?>
                </p>
                <?php if ($has_weglot): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=weglot-settings')); ?>" class="button button-secondary">
                    <?php esc_html_e('Configure Weglot', 'text-to-speech-tts'); ?>
                </a>
                <?php endif; ?>
                <?php if ($has_wpml): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=sitepress-multilingual-cms/menu/languages.php')); ?>" class="button button-secondary">
                    <?php esc_html_e('Configure WPML', 'text-to-speech-tts'); ?>
                </a>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>

        <!-- Language-Voice Mapping Table -->
        <div class="mementor-tts-language-voice-table" style="margin-top: 20px;">
            <table class="widefat" style="border-collapse: collapse;">
                <thead>
                    <tr style="background: #f8fafc;">
                        <th style="padding: 12px 15px; text-align: left; font-weight: 600; color: #334155; width: 30%;">
                            <span class="dashicons dashicons-translation" style="vertical-align: middle; margin-right: 5px;"></span>
                            <?php esc_html_e('Language', 'text-to-speech-tts'); ?>
                        </th>
                        <th style="padding: 12px 15px; text-align: left; font-weight: 600; color: #334155; width: 50%;">
                            <span class="dashicons dashicons-microphone" style="vertical-align: middle; margin-right: 5px;"></span>
                            <?php esc_html_e('Voice ID', 'text-to-speech-tts'); ?>
                        </th>
                        <th style="padding: 12px 15px; text-align: left; font-weight: 600; color: #334155; width: 20%;">
                            <span class="dashicons dashicons-admin-generic" style="vertical-align: middle; margin-right: 5px;"></span>
                            <?php esc_html_e('Status', 'text-to-speech-tts'); ?>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($available_languages as $lang_code): ?>
                    <?php
                    $is_default_lang = ($lang_code === $original_language);
                    $saved_voice_id = isset($language_voice_mappings[$lang_code]['voice_id']) ? $language_voice_mappings[$lang_code]['voice_id'] : '';
                    $lang_name = mementor_tts_get_language_name($lang_code, $language_names);
                    ?>
                    <tr class="mementor-tts-lang-row" data-lang="<?php echo esc_attr($lang_code); ?>" style="border-bottom: 1px solid #e2e8f0;">
                        <td style="padding: 15px;">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <span class="mementor-tts-lang-badge" style="background: <?php echo $is_default_lang ? '#dbeafe' : '#f0fdf4'; ?>; color: <?php echo $is_default_lang ? '#1e40af' : '#166534'; ?>; padding: 4px 10px; border-radius: 6px; font-weight: 600; font-size: 13px;">
                                    <?php echo esc_html(strtoupper($lang_code)); ?>
                                </span>
                                <span style="color: #334155; font-weight: 500;">
                                    <?php echo esc_html($lang_name); ?>
                                    <?php if ($is_default_lang): ?>
                                    <span style="color: #64748b; font-weight: 400; font-size: 12px;">(<?php esc_html_e('default', 'text-to-speech-tts'); ?>)</span>
                                    <?php endif; ?>
                                </span>
                            </div>
                        </td>
                        <td style="padding: 15px;">
                            <input type="text"
                                   class="mementor-tts-lang-voice-input"
                                   name="mementor_tts_language_voice_mappings[<?php echo esc_attr($lang_code); ?>][voice_id]"
                                   data-lang="<?php echo esc_attr($lang_code); ?>"
                                   value="<?php echo esc_attr($saved_voice_id); ?>"
                                   placeholder="<?php esc_attr_e('Enter Voice ID or leave empty for default', 'text-to-speech-tts'); ?>"
                                   style="width: 100%; max-width: 400px; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-family: monospace;">
                            <?php if ($is_default_lang): ?>
                            <p class="description" style="margin-top: 5px; color: #b45309; font-size: 12px;">
                                <span class="dashicons dashicons-info" style="font-size: 14px; width: 14px; height: 14px; vertical-align: text-bottom;"></span>
                                <?php esc_html_e('Setting a Voice ID here overrides the Voice Selection below for this language.', 'text-to-speech-tts'); ?>
                            </p>
                            <?php else: ?>
                            <p class="description" style="margin-top: 5px; color: #64748b; font-size: 12px;">
                                <?php esc_html_e('Leave empty to use the default voice', 'text-to-speech-tts'); ?>
                            </p>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 15px;">
                            <?php if (!empty($saved_voice_id)): ?>
                            <span class="mementor-tts-status-indicator" style="color: #22c55e; display: flex; align-items: center; gap: 5px;">
                                <span class="dashicons dashicons-yes-alt" style="font-size: 18px; width: 18px; height: 18px;"></span>
                                <?php esc_html_e('Custom voice set', 'text-to-speech-tts'); ?>
                            </span>
                            <?php else: ?>
                            <span class="mementor-tts-status-indicator" style="color: #94a3b8; display: flex; align-items: center; gap: 5px;">
                                <span class="dashicons dashicons-minus" style="font-size: 18px; width: 18px; height: 18px;"></span>
                                <?php echo $is_default_lang ? esc_html__('Using Voice Selection below', 'text-to-speech-tts') : esc_html__('Using default', 'text-to-speech-tts'); ?>
                            </span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Info Box -->
        <div class="mementor-tts-info-box" style="background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); border: 1px solid #bae6fd; border-radius: 8px; padding: 20px; margin-top: 20px;">
            <h4 style="margin: 0 0 10px; color: #0369a1; display: flex; align-items: center; gap: 8px;">
                <span class="dashicons dashicons-lightbulb" style="color: #0ea5e9;"></span>
                <?php esc_html_e('How Language-Specific Voices Work', 'text-to-speech-tts'); ?>
            </h4>
            <ul style="margin: 0 0 0 20px; color: #475569; list-style-type: disc;">
                <li><?php esc_html_e('The plugin detects the current language via your translation plugin and uses the Voice ID assigned here.', 'text-to-speech-tts'); ?></li>
                <li><?php esc_html_e('Setting a Voice ID for the default language overrides the Voice Selection section below.', 'text-to-speech-tts'); ?></li>
                <li><?php esc_html_e('If no Voice ID is assigned, the default voice from the Voice Selection below will be used.', 'text-to-speech-tts'); ?></li>
                <li><?php esc_html_e('You can find Voice IDs in the Voice Selection section below or from your ElevenLabs dashboard.', 'text-to-speech-tts'); ?></li>
            </ul>
        </div>

        <?php endif; // end if available_languages ?>
        <?php endif; // end if has_any_integration ?>

    </div>
</div>

<style>
.mementor-tts-language-voice-section .mementor-tts-collapsible-header:hover {
    background-color: rgba(0,0,0,0.02);
}

.mementor-tts-language-voice-section .mementor-tts-toggle-icon {
    transition: transform 0.3s ease;
}

.mementor-tts-language-voice-section .mementor-tts-toggle-icon.rotated {
    transform: rotate(180deg);
}

.mementor-tts-lang-voice-input:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
    outline: none;
}

.mementor-tts-lang-row:hover {
    background-color: #f8fafc;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Toggle collapsible section
    $('.mementor-tts-collapsible-header').on('click', function() {
        var targetId = $(this).data('target');
        var $content = $('#' + targetId);
        var $icon = $(this).find('.mementor-tts-toggle-icon');

        $content.slideToggle(300);
        $icon.toggleClass('rotated');
    });

    // Update status when voice ID is entered/removed
    var defaultLang = '<?php echo esc_js($original_language); ?>';
    $('.mementor-tts-lang-voice-input').on('input', function() {
        var $input = $(this);
        var $row = $input.closest('tr');
        var $statusCell = $row.find('.mementor-tts-status-indicator');
        var lang = $input.data('lang');

        if ($input.val().trim()) {
            $statusCell.html('<span class="dashicons dashicons-yes-alt" style="font-size: 18px; width: 18px; height: 18px;"></span><?php echo esc_js(__('Custom voice set', 'text-to-speech-tts')); ?>');
            $statusCell.css('color', '#22c55e');
        } else {
            var emptyText = (lang === defaultLang) ? '<?php echo esc_js(__('Using Voice Selection below', 'text-to-speech-tts')); ?>' : '<?php echo esc_js(__('Using default', 'text-to-speech-tts')); ?>';
            $statusCell.html('<span class="dashicons dashicons-minus" style="font-size: 18px; width: 18px; height: 18px;"></span>' + emptyText);
            $statusCell.css('color', '#94a3b8');
        }
    });
});
</script>
