HEX
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.4.30
System: Linux iZj6c1151k3ad370bosnmsZ 3.10.0-1160.76.1.el7.x86_64 #1 SMP Wed Aug 10 16:21:17 UTC 2022 x86_64
User: root (0)
PHP: 7.4.30
Disabled: NONE
Upload Files
File: /var/www/html/www.winghung.com/wp-content/plugins/upkyk-assistant-ai/admin/js/api-diagnostics.js
jQuery(document).ready(function($) {
    // Check if upkykApiDiag object exists (passed via wp_localize_script)
    if (typeof upkykApiDiag === 'undefined') {
        console.error('Upkyk API Diagnostics: Localized data not found.');
        // Provide fallback texts or disable functionality if needed
        window.upkykApiDiag = {
            ajax_url: (typeof ajaxurl !== 'undefined') ? ajaxurl : '/wp-admin/admin-ajax.php',
            nonce: '', // Cannot proceed securely without nonce
            text: {
                test_custom_model: 'Test Custom Model',
                test_model_prefix: 'Test %s',
                testing: 'Testing...',
                enter_model_name: 'Please enter a model name to test',
                success: 'Success!',
                error: 'Error:',
                ai_response: 'AI Response:',
                no_details: 'No detailed response available',
                ajax_failed: 'AJAX request failed. Please check your network connection.',
                request_failed: 'Request failed to complete.',
                rebuild_warning: 'WARNING: This will delete all existing phrases and keywords... Continue?',
                rebuilding: 'Rebuilding...',
                rebuild_success: 'Success! Database tables have been rebuilt successfully.',
                rebuild_error: 'Failed to rebuild database tables.',
                delete_warning_1: 'EXTREME CAUTION: Deleting ALL plugin data...',
                delete_warning_2: 'FINAL WARNING: Continue with deletion?',
                deleting: 'Deleting...',
                delete_success: 'Success! All plugin tables deleted.',
                delete_error: 'Failed to delete plugin tables.',
                server_error: 'Server error: %s'
            }
        };
        // Optionally alert the user or log a more specific error
        // alert('Translation data missing for diagnostics page.');
    }

    // Initialize UI elements
    $('#model-test-results').hide();

    // --- Model Testing Logic --- 
    $('.test-model-button').on('click', function() {
        let $button = $(this);
        let modelName = $button.data('model');
        let provider = $button.data('provider'); // Provider should always be set on the button
        let originalButtonText = $button.html(); // Store original HTML, including icons

        // --- Handle Custom Model Input --- 
        if ($button.attr('id') === 'test-custom-deepseek-model') {
            modelName = $('#custom-deepseek-model-name').val().trim();
            provider = 'deepseek';
            if (!modelName) {
                alert(upkykApiDiag.text.enter_model_name);
                return;
            }
            originalButtonText = upkykApiDiag.text.test_custom_model;
        } else if ($button.attr('id') === 'test-custom-openai-model') {
            modelName = $('#custom-openai-model-name').val().trim();
            provider = 'openai';
            if (!modelName) {
                alert(upkykApiDiag.text.enter_model_name);
                return;
            }
            originalButtonText = upkykApiDiag.text.test_custom_model;
        } else if ($button.attr('id') === 'test-custom-model') {
            modelName = $('#custom-model-name').val().trim();
            // Provider is already set via data-provider
            if (!modelName) {
                alert(upkykApiDiag.text.enter_model_name);
                return;
            }
            originalButtonText = upkykApiDiag.text.test_custom_model; // Assuming a generic text
        } else {
            // For standard buttons, reconstruct the original text if needed
            originalButtonText = upkykApiDiag.text.test_model_prefix.replace('%s', modelName);
        }

        // Disable all test buttons and show loading state
        $('.test-model-button').prop('disabled', true);
        $button.text(upkykApiDiag.text.testing);
        $('#model-test-results').hide();
        $('#model-test-message').removeClass('notice-success notice-error').empty();
        $('#model-test-details pre').empty();

        // --- AJAX Request --- 
        $.ajax({
            url: upkykApiDiag.ajax_url,
            type: 'POST',
            data: {
                action: 'upkyk_test_api_models',
                nonce: upkykApiDiag.nonce,
                model: modelName,
                provider: provider
            },
            success: function(response) {
                $('#model-test-results').show();
                if (response.success) {
                    $('#model-test-message').addClass('notice-success')
                        .html('<p><strong>' + upkykApiDiag.text.success + '</strong> ' + response.data.message + '</p>');
                    
                    let formattedResponse = JSON.stringify(response.data.response, null, 2);
                    $('#model-test-details pre').text(formattedResponse);
                    
                    if (response.data.response.choices && response.data.response.choices[0].message) {
                        $('#model-test-message').append('<p><strong>' + upkykApiDiag.text.ai_response + '</strong> ' + 
                            response.data.response.choices[0].message.content + '</p>');
                    }
                } else {
                    $('#model-test-message').addClass('notice-error')
                        .html('<p><strong>' + upkykApiDiag.text.error + '</strong> ' + response.data.message + '</p>');
                    
                    let formattedResponse = response.data.response ? 
                        JSON.stringify(response.data.response, null, 2) : upkykApiDiag.text.no_details;
                    $('#model-test-details pre').text(formattedResponse);
                }
            },
            error: function(xhr, status, error) {
                $('#model-test-results').show();
                $('#model-test-message').addClass('notice-error')
                    .html('<p><strong>' + upkykApiDiag.text.error + '</strong> ' + upkykApiDiag.text.ajax_failed + '</p>');
                $('#model-test-details pre').text(upkykApiDiag.text.request_failed + ' Status: ' + status + ', Error: ' + error);
                console.error('AJAX Error:', xhr.responseText);
            },
            complete: function() {
                // Re-enable all buttons and restore original text
                $('.test-model-button').each(function(){
                    let $btn = $(this);
                    let btn_model = $btn.data('model');
                    let btn_id = $btn.attr('id');
                    let original_text = '';

                    if (btn_id === 'test-custom-deepseek-model' || btn_id === 'test-custom-openai-model' || btn_id === 'test-custom-model') {
                        original_text = upkykApiDiag.text.test_custom_model;
                    } else if (btn_model) {
                         original_text = upkykApiDiag.text.test_model_prefix.replace('%s', btn_model);
                    }
                    $btn.text(original_text).prop('disabled', false);
                });
            }
        });
    });

    // --- Database Maintenance Logic --- 

    // Handle rebuild tables button click
    $('#rebuild-tables-diag').on('click', function() {
        if (!confirm(upkykApiDiag.text.rebuild_warning)) {
            return;
        }
        
        let $button = $(this);
        let originalHtml = $button.html(); // Store original HTML with icon
        $button.prop('disabled', true).text(upkykApiDiag.text.rebuilding);
        
        $.ajax({
            url: upkykApiDiag.ajax_url,
            type: 'POST',
            data: {
                action: 'upkyk_rebuild_tables',
                nonce: upkykApiDiag.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert(upkykApiDiag.text.rebuild_success);
                } else {
                    alert(upkykApiDiag.text.error + ' ' + (response.data.message || upkykApiDiag.text.rebuild_error));
                }
            },
            error: function(xhr, status, error) {
                 alert(upkykApiDiag.text.server_error.replace('%s', error));
                 console.error('AJAX Error:', xhr.responseText);
            },
            complete: function() {
                $button.prop('disabled', false).html(originalHtml);
            }
        });
    });
    
    // Handle delete all tables button click
    $('#delete-all-tables').on('click', function() {
        if (!confirm(upkykApiDiag.text.delete_warning_1)) {
            return;
        }
        if (!confirm(upkykApiDiag.text.delete_warning_2)) {
            return;
        }
        
        let $button = $(this);
        let originalHtml = $button.html(); // Store original HTML with icon
        $button.prop('disabled', true).text(upkykApiDiag.text.deleting);
        
        $.ajax({
            url: upkykApiDiag.ajax_url,
            type: 'POST',
            data: {
                action: 'upkyk_delete_all_tables',
                nonce: upkykApiDiag.nonce
            },
            success: function(response) {
                 if (response.success) {
                    alert(upkykApiDiag.text.delete_success);
                } else {
                    alert(upkykApiDiag.text.error + ' ' + (response.data.message || upkykApiDiag.text.delete_error));
                }
            },
            error: function(xhr, status, error) {
                alert(upkykApiDiag.text.server_error.replace('%s', error));
                console.error('AJAX Error:', xhr.responseText);
            },
            complete: function() {
                 $button.prop('disabled', false).html(originalHtml);
            }
        });
    });
});