<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

// 初始化宝塔API
$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'];

// 获取网站目录路径 - 像jk.php一样直接构建路径
$os_type = isset($bt['czzt']) ? $bt['czzt'] : 'Linux';
$web_path = ($os_type == 'Linux' ? '/www/wwwroot/' : 'D:/wwwroot/') . $user['user'];

/**
 * 解析大小字符串（如 "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;
}

// 获取网页空间使用量
$web_usage = 0;
$dir_size_result = $bt_api->GetDirSize($web_path);
$web_usage = parse_size_string($dir_size_result);

// 获取数据库使用量
$db_usage = 0;
$db_info = $bt_api->sqlkjhq($user['sqldb']);
if ($db_info && isset($db_info['data_size'])) {
    $db_usage = parse_size_string($db_info['data_size']);
}

// 获取流量使用量（从数据库读取，与traffic.php页面一致）
$traffic_usage = 0;

// 获取本月流量累计
$month_start = date('Y-m-01');
$user_id_escaped = intval($user['id']);
$month_stats = $DB->query("SELECT SUM(traffic_total) as total FROM `traffic_stats` WHERE `user_id`='{$user_id_escaped}' 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');
    $user_id_escaped = intval($user['id']);
    $today_traffic = $DB->get_row("SELECT * FROM `traffic_stats` WHERE `user_id`='{$user_id_escaped}' AND `stat_date`='{$today}'");
    if ($today_traffic) {
        $traffic_usage = $today_traffic['traffic_total'];
    }
}

// 转换为GB
$web_usage_gb = round($web_usage / (1024 * 1024 * 1024), 2);
$db_usage_gb = round($db_usage / (1024 * 1024 * 1024), 2);
$traffic_usage_gb = round($traffic_usage / (1024 * 1024 * 1024), 2);

// 获取限制值 - wypj和sypj以MB存储，llxz以GB存储
$web_limit_mb = floatval($user['wypj']); // MB
$db_limit_mb = floatval($user['sypj']); // MB
$web_limit = $web_limit_mb / 1024; // 转换为GB用于计算百分比
$db_limit = $db_limit_mb / 1024; // 转换为GB用于计算百分比
$traffic_limit = floatval($user['llxz']); // GB

// 计算百分比
$web_percent = $web_limit > 0 ? min(100, round(($web_usage_gb / $web_limit) * 100, 1)) : 0;
$db_percent = $db_limit > 0 ? min(100, round(($db_usage_gb / $db_limit) * 100, 1)) : 0;
$traffic_percent = $traffic_limit > 0 ? min(100, round(($traffic_usage_gb / $traffic_limit) * 100, 1)) : 0;

// 获取本月流量累计
$month_ago = date('Y-m-d', strtotime('-30 days'));
$user_id_escaped = intval($user['id']);
$month_traffic = $DB->query("SELECT SUM(traffic_total) as total FROM `traffic_stats` WHERE `user_id`='{$user_id_escaped}' AND `stat_date` >= '{$month_ago}'");
$month_data = $DB->fetch($month_traffic);
$traffic_month_usage = $month_data['total'] ? round($month_data['total'] / (1024 * 1024 * 1024), 2) : $traffic_usage_gb;
$traffic_month_percent = $traffic_limit > 0 ? min(100, round(($traffic_month_usage / $traffic_limit) * 100, 1)) : 0;

// 格式化显示函数 - 根据大小自动选择单位
function formatUsage($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';
    }
}

// 智能格式化限制值 - 直接以MB为单位显示（数据库中已存储为MB）
function formatLimitSmart($mb) {
    $mb = floatval($mb);
    if ($mb <= 0) {
        return '0 MB';
    }
    
    // 直接显示MB
    if ($mb == intval($mb)) {
        return intval($mb) . ' MB';
    } else {
        return round($mb, 2) . ' MB';
    }
}

// 格式化流量限制 - 以GB为单位显示
function formatTrafficLimit($gb) {
    $gb = floatval($gb);
    if ($gb <= 0) {
        return '0 GB';
    }
    
    // 如果是整数，不显示小数
    if ($gb == intval($gb)) {
        return intval($gb) . ' GB';
    } else {
        return round($gb, 2) . ' GB';
    }
}

// 格式化显示值
$web_usage_display = formatUsage($web_usage);
$db_usage_display = formatUsage($db_usage);
$traffic_usage_display = formatUsage($traffic_usage);
$traffic_month_display = formatUsage($month_data['total'] ?? 0);
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css?v=20260224_1">

<div class="alert">
    <i class="fas fa-info-circle"></i> <?php 
        $welcome_msg = L('welcome_message', 'dashboard');
        $welcome_msg = str_replace('{site_name}', $conf['name'], $welcome_msg);
        $welcome_msg = str_replace('{username}', $user['user'], $welcome_msg);
        $welcome_msg = str_replace('{status}', $user['zt'], $welcome_msg);
        echo $welcome_msg;
    ?>
</div>

<div class="stats-grid">
    <div class="stat-card">
        <div class="icon">
            <i class="fas fa-hdd"></i>
        </div>
        <h4><?php echo L('web_space', 'dashboard'); ?></h4>
        <div class="number"><?php echo $web_usage_display; ?> <small>/ <?php echo formatLimitSmart($web_limit_mb); ?></small></div>
        <div class="progress">
            <div class="progress-bar <?php echo $web_percent > 90 ? 'danger' : ($web_percent > 70 ? 'warning' : ''); ?>" style="width: <?php echo $web_percent; ?>%"></div>
        </div>
        <div class="usage-info">
            <?php echo L('used', 'dashboard'); ?> <strong><?php echo $web_percent; ?>%</strong>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon">
            <i class="fas fa-database"></i>
        </div>
        <h4><?php echo L('database_space', 'dashboard'); ?></h4>
        <div class="number"><?php echo $db_usage_display; ?> <small>/ <?php echo formatLimitSmart($db_limit_mb); ?></small></div>
        <div class="progress">
            <div class="progress-bar <?php echo $db_percent > 90 ? 'danger' : ($db_percent > 70 ? 'warning' : ''); ?>" style="width: <?php echo $db_percent; ?>%"></div>
        </div>
        <div class="usage-info">
            <?php echo L('used', 'dashboard'); ?> <strong><?php echo $db_percent; ?>%</strong>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon">
            <i class="fas fa-tachometer-alt"></i>
        </div>
        <h4><?php echo L('monthly_traffic', 'dashboard'); ?></h4>
        <div class="number"><?php echo $traffic_month_display; ?> <small>/ <?php echo formatTrafficLimit($traffic_limit); ?></small></div>
        <div class="progress">
            <div class="progress-bar <?php echo $traffic_month_percent > 90 ? 'danger' : ($traffic_month_percent > 70 ? 'warning' : ''); ?>" style="width: <?php echo $traffic_month_percent; ?>%"></div>
        </div>
        <div class="usage-info">
            <?php echo L('used', 'dashboard'); ?> <strong><?php echo $traffic_month_percent; ?>%</strong> | <?php echo L('reset_monthly', 'dashboard'); ?>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon">
            <i class="fas fa-calendar-alt"></i>
        </div>
        <h4><?php echo L('expire_date', 'dashboard'); ?></h4>
        <?php
        // 处理到期时间格式（支持日期字符串和时间戳）
        $dqsj_raw = $user['dqsj'];
        if (is_numeric($dqsj_raw) && strlen($dqsj_raw) > 8) {
            // 是时间戳格式
            $dqsj_display = date('Y-m-d', intval($dqsj_raw));
            $end = intval($dqsj_raw);
        } else {
            // 是日期字符串
            $dqsj_display = $dqsj_raw;
            $end = strtotime($dqsj_raw);
        }
        ?>
        <div class="number number-expire"><?php echo $dqsj_display; ?></div>
        <div class="progress">
            <?php 
            // 计算到期倒计时
            $now = time();
            $days_left = $end > $now ? ceil(($end - $now) / (60 * 60 * 24)) : 0;
            $expired = $end <= $now;
            ?>
            <div class="progress-bar <?php echo $expired ? 'danger' : ($days_left < 7 ? 'warning' : ''); ?>" style="width: 100%"></div>
        </div>
        <div class="usage-info">
            <strong><?php 
                if ($expired) {
                    echo L('expired', 'dashboard');
                } else {
                    $days_text = L('days_left', 'dashboard');
                    echo str_replace('{days}', $days_left, $days_text);
                }
            ?></strong>
        </div>
    </div>
</div>

<div class="row" style="margin: 0 -10px;">
    <div class="col-md-6" style="padding: 0 10px;">
        <div class="card h-100">
            <h3><i class="fas fa-info-circle"></i> <?php echo L('host_info', 'dashboard'); ?></h3>
            <table class="table mb-0">
                <tbody>
                    <tr>
                        <td class="text-muted" style="width: 100px;"><?php echo L('username', 'dashboard'); ?></td>
                        <td class="font-weight-bold"><?php echo $user['user']; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted"><?php echo L('product_type', 'dashboard'); ?></td>
                        <td class="font-weight-bold"><?php echo $user['cplx']; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted"><?php echo L('status', 'dashboard'); ?></td>
                        <td>
                            <?php echo $user['zt'] == '正常' ? '<span class="badge badge-success">'.L('normal', 'dashboard').'</span>' : '<span class="badge badge-danger">'.$user['zt'].'</span>'; ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <div class="col-md-6" style="padding: 0 10px;">
        <div class="card h-100">
            <h3><i class="fas fa-globe"></i> <?php echo L('domain_list', 'dashboard'); ?></h3>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="text-muted border-0 font-weight-normal" style="font-size: 13px;"><?php echo L('domain', 'dashboard'); ?></th>
                            <th class="text-muted border-0 font-weight-normal" style="font-size: 13px; width: 60px;"><?php echo L('status', 'dashboard'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="ymListBody">
                        <tr id="ymListLoadingRow">
                            <td colspan="2" class="text-center text-muted py-4">
                                <div id="ymListLoading"><i class="fas fa-spinner fa-spin mr-2"></i><?php echo L('loading', 'common'); ?>...</div>
                                <div id="ymListContent" style="display: none;"></div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <h3><i class="fas fa-bullhorn"></i> <?php echo L('announcements', 'dashboard'); ?></h3>
    <div id="homeAnnouncement" class="mb-3">
        <p class="text-muted small mb-0"><?php echo L('loading', 'common'); ?>...</p>
    </div>
    <div>
        <a href="notifications.php" class="btn btn-link btn-sm pl-0"><?php echo L('view_more', 'dashboard'); ?> <i class="fas fa-arrow-right"></i></a>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<style>
/* =========================================
   Dashboard Grid Layout (Mobile Only)
   ========================================= */

@media (max-width: 768px) {
    /* 容器：强制双列网格 */
    .stats-grid {
        display: grid !important;
        grid-template-columns: 1fr 1fr !important;
        gap: 12px !important;
        padding: 0 5px !important;
    }

    /* 卡片：垂直布局 */
    .stat-card {
        display: flex !important;
        flex-direction: column !important;
        justify-content: space-between !important;
        align-items: flex-start !important;
        padding: 16px !important;
        height: 140px !important;
        background: #fff;
        border-radius: 16px !important;
        box-shadow: 0 2px 6px rgba(0,0,0,0.04) !important;
        margin-bottom: 0 !important;
        position: relative;
        overflow: hidden;
        border: 1px solid rgba(0,0,0,0.02) !important;
    }

    /* 图标：左上角 */
    .stat-card .icon {
        width: 36px !important;
        height: 36px !important;
        border-radius: 10px !important;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px !important;
        margin-bottom: 12px !important;
        background-color: #e6f4ea !important;
        color: #188038 !important;
        margin-right: 0 !important;
    }

    /* 数值 */
    .stat-card .number {
        font-size: 18px !important;
        font-weight: 600 !important;
        color: #111827 !important;
        line-height: 1.2;
        margin-bottom: 4px !important;
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .stat-card .number.number-expire {
        font-size: 18px !important;
        font-weight: 600 !important;
        letter-spacing: 0.2px;
    }
    
    .stat-card .number small {
        font-size: 13px !important;
        color: #5f6368;
        font-weight: 400;
        margin-left: 2px;
    }

    /* 标题 */
    .stat-card h4 {
        font-size: 12px !important;
        color: #6b7280 !important;
        margin: 0 !important;
        font-weight: 500;
    }

    /* 进度条 */
    .stat-card .progress {
        position: absolute !important;
        bottom: 0 !important;
        left: 0 !important;
        width: 100% !important;
        height: 3px !important;
        border-radius: 0 !important;
        background-color: transparent !important;
        margin: 0 !important;
    }
    .stat-card .progress .progress-bar {
        border-radius: 0 !important;
        opacity: 0.8;
    }

    /* 隐藏辅助信息 */
    .stat-card .usage-info {
        display: none !important;
    }

    /* =========================================
       域名列表卡片手机版优化
       ========================================= */
    /* 域名列表卡片：全宽显示 */
    .col-md-6 {
        width: 100% !important;
        padding: 0 5px !important;
        margin-bottom: 12px !important;
    }
    
    /* 域名列表卡片样式优化 */
    .col-md-6 .card {
        border-radius: 12px !important;
        box-shadow: 0 2px 6px rgba(0,0,0,0.04) !important;
        border: 1px solid rgba(0,0,0,0.02) !important;
    }
    
    .col-md-6 .card h3 {
        font-size: 14px !important;
        padding: 12px 16px !important;
        margin: 0 !important;
        border-bottom: 1px solid #f0f0f0 !important;
    }
    
    /* 域名列表表格优化 */
    .col-md-6 .table-responsive {
        border: none !important;
    }
    
    .col-md-6 .table {
        font-size: 13px !important;
    }
    
    .col-md-6 .table thead th {
        font-size: 12px !important;
        padding: 10px 16px !important;
        background-color: #fafafa !important;
    }
    
    .col-md-6 .table tbody td {
        padding: 10px 16px !important;
    }
    
    /* 域名链接样式 */
    .col-md-6 .table tbody td a {
        font-size: 13px !important;
        color: #1a73e8 !important;
        word-break: break-all !important;
    }
    
    /* 状态标签优化 */
    .col-md-6 .table .badge {
        font-size: 11px !important;
        padding: 4px 8px !important;
        border-radius: 4px !important;
    }
    
    /* 主机信息卡片也全宽 */
    .row .col-md-6:first-child {
        width: 100% !important;
    }
}
</style>
<!-- 邮箱绑定模态框 -->
<div id="emailBindModal" class="modal" style="display: none; position: fixed; z-index: 9999; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5);">
    <div class="modal-content" style="background-color: #fff; margin: 10% auto; padding: 0; border-radius: 8px; width: 90%; max-width: 400px; box-shadow: 0 4px 20px rgba(0,0,0,0.15);">
        <div class="modal-header" style="padding: 16px 20px; border-bottom: 1px solid #e8eaed; display: flex; align-items: center; justify-content: space-between;">
            <h3 style="margin: 0; font-size: 16px; color: #202124;"><i class="fas fa-envelope" style="color: #1a73e8; margin-right: 8px;"></i>绑定邮箱</h3>
            <span class="close" style="cursor: pointer; font-size: 24px; color: #5f6368;" onclick="closeEmailModal()">&times;</span>
        </div>
        <div class="modal-body" style="padding: 20px;">
            <p style="color: #5f6368; font-size: 13px; margin-bottom: 16px;">系统要求绑定邮箱后才能继续使用，请输入您的邮箱地址。</p>
            <div class="form-group" style="margin-bottom: 16px;">
                <label style="display: block; font-size: 13px; color: #5f6368; margin-bottom: 6px;">邮箱地址</label>
                <input type="email" id="bindEmail" class="form-control" placeholder="请输入邮箱地址" style="width: 100%; padding: 10px 12px; border: 1px solid #dadce0; border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                <small id="emailError" style="color: #d93025; font-size: 12px; display: none;">请输入有效的邮箱地址</small>
            </div>
        </div>
        <div class="modal-footer" style="padding: 16px 20px; border-top: 1px solid #e8eaed; text-align: right;">
            <button type="button" class="btn btn-primary" onclick="saveEmail()" style="background: #1a73e8; color: #fff; border: none; padding: 10px 24px; border-radius: 4px; font-size: 14px; cursor: pointer;">
                <i class="fas fa-save"></i> 保存
            </button>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    loadHomeAnnouncement();
    loadDomainList();
    
    // 检查是否需要绑定邮箱
    checkEmailBinding();
});

// 检查邮箱绑定状态
function checkEmailBinding() {
    <?php if ($conf['zjyxbd'] == 'true' && empty($user['email'])): ?>
    // 后台开启了邮箱绑定，且用户未绑定邮箱
    setTimeout(function() {
        $('#emailBindModal').fadeIn(300);
    }, 500);
    <?php endif; ?>
}

// 关闭模态框
function closeEmailModal() {
    // 如果必须绑定，不允许关闭
    <?php if ($conf['zjyxbd'] == 'true' && empty($user['email'])): ?>
    alert('请先绑定邮箱才能继续使用');
    return;
    <?php endif; ?>
    $('#emailBindModal').fadeOut(200);
}

// 保存邮箱
function saveEmail() {
    var email = $('#bindEmail').val().trim();
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    
    if (!email || !emailRegex.test(email)) {
        $('#emailError').show();
        $('#bindEmail').css('border-color', '#d93025');
        return;
    }
    
    $('#emailError').hide();
    $('#bindEmail').css('border-color', '#dadce0');
    
    // 发送AJAX请求保存邮箱
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'bindemail',
            email: email
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                alert('邮箱绑定成功！');
                $('#emailBindModal').fadeOut(200);
                // 刷新页面以更新状态
                location.reload();
            } else {
                alert(data.msg || '绑定失败，请重试');
            }
        },
        error: function() {
            alert('网络错误，请重试');
        }
    });
}

// 点击模态框外部不关闭（当必须绑定时）
$('#emailBindModal').on('click', function(e) {
    if (e.target === this) {
        <?php if ($conf['zjyxbd'] == 'true' && empty($user['email'])): ?>
        alert('请先绑定邮箱才能继续使用');
        <?php else: ?>
        closeEmailModal();
        <?php endif; ?>
    }
});

// 回车键保存
$('#bindEmail').on('keypress', function(e) {
    if (e.which === 13) {
        saveEmail();
    }
});

function loadDomainList() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { egn: 'getymlist' },
        dataType: 'json',
        success: function(data) {
            renderDomainList(data);
        },
        error: function(xhr, status, error) {
            console.log('加载域名列表失败: ' + status);
            $('#ymListBody').html('<tr><td colspan="2" class="text-center text-muted py-4">加载失败</td></tr>');
        }
    });
}

function renderDomainList(data) {
    var html = '';
    if (data.code === 'success' && data.domains && data.domains.length > 0) {
        for (var i = 0; i < data.domains.length; i++) {
            var domain = data.domains[i];
            var port = domain.port || 80;
            var url = (port == 80 || port == 443) ? (port == 443 ? 'https://' : 'http://') + domain.name : 'http://' + domain.name + ':' + port;
            html += '<tr class="align-middle">' +
                    '<td class="py-2"><a href="' + url + '" target="_blank" class="text-dark text-decoration-none" title="点击访问" style="font-size: 14px;">' + domain.name + '</a></td>' +
                    '<td><span class="badge badge-success" style="font-size: 12px; font-weight: normal;">正常</span></td>' +
                    '</tr>';
        }
    } else {
        html = '<tr><td colspan="2" class="text-center text-muted py-4">暂无域名</td></tr>';
    }
    $('#ymListBody').html(html);
}

function loadHomeAnnouncement() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { egn: 'getnotifications' },
        dataType: 'json',
        success: function(data) {
            renderHomeAnnouncement(data);
        },
        error: function() {
            $('#homeAnnouncement').html('<p style="color: #5f6368;">加载失败</p>');
        }
    });
}

function renderHomeAnnouncement(data) {
    var html = '';
    if (data.code === 'success' && data.notifications && data.notifications.length > 0) {
        var topNotif = data.notifications[0];
        var badge = topNotif.status === 'unread' ? '<span class="badge badge-success ml-2">新</span>' : '';
        html = '<div class="cursor-pointer" onclick="location.href=\'notifications.php\'">' +
               '<h5 class="text-primary mb-2">' + topNotif.title + badge + '</h5>' +
               '<p class="text-muted small mb-1 text-truncate" style="max-width: 100%;">' + 
               topNotif.content.substring(0, 100) + (topNotif.content.length > 100 ? '...' : '') + '</p>' +
               '<small class="text-muted">' + topNotif.created_at + '</small>' +
               '</div>';
    } else {
        html = '<p class="text-muted small mb-0">暂无公告</p>';
    }
    $('#homeAnnouncement').html(html);
}

</script>
