<?php
/**
 * 诊断脚本 - 用于排查 500 错误
 */

// 显示所有错误
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>HuSNS 诊断报告</h1>";
echo "<pre>";

// 1. PHP 版本
echo "PHP 版本: " . PHP_VERSION . "\n";

// 2. 检查必需文件
echo "\n=== 检查必需文件 ===\n";
$requiredFiles = [
    'config.php',
    'config.secret.php',
    'core/Helper.php',
    'core/Security.php',
    'core/Database.php',
    'core/View.php',
    'core/Controller.php',
    'core/RateLimiter.php',
    'core/Cache.php',
    'core/Logger.php',
    'core/ExceptionHandler.php',
    'core/App.php',
];

foreach ($requiredFiles as $file) {
    $path = __DIR__ . '/' . $file;
    $exists = file_exists($path);
    echo "$file: " . ($exists ? "OK" : "MISSING") . "\n";
}

// 3. 尝试加载核心文件
echo "\n=== 加载核心文件 ===\n";
try {
    require_once __DIR__ . '/config.php';
    echo "config.php: OK\n";
    
    require_once __DIR__ . '/core/Logger.php';
    echo "Logger.php: OK\n";
    
    require_once __DIR__ . '/core/ExceptionHandler.php';
    echo "ExceptionHandler.php: OK\n";
    
    require_once __DIR__ . '/core/RateLimiter.php';
    echo "RateLimiter.php: OK\n";
    
    require_once __DIR__ . '/core/Cache.php';
    echo "Cache.php: OK\n";
    
} catch (Exception $e) {
    echo "错误: " . $e->getMessage() . "\n";
    echo "文件: " . $e->getFile() . "\n";
    echo "行号: " . $e->getLine() . "\n";
}

// 4. 检查数据库连接
echo "\n=== 数据库连接测试 ===\n";
try {
    $db = Database::getInstance();
    echo "数据库连接: OK\n";
    
    // 测试查询
    $result = $db->fetch("SELECT 1 as test");
    echo "数据库查询: " . ($result['test'] == 1 ? "OK" : "FAILED") . "\n";
    
} catch (Exception $e) {
    echo "数据库错误: " . $e->getMessage() . "\n";
}

// 5. 检查缓存目录
echo "\n=== 缓存目录 ===\n";
$cacheDir = __DIR__ . '/cache';
if (is_dir($cacheDir)) {
    echo "缓存目录存在: OK\n";
    echo "可写: " . (is_writable($cacheDir) ? "OK" : "FAILED") . "\n";
} else {
    echo "缓存目录不存在，正在创建...\n";
    if (mkdir($cacheDir, 0755, true)) {
        echo "创建成功: OK\n";
    } else {
        echo "创建失败: FAILED\n";
    }
}

// 6. 检查日志目录
echo "\n=== 日志目录 ===\n";
$logDir = __DIR__ . '/logs';
if (is_dir($logDir)) {
    echo "日志目录存在: OK\n";
    echo "可写: " . (is_writable($logDir) ? "OK" : "FAILED") . "\n";
} else {
    echo "日志目录不存在\n";
}

echo "\n=== 诊断完成 ===\n";
echo "</pre>";
