<?php
/**
 * 流量配额重置问题修复和诊断工具
 * 运行此脚本来检查和修复流量重置问题
 */

// 包含必要文件
include_once("./includes/common.php");

// 检查是否是管理员访问
if (!$islogin) {
    echo "请先登录管理员账号！\n";
    exit;
}

echo "=== 彩虹外链网盘流量配额重置问题诊断工具 ===\n\n";

// 1. 检查配置
echo "1. 检查系统配置:\n";
echo "   traffic_quota_reset_interval: " . ($conf['traffic_quota_reset_interval'] ?? '未设置') . " 天\n";
echo "   user_traffic_quota: " . ($conf['user_traffic_quota'] ?? '未设置') . " MB\n";
echo "   traffic_log_enabled: " . ($conf['traffic_log_enabled'] ?? '未设置') . "\n\n";

// 2. 检查数据库字段
echo "2. 检查数据库字段:\n";
$columns = $DB->getAll("SHOW COLUMNS FROM pre_user");
$required_fields = ['traffic_used', 'last_traffic_reset_time', 'u_traffic_quota'];

foreach ($required_fields as $field) {
    $exists = false;
    foreach ($columns as $col) {
        if ($col['Field'] == $field) {
            $exists = true;
            break;
        }
    }
    echo "   {$field}: " . ($exists ? "✅ 存在" : "❌ 缺失") . "\n";
}

// 3. 检查用户重置状态
echo "\n3. 检查用户重置状态:\n";
$users = $DB->getAll("SELECT uid, username, traffic_used, last_traffic_reset_time FROM pre_user LIMIT 10");

foreach ($users as $user) {
    echo "   用户ID: {$user['uid']} ({$user['username']})\n";
    echo "     已用流量: " . round($user['traffic_used'] / 1048576, 2) . " MB\n";
    echo "     上次重置: " . ($user['last_traffic_reset_time'] ?? '从未重置') . "\n";
    
    if ($user['last_traffic_reset_time']) {
        $reset_interval = isset($conf['traffic_quota_reset_interval']) ? intval($conf['traffic_quota_reset_interval']) : 30;
        if ($reset_interval > 0) {
            $last_reset = strtotime($user['last_traffic_reset_time']);
            $next_reset = $last_reset + ($reset_interval * 86400);
            $days_until = ceil(($next_reset - time()) / 86400);
            echo "     下次重置: " . date('Y-m-d H:i:s', $next_reset) . " ({$days_until}天后)\n";
        }
    }
    echo "\n";
}

// 4. 检查流量日志
echo "4. 检查流量日志:\n";
$log_count = $DB->getColumn("SELECT COUNT(*) FROM pre_traffic_log");
echo "   总日志条数: {$log_count}\n";

if ($log_count > 0) {
    $recent_log = $DB->getRow("SELECT created_at FROM pre_traffic_log ORDER BY created_at DESC LIMIT 1");
    echo "   最近记录时间: {$recent_log['created_at']}\n";
}
echo "\n";

// 5. 修复选项
echo "5. 修复选项:\n";
echo "   [1] 修复缺失的数据库字段\n";
echo "   [2] 重置所有用户的重置时间\n";
echo "   [3] 检查特定用户的状态\n";
echo "   [4] 测试重置功能\n";
echo "   [0] 退出\n\n";

echo "请选择操作 (0-4): ";

// 读取用户输入（如果在命令行运行）
if (php_sapi_name() === 'cli') {
    $handle = fopen("php://stdin", "r");
    $choice = trim(fgets($handle));
    fclose($handle);
    
    switch ($choice) {
        case '1':
            echo "\n正在修复数据库字段...\n";
            
            // 检查并添加缺失字段
            foreach ($required_fields as $field) {
                $exists = false;
                foreach ($columns as $col) {
                    if ($col['Field'] == $field) {
                        $exists = true;
                        break;
                    }
                }
                
                if (!$exists) {
                    switch ($field) {
                        case 'traffic_used':
                            $DB->exec("ALTER TABLE pre_user ADD `traffic_used` bigint(20) unsigned NOT NULL DEFAULT '0'");
                            echo "   ✅ 添加了 traffic_used 字段\n";
                            break;
                        case 'last_traffic_reset_time':
                            $DB->exec("ALTER TABLE pre_user ADD `last_traffic_reset_time` datetime DEFAULT NULL");
                            $DB->exec("UPDATE pre_user SET last_traffic_reset_time = NOW() WHERE last_traffic_reset_time IS NULL");
                            echo "   ✅ 添加了 last_traffic_reset_time 字段\n";
                            break;
                        case 'u_traffic_quota':
                            $DB->exec("ALTER TABLE pre_user ADD `u_traffic_quota` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '用户额外流量配额'");
                            echo "   ✅ 添加了 u_traffic_quota 字段\n";
                            break;
                    }
                }
            }
            echo "数据库字段修复完成！\n";
            break;
            
        case '2':
            echo "\n正在重置所有用户的重置时间...\n";
            $result = $DB->exec("UPDATE pre_user SET last_traffic_reset_time = NOW()");
            echo "   ✅ 重置了 {$result} 个用户的重置时间\n";
            break;
            
        case '3':
            echo "\n请输入用户ID: ";
            $handle = fopen("php://stdin", "r");
            $uid = intval(trim(fgets($handle)));
            fclose($handle);
            
            if ($uid > 0) {
                $status = get_traffic_reset_status($uid);
                if ($status) {
                    echo "用户 {$uid} 的流量重置状态:\n";
                    echo "   重置周期: {$status['reset_interval_days']} 天\n";
                    echo "   上次重置: {$status['last_reset_time']}\n";
                    echo "   已用流量: " . round($status['traffic_used'] / 1048576, 2) . " MB\n";
                    echo "   下次重置: {$status['next_reset_time']}\n";
                    echo "   距离重置: {$status['days_until_reset']} 天\n";
                } else {
                    echo "用户 {$uid} 不存在！\n";
                }
            }
            break;
            
        case '4':
            echo "\n正在测试重置功能...\n";
            // 获取第一个用户进行测试
            $test_user = $DB->getRow("SELECT uid FROM pre_user LIMIT 1");
            if ($test_user) {
                $result = reset_traffic_quota_if_needed($test_user['uid']);
                echo "   测试用户 {$test_user['uid']}: " . ($result ? "需要重置" : "无需重置") . "\n";
            } else {
                echo "   没有找到测试用户\n";
            }
            break;
            
        default:
            echo "退出\n";
            break;
    }
}

echo "\n=== 诊断完成 ===\n";
echo "如果问题仍然存在，请检查:\n";
echo "1. 系统日志文件\n";
echo "2. 数据库错误日志\n";
echo "3. PHP错误日志\n";
?>