<?php
/**
 * Chatbot Labels - PHP Native Array
 *
 * Performance optimized label storage using PHP native arrays.
 * Benefits over JSON:
 * - PHP Opcache eliminates parsing overhead (~100x faster)
 * - No file_get_contents + json_decode on every request
 * - Type safety and IDE autocompletion
 * - Can use WordPress i18n for defaults as fallback
 *
 * @package AIPT
 * @since 2.5.4
 */

defined('ABSPATH') || exit;

/**
 * Supported language codes whitelist.
 * Only these languages can be loaded to prevent path traversal attacks.
 * Synced with VALID_LANGUAGES in ChatbotSettings.php
 */
const AIPT_SUPPORTED_LANGUAGES = [
    'en', 'en-GB', 'tr', 'de', 'fr', 'es', 'it', 'pt', 'nl', 'ru',
    'ja', 'zh', 'zh-TW', 'ko', 'ar', 'af', 'bg', 'bn', 'ca', 'cs',
    'da', 'el', 'et', 'fa', 'fi', 'he', 'hi', 'hr', 'hu', 'id',
    'lt', 'lv', 'ms', 'no', 'pl', 'ro', 'sk', 'sl', 'sr', 'sv',
    'th', 'uk', 'ur', 'vi',
];

/**
 * Get all chatbot labels.
 *
 * @return array{defaults: array<string, string>, translations: array<string, array<string, string>>}
 */
function aipt_get_chatbot_labels(): array {
    return [
        'defaults' => [
            'placeholder' => 'Type your message...',
            'input_placeholder' => 'Type your message...',
            'send' => 'Send',
            'send_message' => 'Send',
            'clear' => 'Clear Chat',
            'emoji' => 'Emoji',
            'thinking' => 'Thinking...',
            'error' => 'Something went wrong. Please try again.',
            'queued' => 'Message queued',
            'online' => 'Online',
            'offline' => 'Offline',
            'close' => 'Close',
            'open_chat' => 'Open chat',
            'close_chat' => 'Close chat',
            'prechat_title' => 'Start a conversation',
            'prechat_subtitle' => 'Fill in your details to get started',
            'name_label' => 'Name',
            'name_placeholder' => 'Your name',
            'name_required' => 'Name is required',
            'email_label' => 'Email',
            'email_placeholder' => 'your@email.com',
            'email_required' => 'Email is required',
            'invalid_email' => 'Invalid email address',
            'message_label' => 'Message',
            'prechat_message_placeholder' => 'How can we help you?',
            'message_required' => 'Message is required',
            'consent_text_before' => 'I agree to the ',
            'consent_text' => 'I agree to the privacy policy',
            'consent_and' => ' and ',
            'consent_required' => 'Please agree to continue',
            'start_chat' => 'Start Chat',
            'view_product' => 'View Product',
            'add_to_cart' => 'Add to Cart',
            'addedToCart' => 'Added to cart!',
            'out_of_stock' => 'Out of Stock',
            'backorder' => 'Backorder',
            'variable_options' => 'Multiple options available',
            'cart_error' => 'Could not add to cart',
            'cart_error_generic' => 'Error adding to cart',
            'support_team' => 'Support Team',
            'message_queued' => 'Message queued',
            'start_conversation' => 'Start a conversation!',
            'today' => 'Today',
            'yesterday' => 'Yesterday',
            'privacy_label' => 'Privacy',
            'terms_label' => 'Terms',
            'powered_by' => 'Powered by AI Product Tools',
            'home_tab' => 'Home',
            'messages_tab' => 'Messages',
            'hero_greeting' => 'Hi there',
            'hero_subtitle' => 'How can we help?',
            'send_message_cta' => 'Send us a message',
            'send_message_subtitle' => 'We typically reply in a few minutes',
            'whatsapp_cta' => 'Chat on WhatsApp',
            'whatsapp_subtitle' => 'Get instant support via WhatsApp',
            'attention_bubble' => 'Chat with us!',
        ],
        'translations' => [

        ],
    ];
}

/**
 * Get labels for a specific language with caching.
 *
 * Uses WordPress transients for persistent caching across requests.
 * Falls back to English defaults if language not found.
 *
 * @param string $language Language code (e.g., 'tr', 'de', 'fr').
 * @return array<string, string> Labels for the specified language.
 */
function aipt_get_labels_for_language(string $language): array {

    $all_labels = aipt_get_chatbot_labels();
    $defaults = $all_labels['defaults'];

    if ( ! in_array( $language, AIPT_SUPPORTED_LANGUAGES, true ) ) {

        $language = 'en';
    }

    $cache_key = 'aipt_chatbot_labels_' . sanitize_key($language);

    $cached = get_transient($cache_key);
    if ($cached !== false) {
        return $cached;
    }

    if ($language === 'en') {
        set_transient($cache_key, $defaults, DAY_IN_SECONDS);
        return $defaults;
    }

    $lang_file = AIPT_PLUGIN_DIR . 'src/Assets/data/languages/' . $language . '.php';

    if (file_exists($lang_file)) {
        $translations = include $lang_file;
        if (is_array($translations)) {
            $merged = array_merge($defaults, $translations);
            set_transient($cache_key, $merged, DAY_IN_SECONDS);
            return $merged;
        }
    }

    set_transient($cache_key, $defaults, DAY_IN_SECONDS);
    return $defaults;
}

/**
 * Clear all cached labels.
 *
 * Call this when labels are updated.
 *
 * @return void
 */
function aipt_clear_labels_cache(): void {
    global $wpdb;

    $escaped_transient_pattern = $wpdb->esc_like( '_transient_aipt_chatbot_labels_' ) . '%';
    $escaped_timeout_pattern = $wpdb->esc_like( '_transient_timeout_aipt_chatbot_labels_' ) . '%';

    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            $escaped_transient_pattern
        )
    );
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            $escaped_timeout_pattern
        )
    );

}
