// Test function for Stability AI API – Add to functions.php temporarily
add_action(‘wp_ajax_test_stability_api’, function() {
if (!is_user_logged_in() || !current_user_can(‘manage_options’)) {
wp_send_json_error(‘Unauthorized’);
}

// Get API key
$api_key = 'YOUR_STABILITY_API_KEY'; // Replace with your actual key

// API endpoints to test
$endpoints = [
    'balance' => 'https://api.stability.ai/v1/user/balance',
    'engines' => 'https://api.stability.ai/v1/engines/list'
];

$results = [];

// Test API key with balance check
$response = wp_remote_get($endpoints['balance'], [
    'headers' => [
        'Authorization' => 'Bearer ' . $api_key
    ]
]);

if (is_wp_error($response)) {
    $results['balance'] = [
        'success' => false,
        'message' => $response->get_error_message()
    ];
} else {
    $status = wp_remote_retrieve_response_code($response);
    $body = json_decode(wp_remote_retrieve_body($response), true);

    $results['balance'] = [
        'success' => $status === 200,
        'status' => $status,
        'body' => $body
    ];
}

// Test available engines
$response = wp_remote_get($endpoints['engines'], [
    'headers' => [
        'Authorization' => 'Bearer ' . $api_key
    ]
]);

if (is_wp_error($response)) {
    $results['engines'] = [
        'success' => false,
        'message' => $response->get_error_message()
    ];
} else {
    $status = wp_remote_retrieve_response_code($response);
    $body = json_decode(wp_remote_retrieve_body($response), true);

    $results['engines'] = [
        'success' => $status === 200,
        'status' => $status,
        'body' => $body
    ];
}

// Get system info
$results['system'] = [
    'php_version' => phpversion(),
    'wordpress_version' => get_bloginfo('version'),
    'memory_limit' => ini_get('memory_limit'),
    'max_execution_time' => ini_get('max_execution_time'),
    'upload_max_filesize' => ini_get('upload_max_filesize'),
    'post_max_size' => ini_get('post_max_size'),
    'allow_url_fopen' => ini_get('allow_url_fopen') ? 'Yes' : 'No',
    'curl_enabled' => function_exists('curl_version') ? 'Yes' : 'No'
];

wp_send_json_success($results);

});

// Add this temporary test page to check your API connection
add_action(‘admin_menu’, function() {
add_management_page(
‘Stability API Test’,
‘Stability API Test’,
‘manage_options’,
‘stability-api-test’,
function() {
?>

Stability AI API Test

This page allows you to test your Stability AI API connection.

            <div id="api-test-results" style="background: #f8f9fa; padding: 15px; border-radius: 5px; margin-top: 20px;">
                <p>Click the button below to test your API connection:</p>
                <button id="test-api-button" class="button button-primary">Test API Connection</button>

                <div id="test-loading" style="display: none; margin-top: 15px;">
                    <p><span class="spinner is-active" style="float: none; margin: 0 5px 0 0;"></span> Testing API connection...</p>
                </div>

                <div id="test-results" style="display: none; margin-top: 15px;">
                    <h3>Results:</h3>
                    <pre id="results-content" style="background: #fff; padding: 15px; border: 1px solid #ddd; overflow: auto; max-height: 400px;"></pre>
                </div>
            </div>

            <script>
            jQuery(document).ready(function($) {
                $('#test-api-button').on('click', function() {
                    $('#test-loading').show();
                    $('#test-results').hide();

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'test_stability_api'
                        },
                        success: function(response) {
                            $('#test-loading').hide();
                            $('#test-results').show();

                            if (response.success) {
                                const data = response.data;
                                let output = '';

                                // System Info
                                output += "===== SYSTEM INFORMATION =====\n";
                                for (const [key, value] of Object.entries(data.system)) {
                                    output += `${key}: ${value}\n`;
                                }
                                output += "\n";

                                // Balance Check
                                output += "===== API BALANCE CHECK =====\n";
                                if (data.balance.success) {
                                    output += "Status: SUCCESS (HTTP 200)\n";
                                    output += `Credits: ${JSON.stringify(data.balance.body, null, 2)}\n`;
                                } else {
                                    output += "Status: FAILED\n";
                                    output += `HTTP Status: ${data.balance.status}\n`;
                                    if (data.balance.body) {
                                        output += `Response: ${JSON.stringify(data.balance.body, null, 2)}\n`;
                                    }
                                    if (data.balance.message) {
                                        output += `Error: ${data.balance.message}\n`;
                                    }
                                }
                                output += "\n";

                                // Engines Check
                                output += "===== API ENGINES CHECK =====\n";
                                if (data.engines.success) {
                                    output += "Status: SUCCESS (HTTP 200)\n";
                                    output += "Available Engines:\n";
                                    if (data.engines.body && Array.isArray(data.engines.body)) {
                                        data.engines.body.forEach((engine, index) => {
                                            output += `${index + 1}. ${engine.id} (${engine.name})\n`;
                                        });
                                    } else {
                                        output += `Raw response: ${JSON.stringify(data.engines.body, null, 2)}\n`;
                                    }
                                } else {
                                    output += "Status: FAILED\n";
                                    output += `HTTP Status: ${data.engines.status}\n`;
                                    if (data.engines.body) {
                                        output += `Response: ${JSON.stringify(data.engines.body, null, 2)}\n`;
                                    }
                                    if (data.engines.message) {
                                        output += `Error: ${data.engines.message}\n`;
                                    }
                                }

                                // Display results
                                $('#results-content').text(output);
                            } else {
                                $('#results-content').text('Error: ' + response.data);
                            }
                        },
                        error: function(xhr, status, error) {
                            $('#test-loading').hide();
                            $('#test-results').show();
                            $('#results-content').text('AJAX Error: ' + error);
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }
);

});