<?php
/**
 * Real-Time AI Chat System - Setup Verification
 * Run this to verify everything is configured correctly
 */

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

// Set headers for JSON response
header('Content-Type: application/json');

$checks = [];
$allGood = true;

// 1. Check files exist
$files_to_check = [
    'Backend API' => '/auth-system/api/chat-ai.php',
    'Frontend JS' => '/assets/js/responsive-chat-ai.js',
    'Chat Config' => '/auth-system/chat-config.php',
    'Setup Script' => '/auth-system/api/setup-chat-db.php',
    'Chat Widget HTML' => '/includes/chat-widget.html',
    'Chat Widget CSS' => '/assets/css/responsive-chat.css'
];

foreach ($files_to_check as $name => $file) {
    $path = __DIR__ . $file;
    $exists = file_exists($path);
    $checks[$name] = [
        'status' => $exists ? 'OK' : 'MISSING',
        'path' => $file
    ];
    if (!$exists) $allGood = false;
}

// 2. Check environment configuration
$env_file = __DIR__ . '/.env';
$env_exists = file_exists($env_file);
$checks['Environment File'] = [
    'status' => $env_exists ? 'OK' : 'MISSING',
    'message' => 'Create .env file in root directory with OPENAI_API_KEY'
];
if (!$env_exists) $allGood = false;

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

$db_ok = false;
if (isset($connection) && $connection) {
    // Check if tables exist
    $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;
        }
    }
    
    if (empty($missing_tables)) {
        $checks['Database Tables'] = [
            'status' => 'OK',
            'message' => 'All 3 required tables exist'
        ];
        $db_ok = true;
    } else {
        $checks['Database Tables'] = [
            'status' => 'MISSING',
            'message' => 'Missing tables: ' . implode(', ', $missing_tables),
            'action' => 'Run: php auth-system/api/setup-chat-db.php'
        ];
        $allGood = false;
    }
} else {
    $checks['Database Connection'] = [
        'status' => 'ERROR',
        'message' => 'Could not connect to database'
    ];
    $allGood = false;
}

// 4. Check API configuration
if ($env_exists) {
    $env_contents = file_get_contents($env_file);
    $has_api_key = strpos($env_contents, 'OPENAI_API_KEY=') !== false;
    
    if ($has_api_key) {
        // Extract API key (don't show full key for security)
        preg_match('/OPENAI_API_KEY=(.+)/', $env_contents, $matches);
        $key = trim($matches[1] ?? '');
        $key_masked = substr($key, 0, 10) . '...' . substr($key, -4);
        
        $checks['OpenAI API Key'] = [
            'status' => 'OK',
            'configured' => $key_masked,
            'message' => 'API key is configured (shown masked)'
        ];
    } else {
        $checks['OpenAI API Key'] = [
            'status' => 'MISSING',
            'message' => 'Add OPENAI_API_KEY to .env file'
        ];
        $allGood = false;
    }
}

// 5. Check pages have chat widget
$pages = [
    'index.php',
    'about.php',
    'blog.php',
    'gallery.php',
    'shop.php',
    'contact.php',
    'project.php'
];

$pages_with_chat = [];
$pages_without_chat = [];

foreach ($pages as $page) {
    $path = __DIR__ . '/' . $page;
    if (file_exists($path)) {
        $content = file_get_contents($path);
        if (strpos($content, 'responsive-chat-ai.js') !== false) {
            $pages_with_chat[] = $page;
        } else {
            $pages_without_chat[] = $page;
        }
    }
}

$pages_status = count($pages_without_chat) === 0 ? 'OK' : 'INCOMPLETE';
$checks['Pages with Chat Widget'] = [
    'status' => $pages_status,
    'pages_updated' => count($pages_with_chat),
    'pages_missing' => $pages_without_chat
];

if (!empty($pages_without_chat)) $allGood = false;

// Final result
$result = [
    'overall_status' => $allGood ? 'READY' : 'NOT_READY',
    'checks' => $checks,
    'setup_instructions' => [
        '1' => 'Verify all files exist (all listed above)',
        '2' => 'Create .env file in root with: OPENAI_API_KEY=sk-your-key',
        '3' => 'Run setup script: php auth-system/api/setup-chat-db.php',
        '4' => 'Test chat on any page (look for chat icon bottom-right)',
        '5' => 'Check browser console (F12) for any errors'
    ],
    'next_steps' => $allGood ? [
        'Test chat widget on index.php',
        'Send a test message',
        'Verify AI response is received',
        'Check database for saved messages'
    ] : [
        'Fix missing items listed above',
        'Run setup script',
        'Verify environment configuration',
        'Then test the chat widget'
    ]
];

// If accessed via browser, format nicely
if (php_sapi_name() !== 'cli') {
    echo '<pre style="font-family: monospace; padding: 20px; background: #f5f5f5; border-radius: 8px;">';
    echo '🔍 REAL-TIME AI CHAT SYSTEM - SETUP VERIFICATION';
    echo "\n" . str_repeat('=', 60) . "\n";
    
    echo "\n📊 Overall Status: " . ($result['overall_status'] === 'READY' ? 
        '✅ READY' : '❌ NOT READY');
    
    echo "\n\n📋 Checks Performed:\n";
    echo str_repeat('-', 60) . "\n";
    
    foreach ($result['checks'] as $check_name => $check_result) {
        $status_icon = $check_result['status'] === 'OK' ? '✅' : 
                      ($check_result['status'] === 'MISSING' ? '❌' : '⚠️');
        
        echo "\n$status_icon $check_name\n";
        echo "   Status: " . $check_result['status'] . "\n";
        
        if (isset($check_result['message'])) {
            echo "   Info: " . $check_result['message'] . "\n";
        }
        if (isset($check_result['path'])) {
            echo "   Path: " . $check_result['path'] . "\n";
        }
        if (isset($check_result['action'])) {
            echo "   Action: " . $check_result['action'] . "\n";
        }
        if (isset($check_result['configured'])) {
            echo "   Key: " . $check_result['configured'] . "\n";
        }
        if (isset($check_result['pages_updated'])) {
            echo "   Updated: " . $check_result['pages_updated'] . " pages\n";
            if (!empty($check_result['pages_missing'])) {
                echo "   Missing: " . implode(', ', $check_result['pages_missing']) . "\n";
            }
        }
    }
    
    echo "\n" . str_repeat('=', 60) . "\n";
    echo "\n📝 Next Steps:\n";
    echo str_repeat('-', 60) . "\n";
    foreach ($result['next_steps'] as $step) {
        echo "• $step\n";
    }
    
    echo "\n" . str_repeat('=', 60) . "\n";
    echo "\n📚 Documentation: See REAL_TIME_AI_SETUP.md\n";
    echo '</pre>';
} else {
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
?>
