<?php
/**
 * Chat API Diagnostic Tool
 * Helps troubleshoot connection issues
 */

header('Content-Type: application/json');

// Enable all error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);

$diagnostics = [];

// 1. Check .env file
$diagnostics['env_file'] = [
    'exists' => file_exists(__DIR__ . '/.env'),
    'path' => __DIR__ . '/.env',
    'readable' => is_readable(__DIR__ . '/.env')
];

// 2. Load environment
require_once __DIR__ . '/config/env-loader.php';

$diagnostics['openai_api_key'] = [
    'set' => !empty(getenv('OPENAI_API_KEY')),
    'value_sample' => substr(getenv('OPENAI_API_KEY') ?: '', 0, 20) . '...'
];

// 3. Check database connection
require_once __DIR__ . '/config/db.php';

$db_status = 'unknown';
$db_error = 'not_checked';

try {
    if (isset($connection) && $connection) {
        if ($connection->connect_error) {
            $db_status = 'error';
            $db_error = $connection->connect_error;
        } else {
            $db_status = 'connected';
            
            // Check tables
            $tables = ['chat_sessions', 'chat_messages', 'chat_settings'];
            $missing_tables = [];
            foreach ($tables as $table) {
                $result = $connection->query("SHOW TABLES LIKE '$table'");
                if ($result->num_rows === 0) {
                    $missing_tables[] = $table;
                }
            }
            $db_error = empty($missing_tables) ? 'all_tables_exist' : implode(', ', $missing_tables);
        }
    } else {
        $db_status = 'error';
        $db_error = 'connection_variable_not_set';
    }
} catch (Exception $e) {
    $db_status = 'error';
    $db_error = $e->getMessage();
}

$diagnostics['database'] = [
    'status' => $db_status,
    'details' => $db_error
];

// 4. Check API files
$diagnostics['api_files'] = [
    'chat_ai_php' => file_exists(__DIR__ . '/auth-system/api/chat-ai.php'),
    'chat_config_php' => file_exists(__DIR__ . '/auth-system/chat-config.php'),
    'env_loader_php' => file_exists(__DIR__ . '/config/env-loader.php')
];

// 5. Test API endpoint
$test_action = $_GET['test'] ?? '';

if ($test_action === 'get_status') {
    $diagnostic_response = [
        'diagnostics' => $diagnostics
    ];
    
    // Try calling the status check
    try {
        require_once __DIR__ . '/auth-system/chat-config.php';
        
        $status = [
            'success' => true,
            'openai_key' => !empty(getenv('OPENAI_API_KEY')),
            'database' => $db_status === 'connected'
        ];
        
        $diagnostic_response['api_status'] = $status;
    } catch (Exception $e) {
        $diagnostic_response['api_error'] = $e->getMessage();
    }
    
    echo json_encode($diagnostic_response, JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        'diagnostics' => $diagnostics,
        'instructions' => [
            'full_test' => 'Add ?test=get_status to see full API status',
            'check_logs' => 'Check browser console (F12) for errors',
            'verify_env' => 'Ensure .env file exists with OPENAI_API_KEY'
        ]
    ], JSON_PRETTY_PRINT);
}
?>
