<?php
session_start();
require_once __DIR__ . '/../../../MPHX/common.php';
$user = check_user();
if (!$user) {
    header('Location: /user/login.php');
    exit;
}

// 获取用户详细信息
$user_info = $DB->get_row("SELECT * FROM `zj` WHERE `user`='{$user['user']}'");

// 获取统计数据 - 从zj表获取
// yms字段存储域名数量或域名列表，如果用户有主机则至少显示1个网站
$web_count = 1; // 默认显示1个网站
$db_count = $user_info && !empty($user_info['sqluser']) && $user_info['sqluser'] != '0' ? 1 : 0;
$ftp_count = $user_info && !empty($user_info['ftpuser']) && $user_info['ftpuser'] != '0' ? 1 : 0;

// 初始化宝塔API和获取实际使用量
$bt_api = null;
$web_usage_bytes = 0;
$db_usage_bytes = 0;

if ($user_info && $user_info['btid']) {
    $bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user_info['btid']}'");
    if ($bt) {
        require_once __DIR__ . '/../../../class.php';
        $bt_api = new bt_api();
        
        // 根据安全访问开关动态设置协议
        $protocol = isset($bt['aqfw']) && $bt['aqfw'] == 'true' ? 'https' : 'http';
        $bt_api->BT_PANEL = $protocol . '://' . $bt['ip'] . ':' . $bt['dk'];
        $bt_api->BT_KEY = $bt['key'];
        
        // 获取网页空间实际使用量
        $os_type = isset($bt['czzt']) ? $bt['czzt'] : 'Linux';
        $web_path = ($os_type == 'Linux' ? '/www/wwwroot/' : 'D:/wwwroot/') . $user['user'];
        $dir_size_result = $bt_api->GetDirSize($web_path);
        $web_usage_bytes = parse_size_string($dir_size_result);
        
        // 获取数据库实际使用量
        if (!empty($user_info['sqldb'])) {
            $sql_info = $bt_api->sqlkjhq($user_info['sqldb']);
            if ($sql_info && isset($sql_info['data_size'])) {
                $db_usage_bytes = parse_size_string($sql_info['data_size']);
            }
        }
    }
}

/**
 * 解析大小字符串（如 "11.10KB"）为字节数
 */
function parse_size_string($size_str) {
    if (is_numeric($size_str)) {
        return intval($size_str);
    }
    
    if (preg_match('/([\d.]+)\s*([KMGT]?B)/i', $size_str, $matches)) {
        $value = floatval($matches[1]);
        $unit = strtoupper($matches[2]);
        switch ($unit) {
            case 'B': return $value;
            case 'KB': return $value * 1024;
            case 'MB': return $value * 1024 * 1024;
            case 'GB': return $value * 1024 * 1024 * 1024;
            case 'TB': return $value * 1024 * 1024 * 1024 * 1024;
        }
    }
    
    return 0;
}

// 获取备份数量 - 通过API获取
$backup_count = 0;
if ($user_info && $user_info['btid'] && $user_info['webid'] && $bt_api) {
    // 获取网站备份列表
    $site_backups = $bt_api->GetBackupList(0, $user_info['webid']);
    if (isset($site_backups['data']) && is_array($site_backups['data'])) {
        $backup_count += count($site_backups['data']);
    }
    
    // 获取数据库备份列表
    if (!empty($user_info['sqldb'])) {
        // 先获取数据库列表找到数据库ID
        $url = $bt_api->BT_PANEL . '/data?action=getData';
        $p_data = $bt_api->GetKeyData();
        $p_data['table'] = 'databases';
        $p_data['search'] = $user_info['sqldb'];
        $p_data['limit'] = 10;
        $p_data['p'] = 1;
        
        $result = $bt_api->HttpPostCookie($url, $p_data);
        $db_list = json_decode($result, true);
        
        if (isset($db_list['data']) && is_array($db_list['data'])) {
            foreach ($db_list['data'] as $db_item) {
                if (isset($db_item['name']) && $db_item['name'] == $user_info['sqldb'] && isset($db_item['id'])) {
                    $db_backups = $bt_api->GetBackupList(1, $db_item['id']);
                    if (isset($db_backups['data']) && is_array($db_backups['data'])) {
                        $backup_count += count($db_backups['data']);
                    }
                    break;
                }
            }
        }
    }
}

// 获取最近操作日志 - 仅保留最新4条
$logs = $DB->get_all("SELECT * FROM `log` WHERE `user`='{$user['user']}' ORDER BY `id` DESC LIMIT 4");

// 处理日志内容，隐藏根目录路径
function formatLogContent($content, $username) {
    if (empty($content)) return '';
    
    // 匹配 /www/wwwroot/用户名/ 前缀并替换为 /
    $pattern = '/\/www\/wwwroot\/' . preg_quote($username, '/') . '\//i';
    $content = preg_replace($pattern, '/', $content);
    
    // 也处理 Windows 路径格式 D:/wwwroot/用户名/
    $pattern = '/D:\/wwwroot\/' . preg_quote($username, '/') . '\//i';
    $content = preg_replace($pattern, '/', $content);
    
    return $content;
}

// 获取系统公告（所有用户可见的）- 仅保留最新4条
$announcements = $DB->get_all("SELECT * FROM `notifications` WHERE `target_type`='all' ORDER BY `create_time` DESC LIMIT 4");

// 计算资源使用百分比和限制 - 从zj表获取
$web_space = array('used' => '', 'total' => '0MB', 'percent' => 0);
$db_space = array('used' => '', 'total' => '0MB', 'percent' => 0);
$traffic = array('used' => '', 'total' => '0GB', 'percent' => 0);

// 辅助函数：提取数值和单位（支持纯数字，默认单位为MB）
function extractValueAndUnit($str, $defaultUnit = 'M') {
    $str = trim($str);
    if (preg_match('/^([0-9.]+)\s*([KMGT]?B?)$/i', $str, $matches)) {
        $value = $matches[1];
        $unit = strtoupper($matches[2]);
        // 标准化单位
        if (empty($unit) || $unit == 'B') $unit = $defaultUnit;
        return array('value' => floatval($value), 'unit' => $unit, 'original' => $str);
    }
    // 纯数字，使用默认单位
    return array('value' => floatval(preg_replace('/[^0-9.]/', '', $str)), 'unit' => $defaultUnit, 'original' => $str);
}

// 辅助函数：智能格式化存储大小（根据原始单位显示）
function formatSizeSmart($value, $unit, $displayUnit = null) {
    $unit = strtoupper($unit);
    // 统一转换为字节
    $bytes = $value;
    switch ($unit) {
        case 'T':
        case 'TB':
            $bytes *= 1024 * 1024 * 1024 * 1024;
            break;
        case 'G':
        case 'GB':
            $bytes *= 1024 * 1024 * 1024;
            break;
        case 'M':
        case 'MB':
            $bytes *= 1024 * 1024;
            break;
        case 'K':
        case 'KB':
            $bytes *= 1024;
            break;
    }
    
    // 如果指定了显示单位，使用指定单位
    if ($displayUnit) {
        $displayUnit = strtoupper($displayUnit);
        switch ($displayUnit) {
            case 'T':
            case 'TB':
                $value = $bytes / (1024 * 1024 * 1024 * 1024);
                $unit = 'TB';
                break;
            case 'G':
            case 'GB':
                $value = $bytes / (1024 * 1024 * 1024);
                $unit = 'GB';
                break;
            case 'M':
            case 'MB':
                $value = $bytes / (1024 * 1024);
                $unit = 'MB';
                break;
            case 'K':
            case 'KB':
                $value = $bytes / 1024;
                $unit = 'KB';
                break;
            default:
                $value = $bytes / (1024 * 1024);
                $unit = 'MB';
        }
    } else {
        // 默认以MB为单位显示
        $value = $bytes / (1024 * 1024);
        $unit = 'MB';
    }
    
    // 如果是整数，不显示小数；否则最多显示2位小数
    if ($value == intval($value)) {
        return intval($value) . $unit;
    } else {
        return round($value, 2) . $unit;
    }
}

// 辅助函数：智能格式化流量大小（根据大小自动选择MB或GB）
function formatTrafficSize($bytes) {
    if ($bytes >= 1024 * 1024 * 1024) {
        // GB级别
        $gb = $bytes / (1024 * 1024 * 1024);
        return number_format($gb, 2) . ' GB';
    } elseif ($bytes >= 1024 * 1024) {
        // MB级别
        $mb = $bytes / (1024 * 1024);
        return number_format($mb, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        // KB级别
        $kb = $bytes / 1024;
        return number_format($kb, 2) . ' KB';
    } else {
        // Bytes级别
        return $bytes . ' B';
    }
}

if ($user_info) {
    // 网页空间使用率 - 使用宝塔API获取的实际使用量
    if (!empty($user_info['wypj'])) {
        // 获取限制值（总量）
        $info = extractValueAndUnit($user_info['wypj'], 'M');
        $web_space['total'] = formatSizeSmart($info['value'], $info['unit']);
        
        // 使用实际获取的使用量
        if ($web_usage_bytes > 0) {
            $web_space['used'] = formatSizeSmart($web_usage_bytes / (1024 * 1024), 'M');
            if ($info['value'] > 0) {
                $web_space['percent'] = min(100, round((($web_usage_bytes / (1024 * 1024)) / $info['value']) * 100));
            }
        }
    }
    
    // 数据库空间使用率 - 使用宝塔API获取的实际使用量
    if (!empty($user_info['sypj'])) {
        // 获取限制值（总量）
        $info = extractValueAndUnit($user_info['sypj'], 'M');
        $db_space['total'] = formatSizeSmart($info['value'], $info['unit']);
        
        // 使用实际获取的使用量
        if ($db_usage_bytes > 0) {
            $db_space['used'] = formatSizeSmart($db_usage_bytes / (1024 * 1024), 'M');
            if ($info['value'] > 0) {
                $db_space['percent'] = min(100, round((($db_usage_bytes / (1024 * 1024)) / $info['value']) * 100));
            }
        }
    }
    
    // 流量使用率 - llxz以GB为单位存储，显示也用GB
    if (!empty($user_info['llxz'])) {
        // 获取限制值（总量）
        $info = extractValueAndUnit($user_info['llxz'], 'G');
        $traffic['total'] = formatSizeSmart($info['value'], $info['unit'], 'G');
        
        // 从数据库获取实际流量使用量
        $traffic_usage = 0;
        $month_start = date('Y-m-01');
        $month_stats = $DB->query("SELECT SUM(traffic_total) as total FROM `traffic_stats` WHERE `user_id`='{$user['id']}' AND `stat_date` >= '{$month_start}'");
        if ($month_stats) {
            $month_row = $DB->fetch($month_stats);
            $traffic_usage = isset($month_row['total']) ? intval($month_row['total']) : 0;
        }
        
        // 如果本月没有数据，尝试获取今日流量
        if ($traffic_usage == 0) {
            $today = date('Y-m-d');
            $today_traffic = $DB->get_row("SELECT * FROM `traffic_stats` WHERE `user_id`='{$user['id']}' AND `stat_date`='{$today}'");
            if ($today_traffic) {
                $traffic_usage = $today_traffic['traffic_total'];
            }
        }
        
        // 格式化显示流量使用量（自动选择MB或GB）
        if ($traffic_usage > 0) {
            $traffic['used'] = formatTrafficSize($traffic_usage);
            if ($info['value'] > 0) {
                $traffic['percent'] = min(100, round((($traffic_usage / (1024 * 1024 * 1024)) / $info['value']) * 100));
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>控制台首页</title>
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="/templates/modern/assets/css/dashboard.css?v=<?php echo time(); ?>">
</head>
<body>
    <div class="dashboard">
        <!-- 欢迎栏 -->
        <div class="welcome-bar">
            <div class="welcome-text">
                <h1>欢迎回来，<?php echo htmlspecialchars($user['user']); ?></h1>
                <p><?php echo date('Y年m月d日 l'); ?></p>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-grid">
            <div class="stat-card blue">
                <div class="stat-icon">
                    <i class="fas fa-globe"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-value"><?php echo $web_count; ?></div>
                    <div class="stat-label">网站数量</div>
                </div>
            </div>
            <div class="stat-card green">
                <div class="stat-icon">
                    <i class="fas fa-database"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-value"><?php echo $db_count; ?></div>
                    <div class="stat-label">数据库</div>
                </div>
            </div>
            <div class="stat-card orange">
                <div class="stat-icon">
                    <i class="fas fa-exchange-alt"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-value"><?php echo $ftp_count; ?></div>
                    <div class="stat-label">FTP账户</div>
                </div>
            </div>
            <div class="stat-card purple">
                <div class="stat-icon">
                    <i class="fas fa-archive"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-value"><?php echo $backup_count; ?></div>
                    <div class="stat-label">备份数量</div>
                </div>
            </div>
        </div>

        <!-- 资源使用和快捷操作 -->
        <div class="two-columns">
            <div class="panel">
                <div class="panel-header">
                    <i class="fas fa-chart-pie"></i>
                    <span>资源使用</span>
                </div>
                <div class="panel-body">
                    <div class="resource-item">
                        <div class="resource-info">
                            <span>网页空间: <?php echo ($web_space['used'] ? $web_space['used'] . ' / ' : '') . $web_space['total']; ?></span>
                            <span><?php echo $web_space['percent']; ?>%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill blue" style="width: <?php echo $web_space['percent']; ?>%"></div>
                        </div>
                    </div>
                    <div class="resource-item">
                        <div class="resource-info">
                            <span>数据库空间: <?php echo ($db_space['used'] ? $db_space['used'] . ' / ' : '') . $db_space['total']; ?></span>
                            <span><?php echo $db_space['percent']; ?>%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill green" style="width: <?php echo $db_space['percent']; ?>%"></div>
                        </div>
                    </div>
                    <div class="resource-item">
                        <div class="resource-info">
                            <span>本月流量: <?php echo ($traffic['used'] ? $traffic['used'] . ' / ' : '') . $traffic['total']; ?></span>
                            <span><?php echo $traffic['percent']; ?>%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill orange" style="width: <?php echo $traffic['percent']; ?>%"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="panel">
                <div class="panel-header">
                    <i class="fas fa-bolt"></i>
                    <span>快捷操作</span>
                </div>
                <div class="panel-body">
                    <div class="quick-actions">
                        <a href="/user/index.php?page=set&gn=php" class="quick-action" target="_parent">
                            <i class="fas fa-code"></i>
                            <span>PHP版本</span>
                        </a>
                        <a href="/user/index.php?page=set&gn=ym" class="quick-action" target="_parent">
                            <i class="fas fa-globe"></i>
                            <span>域名管理</span>
                        </a>
                        <a href="/user/index.php?page=set&gn=wjt" class="quick-action" target="_parent">
                            <i class="fas fa-file-code"></i>
                            <span>伪静态</span>
                        </a>
                        <a href="/user/index.php?page=file" class="quick-action" target="_parent">
                            <i class="fas fa-folder"></i>
                            <span>文件管理</span>
                        </a>
                        <a href="/user/index.php?page=backup" class="quick-action" target="_parent">
                            <i class="fas fa-archive"></i>
                            <span>创建备份</span>
                        </a>
                        <a href="/user/index.php?page=traffic" class="quick-action" target="_parent">
                            <i class="fas fa-chart-line"></i>
                            <span>流量统计</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近操作和公告 -->
        <div class="two-columns">
            <div class="panel">
                <div class="panel-header">
                    <i class="fas fa-history"></i>
                    <span>最近操作</span>
                    <a href="/user/logs.php" class="view-more" target="_parent">查看更多</a>
                </div>
                <div class="panel-body">
                    <?php if ($logs): ?>
                    <div class="log-list">
                        <?php foreach ($logs as $log): ?>
                        <div class="log-item">
                            <div class="log-icon">
                                <i class="fas fa-circle"></i>
                            </div>
                            <div class="log-content">
                                <div class="log-text"><?php echo htmlspecialchars(formatLogContent($log['lr'] ?? $log['content'] ?? '', $user['user'])); ?></div>
                                <div class="log-time"><?php echo $log['date'] ?? $log['time'] ?? ''; ?></div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <p>暂无操作记录</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="panel">
                <div class="panel-header">
                    <i class="fas fa-bullhorn"></i>
                    <span>系统公告</span>
                    <a href="/user/notifications.php" class="view-more" target="_parent">查看更多</a>
                </div>
                <div class="panel-body">
                    <?php if ($announcements): ?>
                    <div class="announcement-list">
                        <?php foreach ($announcements as $ann): ?>
                        <div class="announcement-item">
                            <div class="announcement-title"><?php echo htmlspecialchars($ann['title']); ?></div>
                            <div class="announcement-time"><?php echo $ann['create_time'] ?? $ann['time'] ?? ''; ?></div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <p>暂无公告</p>
                    </div>
                    <?php endif; ?>
                    </div>
            </div>
        </div>
    </div>
</body>
</html>
