<?php
if (!defined('ABSPATH')) exit;
require_once BOTAMI_PLUGIN_PATH . 'includes/class-api-config.php';

class Botami_Chatbot_Admin {
    private $assets;
    private $sanitizer;

    public function __construct() {
        $this->assets = new Botami_Chatbot_Assets();
        $this->sanitizer = new Botami_Chatbot_Settings_Sanitizer();
    }

    private $protected_options = [
        'botami_api_key',
        'botami_plan',
        'botami_exceed_limit'
    ];

    private $char_limits = [
        'free' => 10000,
        'pro' => 20000,
        'premium' => 40000,
        'entreprise' => 100000,
    ];

    /**
     * Sanitization wrapper that uses the sanitizer class
     * 
     * @param mixed $input
     * @param string $option_name
     * @return mixed
     */
    public function sanitize_chatbot_option($input, $option_name = null) {
        // If option_name is not provided, try to get it from the current action
        if ($option_name === null) {
            $option_name = current_filter();
            // Remove 'sanitize_option_' prefix if present
            if (strpos($option_name, 'sanitize_option_') === 0) {
                $option_name = substr($option_name, 16);
            }
        }
        
        $access_level = $this->check_access_level();
        return $this->sanitizer->sanitize_option($input, $option_name, $access_level);
    }

    public function add_plugin_admin_menu() {
    add_menu_page(
        'Botami Chatbot',
        'Botami Chatbot', 
        'manage_options',
        'botami-settings',
        [$this, 'display_admin_settings'],
        'dashicons-admin-generic', // placeholder
        21
    );
}

    
    private function update_dashboard_metrics() {
        // Include the metrics class if it's not already loaded
        if (!class_exists('Botami_Dashboard_Metrics')) {
            require_once BOTAMI_PLUGIN_PATH . 'includes/class-dashboard-metrics.php';
        }
        // Update all metrics
        Botami_Dashboard_Metrics::update_all_metrics();

        $api_key = get_option('botami_api_key', '');
        if (!empty($api_key)) {
            // Update credit usage
            if (!class_exists('Botami_Token_Usage')) {
                require_once BOTAMI_PLUGIN_PATH . 'includes/class-token-usage.php';
            }
            Botami_Token_Usage::update_token_usage();
        }
    }

    public function display_admin_settings() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have sufficient permissions to access this page.');
        }
        $this->update_dashboard_metrics();

        $access_level = $this->check_access_level();
        $is_premium = in_array($access_level, ['premium', 'entreprise']);
        $is_pro_or_higher = in_array($access_level, ['pro', 'premium', 'entreprise']);
        $has_api = $access_level !== 'no_api';
        
        // Start output buffering to capture content
        ob_start();
        
        // Include settings template
        include_once BOTAMI_PLUGIN_PATH . 'admin/class-admin-settings.php';
        
        // Get the buffered content
        $plugin_content = ob_get_clean();
        
        // Output with custom wrapper
        echo '<div class="btm-wrap btm-chatbot-admin-container" style="position: relative; z-index: 1;">';
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Admin template content is controlled by plugin
        echo $plugin_content;
        echo '</div>';
        
    }

    private function check_access_level() {
        $api_key = get_option('botami_api_key', '');
        $plan = get_option('botami_plan', '');
        
        if (empty($api_key)) {
            return 'no_api';
        }
        
        if (!in_array($plan, ['free', 'pro', 'premium', 'entreprise'])) {
            return 'free';
        }
        
        return $plan;
    }

    public function enqueue_styles($hook = '') {
        // Always load icon CSS on all admin pages so the menu icon appears correctly
        wp_enqueue_style(
            'botami-admin-icon',
            BOTAMI_PLUGIN_URL . 'admin/css/admin-icon.css',
            [],
            BOTAMI_VERSION
        );

        // Only load other assets on Botami settings page to avoid affecting other admin pages
        if ($hook !== 'toplevel_page_botami-settings') {
            return;
        }

        $this->assets->enqueue_assets();

        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        $screen_id = $screen ? $screen->id : $hook;

        // Only apply on your settings screen
        $is_botami_screen = in_array($screen_id, [
            'toplevel_page_botami-settings',
            'settings_page_botami-settings',
        ], true);

        if (!$is_botami_screen) {
            return;
        }

        if (!wp_style_is('botami-admin', 'registered')) {
            wp_register_style('botami-admin', false, [], defined('BOTAMI_VERSION') ? BOTAMI_VERSION : null);
        }
        wp_enqueue_style('botami-admin');

        $safe_screen_id = esc_attr(sanitize_html_class($screen_id));

        $css = "
            /* Hide external admin notices ONLY on the Botami screen; keep your .chatbot-notice */
            body.{$safe_screen_id} .notice:not(.chatbot-notice),
            body.{$safe_screen_id} .updated:not(.chatbot-notice),
            body.{$safe_screen_id} .update-nag:not(.chatbot-notice),
            body.{$safe_screen_id} .error:not(.chatbot-notice),
            body.{$safe_screen_id} .notice-success:not(.chatbot-notice),
            body.{$safe_screen_id} .notice-warning:not(.chatbot-notice),
            body.{$safe_screen_id} .notice-error:not(.chatbot-notice),
            body.{$safe_screen_id} #wpbody-content > .notice:not(.chatbot-notice) {
                display: none !important;
            }
        ";

        wp_add_inline_style('botami-admin', $css);
    }

    /**
     * Enqueue WordPress Media Library
     * 
     * @param string $hook Current admin page.
     */
    public function enqueue_media_library($hook) {
        if ('toplevel_page_botami-settings' !== $hook) {
            return;
        }
        
        // Enqueue WordPress Media Library
        wp_enqueue_media();
        
        // Enqueue our custom script
        wp_enqueue_script(
            'botami-media-library',
            BOTAMI_PLUGIN_URL . 'admin/js/media-library.js',
            ['jquery'],
            BOTAMI_VERSION,
            true
        );
    }

    public function enqueue_scripts($hook) {
        if ('toplevel_page_botami-settings' !== $hook) {
            return;
        }
        $access_level = $this->check_access_level();
    
        $char_limit = isset($this->char_limits[$access_level]) ? $this->char_limits[$access_level] : $this->char_limits['free'];
        $uploaded_file = get_option('botami_knowledge_file', '');
    
        wp_enqueue_script('botami-admin-script', BOTAMI_PLUGIN_URL . 'admin/js/admin-script.js', ['jquery'], BOTAMI_VERSION, true);
        wp_localize_script('botami-admin-script', 'botamiLocalizedStringsAdmin', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('chatbot_api_verify'),
            'export_nonce' => wp_create_nonce('chat_export_nonce'),
            'lead_export_nonce' => wp_create_nonce('lead_export_nonce'),
            'file_upload_nonce' => wp_create_nonce('chatbot_file_upload'),
            'access_level' => $access_level,
            'is_premium' => in_array($access_level, ['premium', 'entreprise']),
            'is_pro_or_higher' => in_array($access_level, ['pro', 'premium', 'entreprise']),
            'has_api' => $access_level !== 'no_api',
            'char_limit' => $char_limit,
            'uploaded_knowledge_files' => $uploaded_file,
            // Add localized strings for JavaScript
            'strings' => [
                'questionNumber' => botamichat_admin_text('admin.question_number'),
                'interactiveQuestionnaire' => botamichat_admin_text('admin.interactive_questionnaire'),
                'deleteQuestion' => botamichat_admin_text('admin.delete_question'),
                'mainQuestion' => botamichat_admin_text('admin.main_question'),
                'enterQuestion' => botamichat_admin_text('admin.enter_question'),
                'responseOptions' => botamichat_admin_text('admin.response_options'),
                'addOption' => botamichat_admin_text('admin.add_option'),
                'enterOption' => botamichat_admin_text('admin.enter_option'),
                'previousQuestion' => botamichat_admin_text('admin.previous_question'),
                'optional' => botamichat_admin_text('admin.optional'),
                'noPreviousQuestion' => botamichat_admin_text('admin.no_previous_question'),
                'previousAnswerOption' => botamichat_admin_text('admin.previous_answer_option'),
                'noSpecificAnswer' => botamichat_admin_text('admin.no_specific_answer'),
                'onlyAfterAnswer' => botamichat_admin_text('admin.only_after_answer'),
                'autoSaveEnabled' => botamichat_admin_text('admin.auto_save_enabled'),
                'edit' => botamichat_admin_text('admin.edit'),
                'deleteQuestionConfirm' => botamichat_admin_text('admin.delete_question_confirm'),
                'enterQuestionMessage' => botamichat_admin_text('admin.enter_question_message'),
                'removeAllConfirm' => botamichat_admin_text('admin.remove_all_confirm'),
            ],

            'file_upload_strings' => [
                'uploading_file' => botamichat_admin_text('admin.uploading_file'),
                'file_uploaded' => botamichat_admin_text('admin.file_uploaded'),
                'upload_failed' => botamichat_admin_text('admin.upload_failed'),
                'error_uploading' => botamichat_admin_text('admin.error_uploading'),
                'invalid_file_format' => botamichat_admin_text('admin.invalid_file_format'),
                'content_truncated_warning' => botamichat_admin_text('admin.content_truncated_warning'),
                'file_too_large_for_plan' => botamichat_admin_text('admin.file_too_large_for_plan'),
            ],

            'animation_strings' => [
                'title' => botamichat_admin_text('admin.setup_animation_title'),
                'init' => botamichat_admin_text('admin.setup_animation_init'),
                'building' => botamichat_admin_text('admin.setup_animation_building'),
                'learning' => botamichat_admin_text('admin.setup_animation_learning'),
                'optimizing' => botamichat_admin_text('admin.setup_animation_optimizing'),
                'customizing' => botamichat_admin_text('admin.setup_animation_customizing'),
                'finalizing' => botamichat_admin_text('admin.setup_animation_finalizing'),
                'ready' => botamichat_admin_text('admin.setup_animation_ready'),
                'no_content' => botamichat_admin_text('admin.setup_animation_no_content'),
            ],
        ]);
        
        $this->enqueue_media_library($hook);
    }
    
    private function verify_api_key($key) {
        if (empty($key)) {
            return false;
        }

        $data = array(
            'api_key' => $key,
            'site_url' => get_site_url(),
        );
        $response = wp_remote_post(Botami_API_Config::get_verify_endpoint(), [
            'body' => json_encode($data),
            'timeout' => 15,
            'headers' => [
                'X-API-Key' => get_option("botami_api_key", ''),
                'Content-Type' => 'application/json',
            ],
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code !== 200) {
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        $verified = isset($data['verified']) && $data['verified'] === true;
        if ($verified) {
            if (isset($data['plan_name'])){
                update_option('botami_plan', $data['plan_name']);
            }

            // Check if we have content data (only returned on first API key setup)
            $has_content = false;
            if (isset($data['content'])) {
                if (!empty($data['content'])) {
                    // Update the knowledge document option directly
                    $sanitized_content = $this->sanitize_chatbot_option($data['content'], 'botami_knowledge_document');
                    update_option('botami_knowledge_document', $sanitized_content);

                    $has_content = true;
                } else {
                    $has_content = false;
                }

                // Return has_content flag for frontend to show appropriate message
                return [
                    'verified' => true,
                    'has_content' => $has_content
                ];
            }

            return true;
        }

        return false;
    }

    public function verify_api_key_ajax() {
        check_ajax_referer('chatbot_api_verify', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized access');
        }
        if (!isset($_POST['api_key'])) {
            wp_send_json_error('missing api key');
        }

        $old_api_key = get_option('botami_api_key', '');
        $is_first_setup = empty($old_api_key);

        $api_key = sanitize_text_field(wp_unslash($_POST['api_key']));
        $result = $this->verify_api_key($api_key);

        if ($result) {
            update_option('botami_api_key', $api_key);
            delete_option('botami_exceed_limit');

            $response_data = [
                'message' => 'API key verified successfully',
                'is_first_setup' => $is_first_setup
            ];

            // If this is first setup and we have has_content info from backend, include it
            if ($is_first_setup && is_array($result) && isset($result['has_content'])) {
                $response_data['has_content'] = $result['has_content'];
            }

            wp_send_json_success($response_data);
        } else {
            wp_send_json_error(['message' => 'Invalid API key']);
        }
    }

    public function mark_setup_complete_ajax() {
        check_ajax_referer('chatbot_api_verify', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized access');
        }

        update_option('botami_setup_complete', '1');
        wp_send_json_success(['message' => 'Setup marked as complete']);
    }

    public function handle_content_upload($content) {    
    
        // Get the API key for authentication
        $api_key = get_option('botami_api_key');
        
        if (empty($api_key)) {
            wp_send_json_error(['message' => 'API key is not configured']);
        }
        
        $data = array(
            'pdf_content' => $content,
        );
        $response = wp_remote_post(Botami_API_Config::get_upload_endpoint(), [
            'body' => json_encode($data),
            'timeout' => 15,
            'headers' => [
                'X-API-Key' => $api_key,
                'Content-Type' => 'application/json',
            ],
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code !== 200) {
            return false;
        }
         return true;
    }

    public function handle_form_submission() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have sufficient permissions to access this page.');
        }
    
        $access_level = $this->check_access_level();
        
        if ($access_level === 'no_api' && !isset($_POST['botami_api_key'])) {
            wp_die('Please configure your API key first.');
        }
    
        if (!isset($_POST['chatbot_settings_nonce'])) {
            wp_die('Invalid nonce verification');
        }
        $clean_nonce = sanitize_text_field(wp_unslash($_POST['chatbot_settings_nonce']));
    
        if (!wp_verify_nonce($clean_nonce, 'chatbot_settings_action')) {
            wp_die('Invalid nonce verification');
        }
        
        $free_options = [
            'botami_welcome_message',
            'botami_heading_text',
            'botami_online_status_text',
            'botami_reload_text',
            'botami_placeholder_text',
            'botami_default_message',
            'botami_excluded_urls',
            'botami_welcome_message_enabled',
            'botami_is_active',
            'botami_should_reload',
            'botami_quick_replies',
            'botami_show_powered_by'
        ];
    
        $pro_options = array_merge($free_options, [
            'botami_primary_color',
            'botami_secondary_color',
            'botami_lead_gen_enabled',
            'botami_lead_gen_intro_message',
            'botami_lead_gen_consentment',
            'botami_lead_gen_name_placeholder',
            'botami_lead_gen_email_placeholder',
            'botami_lead_gen_field_placeholder',
            'botami_lead_gen_button_text',
            'botami_lead_gen_quick_reply',
            'botami_lead_gen_thank_you',
            'botami_lead_consent_is_active',
            'botami_lead_email_enabled'
        ]);
        $allowed_options = $free_options;
        if (in_array($access_level, ['pro', 'premium', 'entreprise'])) {
            $allowed_options = $pro_options;
        }
        
        if (in_array($access_level, ['pro', 'premium', 'entreprise'])) {
            // Use WordPress site language as default instead of hardcoded 'en'
            $default_language = Botami_Language_Manager::get_site_language();
            $input_language = isset($_POST['botami_input_language']) ? sanitize_text_field(wp_unslash($_POST['botami_input_language'])) : $default_language;

            // Handle enabled languages
            $enabled_languages = [$default_language]; // Default to site language
            if (isset($_POST['botami_enabled_languages']) && is_array($_POST['botami_enabled_languages'])) {
                $enabled_languages = array_map('sanitize_text_field', wp_unslash($_POST['botami_enabled_languages']));
            }
            
            update_option('botami_input_language', $input_language);
            update_option('botami_enabled_languages', json_encode($enabled_languages));
            
            // Define translatable fields and their translation storage options
            $translatable_fields = [
                'botami_placeholder_text' => 'botami_placeholder_text_translations',
                'botami_default_message' => 'botami_default_message_translations',
                'botami_reload_text' => 'botami_reload_text_translations',
                'botami_welcome_message' => 'botami_welcome_message_translations'
            ];
            
            $texts_to_translate = [];
            
            foreach ($translatable_fields as $field => $translation_field) {
                if (isset($_POST[$field])) {
                    $new_value = sanitize_text_field(wp_unslash($_POST[$field]));
                    $old_value = get_option($field, '');
                    
                    // Always save the input language version in the JSON
                    $translations = json_decode(get_option($translation_field, '{}'), true);
                    if (!is_array($translations)) {
                        $translations = [];
                    }
                    $translations[$input_language] = $new_value;
                    update_option($translation_field, json_encode($translations));
                    
                    // Only translate if value has changed and we have multiple languages enabled
                    if ($new_value !== $old_value && count($enabled_languages) > 1) {
                        $texts_to_translate[$field] = [
                            'text' => $new_value,
                            'translation_field' => $translation_field
                        ];
                    }
                }
            }
            
            // Call backend API for translation if there are texts to translate
            if (!empty($texts_to_translate)) {
                $this->translate_and_save_texts($texts_to_translate, $input_language, $enabled_languages);
            }
        }
        // Update only submitted form values with proper sanitization
        foreach ($allowed_options as $option) {
            if (isset($_POST[$option])) {
                $option_value = wp_unslash($_POST[$option]);
                // Apply proper sanitization based on option type
                $sanitized_value = $this->sanitize_chatbot_option($option_value, $option);
                update_option($option, $sanitized_value);
            }
        }
    
        if (in_array($access_level, ['pro', 'premium', 'entreprise'])) {
            // Gestion de l'image du bot - FIX pour le sélecteur de logo
            if (isset($_POST['botami_bot_image_url'])) {
                // Save the image URL with proper sanitization
                $sanitized_url = $this->sanitize_chatbot_option(wp_unslash($_POST['botami_bot_image_url']), 'botami_bot_image_url');
                update_option('botami_bot_image_url', $sanitized_url);
                
                // Save the image ID (if from media library)
                if (isset($_POST['botami_bot_image_id']) && !empty($_POST['botami_bot_image_id'])) {
                    $sanitized_id = $this->sanitize_chatbot_option($_POST['botami_bot_image_id'], 'botami_bot_image_id');
                    update_option('botami_bot_image_id', $sanitized_id);
                } else {
                    // If using a predefined logo, clear the image ID
                    update_option('botami_bot_image_id', '');
                }
            }
    
            // Process knowledge URLs if they've changed
            $knowledge_urls = '';
            if (isset($_POST['botami_knowledge_urls'])) {
                $knowledge_urls = $this->sanitize_chatbot_option(wp_unslash($_POST['botami_knowledge_urls']), 'botami_knowledge_urls');
            }
            $existing_urls = get_option('botami_knowledge_urls', '');
    
            if ($knowledge_urls !== $existing_urls) {
                // Only process if the URLs have changed
                $success = $this->process_knowledge_urls($knowledge_urls);
                if ($success) {
                    update_option('botami_knowledge_urls', $knowledge_urls);
                }
            }
        }
    
        $max_length = isset($this->char_limits[$access_level]) ? $this->char_limits[$access_level] : $this->char_limits['free'];
    
        $botami_knowledge_document = get_option('botami_knowledge_document');
        $post_knowledge_document = "";
        if (isset($_POST['botami_knowledge_document'])) {
            $post_knowledge_document = $this->sanitize_chatbot_option(wp_unslash($_POST['botami_knowledge_document']), 'botami_knowledge_document');
        }
        
        if ($post_knowledge_document !== $botami_knowledge_document) {
            $uploaded = $this->handle_content_upload($post_knowledge_document);
            if ($uploaded) {
                update_option('botami_knowledge_document', $post_knowledge_document);
            }
        }
        
        // Preserve protected options
        foreach ($this->protected_options as $protected_option) {
            $existing_value = get_option($protected_option);
            if ($existing_value !== false) {
                update_option($protected_option, $existing_value);
            }
        }
    
        // Redirect back to the settings page
        $current_tab = isset($_POST['current_tab']) ? sanitize_text_field($_POST['current_tab']) : '';
        $redirect_url = admin_url('admin.php?page=botami-settings');
    
        // Add tab parameter if we have one
        if (!empty($current_tab)) {
            $redirect_url = add_query_arg('tab', $current_tab, $redirect_url);
        }
        
        if (function_exists('wp_cache_flush')) {
            wp_cache_flush();
        }

        // Clear alloptions cache specifically  
        wp_cache_delete('alloptions', 'options');

        // Force update cache buster for frontend scripts
        update_option('botami_cache_buster', time());

        // Add settings-updated parameter
        $redirect_url = add_query_arg('settings-updated', 'true', $redirect_url);
        
        // Redirect to the settings page with the current tab
        wp_redirect($redirect_url);
        exit;
    }
    
    public function chatbot_register_settings() {
        // Register all settings with sanitization
        $all_options = array_merge([
            'botami_excluded_urls',
            'botami_welcome_message',
            'botami_bot_image_url',
            'botami_bot_image_id',
            'botami_primary_color',
            'botami_secondary_color',
            'botami_knowledge_urls',
            'botami_knowledge_document',
            'botami_heading_text',
            'botami_online_status_text',
            'botami_reload_text',
            'botami_placeholder_text',
            'botami_default_message',
            'botami_welcome_message_enabled',
            'botami_is_active',
            'botami_should_reload',
            'botami_quick_replies',
            'botami_lead_gen_enabled',
            'botami_lead_gen_intro_message',
            'botami_lead_gen_consentment',
            'botami_lead_gen_name_placeholder',
            'botami_lead_gen_email_placeholder',
            'botami_lead_gen_field_placeholder',
            'botami_lead_gen_button_text',
            'botami_lead_gen_quick_reply',
            'botami_lead_gen_thank_you',
            'botami_lead_consent_is_active',
            'botami_knowledge_file',
            'botami_lead_email_enabled',
            'botami_cache_buster',
            'botami_show_powered_by',
            'botami_input_language',
            'botami_enabled_languages',
            'botami_placeholder_text_translations',
            'botami_default_message_translations',
            'botami_reload_text_translations',
            'botami_welcome_message_translations',
        ], $this->protected_options);

        foreach ($all_options as $option) {
            register_setting(
                'botami-settings-group', 
                $option,
                [
                    'sanitize_callback' => [$this, 'sanitize_chatbot_option']
                ]
            );
        }
    }


    public function handle_image_upload($file) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 10 * 1024 * 1024; // 10MB
        
        $validation = $this->validate_file($file, $allowed_types, $max_size);
        if (!$validation['valid']) {
            return false;
        }

    
        // WordPress upload function
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        // Insert the file into WordPress media library
        $attachment_id = media_handle_upload('fileImg', 0);

        if (is_wp_error($attachment_id)) {
            return false;
        }

        // Get the attachment URL
        $attachment_url = wp_get_attachment_url($attachment_id);
        
        if (!$attachment_url) {
            return false;
        }

        // Save both the URL and attachment ID with sanitization
        update_option('botami_bot_image_url', $this->sanitize_chatbot_option($attachment_url, 'botami_bot_image_url'));
        update_option('botami_bot_image_id', $this->sanitize_chatbot_option($attachment_id, 'botami_bot_image_id'));

        return $attachment_url;
    }

    public function handle_chat_export() {
        // Verify nonce
        if (!isset($_POST['nonce'])) {
            wp_die('Invalid nonce');
        }
        $clean_nonce = sanitize_text_field(wp_unslash($_POST['nonce']));

        if (!wp_verify_nonce($clean_nonce, 'chat_export_nonce')) {
            wp_die('Invalid nonce verification');
        }

        $access_level = $this->check_access_level();
        if (!in_array($access_level, ['pro', 'premium', 'entreprise'])) {
            wp_send_json_error('Invalid plan');
        }
        if (!isset($_POST['start_date'], $_POST['end_date'])) {
            wp_send_json_error(botamichat_admin_text('admin.please_select_dates'));
        }

        $start_date = sanitize_text_field(wp_unslash($_POST['start_date']));
        $end_date = sanitize_text_field(wp_unslash($_POST['end_date']));
        
        // Get chat messages
        $chat_messages = Botami_Chat_Messages::getInstance();
        $csv_content = $chat_messages->export_messages_to_csv($start_date, $end_date);
        
        if ($csv_content === false) {
            wp_send_json_error(botamichat_admin_text('admin.no_messages_found'));
        }
        
        // Generate filename
        $filename = 'chat_export_' . gmdate('Y-m-d') . '.csv';
        
        // Send JSON response with CSV content
        wp_send_json_success(array(
            'content' => base64_encode($csv_content),
            'filename' => $filename
        ));
    }

    public function handle_pdf_upload() {
        check_ajax_referer('chatbot_file_upload', 'nonce');
    
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized access']);
        }
    
        $access_level = $this->check_access_level();
        if (!in_array($access_level, ['pro','premium', 'entreprise'])) {
            wp_send_json_error('Invalid plan');
        }
    
        if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
            wp_send_json_error(['message' => 'No file was uploaded']);
        }
    
        $allowed_types = [
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
            'text/csv', // .csv
            'application/vnd.ms-excel', // .xls
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // .xlsx
        ];
        $max_size = 20 * 1024 * 1024; // 20MB
        
        $validation = $this->validate_file($_FILES['file'], $allowed_types, $max_size);
        if (!$validation['valid']) {
            wp_send_json_error(['message' => $validation['message']]);
        }
    
        // Get the API key for authentication
        $api_key = get_option('botami_api_key');
        
        if (empty($api_key)) {
            wp_send_json_error(['message' => 'API key is not configured']);
        }
        
        if (!isset($_FILES['file']['tmp_name']) || !isset($_FILES['file']['name']) || 
            !isset($_FILES['file']['type']) || !isset($_FILES['file']['size'])) {
            wp_send_json_error(['message' => 'Invalid file data']);
        }
        // Prepare file data with sanitization
        $file_path = $_FILES['file']['tmp_name'];
        $file_name = sanitize_file_name($_FILES['file']['name']);
        $file_type = sanitize_mime_type($_FILES['file']['type']);
        $file_size = absint($_FILES['file']['size']);
        
        // Read file content
        $file_content = file_get_contents($file_path);
        if ($file_content === false) {
            wp_send_json_error(['message' => 'Failed to read file']);
        }
    
        // Create multipart boundary
        $boundary = wp_generate_password(24);
        $payload = '';
        
        // Add file content to payload
        $payload .= "--" . $boundary . "\r\n";
        $payload .= 'Content-Disposition: form-data; name="file"; filename="' . $file_name . '"' . "\r\n";
        $payload .= 'Content-Type:  ' . $file_type . "\r\n\r\n";
        $payload .= $file_content . "\r\n";
        
        // Add site URL to payload
        $payload .= "--" . $boundary . "\r\n";
        $payload .= 'Content-Disposition: form-data; name="site_url"' . "\r\n\r\n";
        $payload .= esc_url_raw(get_site_url()) . "\r\n";
        $payload .= "--" . $boundary . "--\r\n";
    
        // Send request using WordPress HTTP API
        $response = wp_remote_post(Botami_API_Config::get_pdf_upload_endpoint(), [
            'headers' => [
                'X-API-Key' => $api_key,
                'Content-Type' => 'multipart/form-data; boundary=' . $boundary
            ],
            'body' => $payload,
            'timeout' => 60,
            'method' => 'POST'
        ]);
    
        if (is_wp_error($response)) {
            wp_send_json_error([
                'message' => 'Failed to upload file: ' . esc_html($response->get_error_message()),
                'filename' => $file_name
            ]);
        }
    
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
    
        switch ($status_code) {
            case 200:
                // Save file info to WordPress options with sanitization
                $file_info = [
                    'filename' => $file_name,
                    'type' => $file_type,
                    'size' => $file_size,
                    'uploaded_at' => current_time('mysql')
                ];
                
                $sanitized_file_info = $this->sanitize_chatbot_option(json_encode($file_info), 'botami_knowledge_file');
                update_option('botami_knowledge_file', $sanitized_file_info);
                
                $success_response = [
                    'message' => 'File uploaded successfully',
                    'filename' => $file_name
                ];
                
                // Check for warning message from the API response
                if (isset($data['warning']) && !empty($data['warning'])) {
                    $success_response['warning'] = esc_html($data['warning']);
                }
                
                // Include content length if available
                if (isset($data['content_length'])) {
                    $success_response['content_length'] = absint($data['content_length']);
                }
                
                wp_send_json_success($success_response);
                break;
            case 401:
                wp_send_json_error([
                    'message' => isset($data['detail']) ? esc_html($data['detail']) : 'Unauthorized',
                    'filename' => $file_name
                ]);
                break;
            default:
                wp_send_json_error([
                    'message' => 'Failed to upload file to server',
                    'filename' => $file_name
                ]);
        }
    }

    private function validate_file($file, $allowed_types, $max_size) {
        if (!isset($file) || !is_array($file) || $file['error'] !== UPLOAD_ERR_OK) {
            return ['valid' => false, 'message' => 'Invalid file upload'];
        }

        // Validate file type using WP's functions
        $check_file = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
        if (!$check_file['type'] || !in_array($check_file['type'], $allowed_types, true)) {
            return ['valid' => false, 'message' => 'Invalid file type'];
        }

        // Validate file size
        if ($file['size'] > $max_size) {
            return ['valid' => false, 'message' => 'File size exceeds limit'];
        }

        // Additional security checks
        if (!is_uploaded_file($file['tmp_name'])) {
            return ['valid' => false, 'message' => 'Invalid upload operation'];
        }

        return ['valid' => true, 'type' => $check_file['type']];
    }
    
    /**
     * Sends knowledge URLs to the backend 
     * 
     * @param string $urls Pipe-separated URLs to process
     * @return bool Success status
     */
    public function process_knowledge_urls($urls) {
        
        // Get the API key for authentication
        $api_key = get_option('botami_api_key');
        
        if (empty($api_key)) {
            return false;
        }
        
        // Split URLs by the separator and sanitize
        $url_array = array_filter(explode('||', $urls));
        $sanitized_urls = [];
        
        foreach ($url_array as $url) {
            $clean_url = esc_url_raw(trim($url));
            if (!empty($clean_url) && filter_var($clean_url, FILTER_VALIDATE_URL)) {
                $sanitized_urls[] = $clean_url;
            }
        }
        
        if (empty($sanitized_urls)) {
            return false;
        }
        
        $endpoint = Botami_API_Config::get_scrape_urls_endpoint();
        
        $data = array(
            'urls' => $sanitized_urls,
        );
        
        $response = wp_remote_post($endpoint, [
            'body' => json_encode($data),
            'timeout' => 30, // Longer timeout for scraping
            'headers' => [
                'X-API-Key' => $api_key,
                'Content-Type' => 'application/json',
            ],
        ]);
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code !== 200) {
            return false;
        }
        
        return true;
    }

    /**
     * Handle lead export request
     * Exports all leads to a CSV file
     */
    public function handle_lead_export() {
        // Verify nonce
        if (!isset($_POST['nonce'])) {
            wp_die('Invalid nonce');
        }
        $clean_nonce = sanitize_text_field(wp_unslash($_POST['nonce']));

        if (!wp_verify_nonce($clean_nonce, 'lead_export_nonce')) {
            wp_die('Invalid nonce verification');
        }

        $access_level = $this->check_access_level();
        if (!in_array($access_level, ['premium', 'entreprise'])) {
            wp_send_json_error('Invalid plan');
        }
        
        // Get lead data
        $lead_generator = Botami_Lead_Generator::getInstance();
        $csv_content = $lead_generator->export_leads_to_csv();
        
        if ($csv_content === false) {
            wp_send_json_error('No leads found');
        }
        
        // Generate filename
        $filename = 'lead_export_' . gmdate('Y-m-d') . '.csv';
        
        // Send JSON response with CSV content
        wp_send_json_success(array(
            'content' => base64_encode($csv_content),
            'filename' => $filename
        ));
    }

    public function botami_delete_knowledge_file() {
        // Verify nonce
        check_ajax_referer('chatbot_file_upload', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized access']);
            return;
        }
        
        // Get API key for backend communication
        $api_key = get_option('botami_api_key', '');
        if (empty($api_key)) {
            wp_send_json_error(['message' => 'API key is not configured']);
            return;
        }
        
        try {
            // Delete the file information from options
            delete_option('botami_knowledge_file');
            
            $response = wp_remote_post(Botami_API_Config::get_delete_content_endpoint(), [
                'headers' => [
                    'X-API-Key' => $api_key,
                    'Content-Type' => 'application/json'
                ],
                'body' => json_encode(['delete_type' => 'file']),
                'timeout' => 15
            ]);
            
            // Check if backend deletion was successful
            $success = true;
            if (!is_wp_error($response)) {
                $status_code = wp_remote_retrieve_response_code($response);
                if ($status_code !== 200) {
                    // Even if backend deletion fails, we still removed the local reference,
                    // so consider it a partial success
                    $success = true;
                }
            }
            
            if ($success) {
                update_option('botami_knowledge_file', '');
                wp_send_json_success(['message' => 'File deleted successfully']);
            } else {
                wp_send_json_error(['message' => 'File deleted locally but failed to remove from backend']);
            }
        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Error deleting file: ' . $e->getMessage()]);
        }
    }

    /**
 * Translate texts using backend API and save translations as JSON
 * 
 * @param array $texts Array of texts to translate with their translation field names
 * @param string $from_lang Source language code
 * @param array $enabled_languages Array of enabled language codes
 */
private function translate_and_save_texts($texts, $from_lang, $enabled_languages) {
    $api_key = get_option('botami_api_key');
    if (empty($api_key)) {
        return;
    }
    
    // Prepare texts array for translation API
    $texts_array = [];
    $field_mapping = [];
    
    foreach ($texts as $field => $data) {
        $texts_array[] = $data['text'];
        $field_mapping[] = $data['translation_field'];
    }
    
    // Call backend API for each target language
    foreach ($enabled_languages as $target_lang) {
        // Skip source language
        if ($target_lang === $from_lang) {
            continue;
        }
        
        $api_url = Botami_API_Config::get_translation_endpoint();
        
        $response = wp_remote_post($api_url, [
            'body' => json_encode([
                'texts' => $texts_array,
                'from_language' => $from_lang,
                'to_language' => $target_lang
            ]),
            'headers' => [
                'X-API-Key' => $api_key,
                'Content-Type' => 'application/json'
            ],
            'timeout' => 30
        ]);
        
        if (is_wp_error($response)) {
            continue;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        // Check if we got valid translations
        if (isset($data['translations']) && is_array($data['translations'])) {
            // Save each translation to its respective JSON field
            foreach ($data['translations'] as $index => $translated_text) {
                if (!isset($field_mapping[$index])) {
                    continue;
                }
                
                $translation_field = $field_mapping[$index];
                
                // Get existing translations
                $translations = json_decode(get_option($translation_field, '{}'), true);
                if (!is_array($translations)) {
                    $translations = [];
                }
                
                // Add the new translation
                $translations[$target_lang] = sanitize_text_field($translated_text);
                
                // Save back as JSON
                update_option($translation_field, json_encode($translations));
            }
            
        }
    }
}

    //This is called in the admin settings page to format file sizes
    private function format_file_size($bytes) {
        $bytes = max((int)$bytes, 0);
        $units = array('B', 'KB', 'MB', 'GB', 'TB');
        
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        
        $bytes /= (1 << (10 * $pow));
        
        return round($bytes, 2) . ' ' . $units[$pow];
    }
}