<?php
$title = '控制面板';
include __DIR__ . '/head.php';

$user_count = $DB->getColumn("SELECT COUNT(*) FROM pre_user");
$qq_count_cloud = intval($DB->getColumn("SELECT COUNT(*) FROM pre_qq"));
$qq_online_cloud = intval($DB->getColumn("SELECT COUNT(*) FROM pre_qq WHERE login_zt = '1'"));
$qq_count_dg = 0;
$qq_online_dg = 0;
$dg_tables = $DB->getColumn("SHOW TABLES LIKE 'pre_dg_qq'", 0);
if($dg_tables){
    $qq_count_dg = intval($DB->getColumn("SELECT COUNT(*) FROM pre_dg_qq"));
    $qq_online_dg = intval($DB->getColumn("SELECT COUNT(*) FROM pre_dg_qq WHERE login_zt = '1'"));
}
$qq_count = $qq_count_cloud + $qq_count_dg;
$qq_online = $qq_online_cloud + $qq_online_dg;
$tixian_pending = $DB->getColumn("SELECT COUNT(*) FROM pre_tixian WHERE status = '0'");
$today_start = date('Y-m-d 00:00:00');
$today_pay = $DB->getColumn("SELECT COALESCE(SUM(money), 0) FROM pre_pay WHERE status = '1' AND addtime >= '{$today_start}'");
$today_user = $DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE addtime >= '{$today_start}'");
$total_income = $DB->getColumn("SELECT COALESCE(SUM(money), 0) FROM pre_pay WHERE status = '1'");
$qzone_count = 0;
$qzone_valid = 0;
$qzone_vip = 0;
$qzone_tables = $DB->getColumn("SHOW TABLES LIKE '" . DBQZ . "qzone_qq'", 0);
if($qzone_tables){
    $qzone_count = intval($DB->getColumn("SELECT COUNT(*) FROM " . DBQZ . "qzone_qq"));
    $qzone_valid = intval($DB->getColumn("SELECT COUNT(*) FROM " . DBQZ . "qzone_qq WHERE login_status=0"));
    $qzone_vip = intval($DB->getColumn("SELECT COUNT(*) FROM " . DBQZ . "qzone_qq WHERE vip_time > NOW()"));
}
$recent_orders = $DB->getAll("SELECT trade_no, zid, name, input, money, type, addtime, endtime FROM pre_pay WHERE status = '1' ORDER BY endtime DESC LIMIT 10");
$recent_users = $DB->getAll("SELECT zid, user, rmb, vip, addtime FROM pre_user ORDER BY zid DESC LIMIT 10");
$weekly_labels = [];
$weekly_regs = [];
$weekly_income = [];
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-{$i} days"));
    $weekly_labels[] = date('m-d', strtotime($d));
    $weekly_regs[] = intval($DB->getColumn("SELECT COUNT(*) FROM pre_user WHERE addtime >= '{$d} 00:00:00' AND addtime <= '{$d} 23:59:59'"));
    $weekly_income[] = floatval($DB->getColumn("SELECT COALESCE(SUM(money),0) FROM pre_pay WHERE status='1' AND endtime >= '{$d} 00:00:00' AND endtime <= '{$d} 23:59:59'"));
}
?>
<div class="p-4 space-y-4">
    <div id="updateNotice" class="hidden rounded-xl border border-amber-200 bg-amber-50 p-4">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
                <div class="text-sm text-amber-700">系统更新提醒</div>
                <div id="updateNoticeText" class="text-amber-900 font-medium mt-1"></div>
            </div>
            <a href="./update.php" class="inline-flex items-center justify-center px-3 py-2 rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition-colors text-sm">
                去更新页面
            </a>
        </div>
    </div>

    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
        <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-4 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-blue-100 text-sm">用户总数</p>
                    <p class="text-2xl font-bold mt-1"><?php echo number_format($user_count); ?></p>
                    <p class="text-blue-200 text-xs mt-1">今日新增 +<?php echo $today_user; ?></p>
                </div>
                <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-users text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-4 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-green-100 text-sm">QQ账号</p>
                    <p class="text-2xl font-bold mt-1"><?php echo number_format($qq_count); ?>/<?php echo $qq_online; ?></p>
                    <?php if($dg_tables): ?>
                        <p class="text-green-200 text-xs mt-1">云端 <?php echo $qq_count_cloud; ?>/<?php echo $qq_online_cloud; ?> · 代挂 <?php echo $qq_count_dg; ?>/<?php echo $qq_online_dg; ?></p>
                    <?php endif; ?>
                </div>
                <div class="flex flex-col items-end gap-1">
                    <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                        <i class="fab fa-qq text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-gradient-to-br from-amber-500 to-orange-500 rounded-xl p-4 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-amber-100 text-sm">今日收入</p>
                    <p class="text-2xl font-bold mt-1"><?php echo number_format($today_pay, 2); ?></p>
                    <p class="text-amber-200 text-xs mt-1">总收入 <?php echo number_format($total_income, 2); ?></p>
                </div>
                <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-yen-sign text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-gradient-to-br from-rose-500 to-pink-500 rounded-xl p-4 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-rose-100 text-sm">待处理提现</p>
                    <p class="text-2xl font-bold mt-1"><?php echo number_format($tixian_pending); ?></p>
                    <a href="./tixian.php" class="text-rose-200 text-xs hover:text-white">立即处理 →</a>
                </div>
                <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-hand-holding-usd text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-gradient-to-br from-cyan-500 to-sky-600 rounded-xl p-4 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-cyan-100 text-sm">秒赞QQ统计</p>
                    <p class="text-2xl font-bold mt-1"><?php echo number_format($qzone_count); ?></p>
                    <p class="text-cyan-200 text-xs mt-1">有效 <?php echo $qzone_valid; ?> / VIP <?php echo $qzone_vip; ?></p>
                </div>
                <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-thumbs-up text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
                <h3 class="font-medium text-gray-800 text-base"><i class="fas fa-toggle-on text-indigo-500 mr-2"></i>系统开关</h3>
            </div>
            <div class="p-4 flex flex-col gap-3 min-h-72 justify-center">
                <div class="flex items-center justify-between p-3 min-h-16 bg-gradient-to-r from-cyan-50 to-sky-50 rounded-xl border border-cyan-100">
                    <div class="min-w-0">
                        <p class="font-semibold text-gray-800 text-lg flex items-center">云端系统 <span id="cloud_enabled_chip" class="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">已关闭</span></p>
                        <p class="text-sm text-gray-500 mt-0.5">关闭后用户端将隐藏云端相关功能</p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" id="cloud_enabled" class="sr-only peer" onchange="saveSystemSwitch('cloud_enabled', this.checked)">
                        <div class="relative w-12 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:left-[26px] after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-cyan-600"></div>
                    </label>
                </div>
                <div class="flex items-center justify-between p-3 min-h-16 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-xl border border-emerald-100">
                    <div class="min-w-0">
                        <p class="font-semibold text-gray-800 text-lg flex items-center">代挂系统 <span id="dg_open_chip" class="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">已关闭</span></p>
                        <p class="text-sm text-gray-500 mt-0.5">关闭后用户端将隐藏代挂相关功能</p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" id="dg_open" class="sr-only peer" onchange="saveSystemSwitch('dg_open', this.checked)">
                        <div class="relative w-12 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:left-[26px] after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-600"></div>
                    </label>
                </div>
                <div class="flex items-center justify-between p-3 min-h-16 bg-gradient-to-r from-purple-50 to-pink-50 rounded-xl border border-purple-100">
                    <div class="min-w-0">
                        <p class="font-semibold text-gray-800 text-lg flex items-center">秒赞系统 <span id="qzone_open_chip" class="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">已关闭</span></p>
                        <p class="text-sm text-gray-500 mt-0.5">关闭后用户端将隐藏秒赞相关功能</p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" id="qzone_open" class="sr-only peer" onchange="saveSystemSwitch('qzone_open', this.checked)">
                        <div class="relative w-12 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:left-[26px] after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                    </label>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
                <h3 class="font-medium text-gray-800"><i class="fas fa-chart-bar text-blue-500 mr-2"></i>近七天注册与收入</h3>
            </div>
            <div class="p-4">
                <div class="h-72">
                    <canvas id="weeklyChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800">快捷操作</h3>
        </div>
        <div class="p-3 grid grid-cols-3 sm:grid-cols-6 gap-2">
            <a href="./user.php" class="flex flex-col items-center p-2 rounded-xl bg-blue-50 hover:bg-blue-100 transition-colors">
                <div class="w-9 h-9 bg-blue-500 rounded-lg flex items-center justify-center mb-1.5">
                    <i class="fas fa-user-plus text-white"></i>
                </div>
                <span class="text-[11px] text-gray-700 font-medium whitespace-nowrap">用户管理</span>
            </a>
            <a href="./qqlist.php" class="flex flex-col items-center p-2 rounded-xl bg-green-50 hover:bg-green-100 transition-colors">
                <div class="w-9 h-9 bg-green-500 rounded-lg flex items-center justify-center mb-1.5">
                    <i class="fab fa-qq text-white"></i>
                </div>
                <span class="text-[11px] text-gray-700 font-medium whitespace-nowrap">QQ管理</span>
            </a>
            <a href="./goods.php" class="flex flex-col items-center p-2 rounded-xl bg-amber-50 hover:bg-amber-100 transition-colors">
                <div class="w-9 h-9 bg-amber-500 rounded-lg flex items-center justify-center mb-1.5">
                    <i class="fas fa-box text-white"></i>
                </div>
                <span class="text-[11px] text-gray-700 font-medium whitespace-nowrap">商品管理</span>
            </a>
            <a href="./kami.php" class="flex flex-col items-center p-2 rounded-xl bg-purple-50 hover:bg-purple-100 transition-colors">
                <div class="w-9 h-9 bg-purple-500 rounded-lg flex items-center justify-center mb-1.5">
                    <i class="fas fa-ticket-alt text-white"></i>
                </div>
                <span class="text-[11px] text-gray-700 font-medium whitespace-nowrap">卡密管理</span>
            </a>
            <a href="./site.php" class="flex flex-col items-center p-2 rounded-xl bg-indigo-50 hover:bg-indigo-100 transition-colors">
                <div class="w-9 h-9 bg-indigo-500 rounded-lg flex items-center justify-center mb-1.5">
                    <i class="fas fa-cog text-white"></i>
                </div>
                <span class="text-[11px] text-gray-700 font-medium whitespace-nowrap">系统设置</span>
            </a>
            <a href="./pay.php" class="flex flex-col items-center p-2 rounded-xl bg-pink-50 hover:bg-pink-100 transition-colors">
                <div class="w-9 h-9 bg-pink-500 rounded-lg flex items-center justify-center mb-1.5">
                    <i class="fas fa-credit-card text-white"></i>
                </div>
                <span class="text-[11px] text-gray-700 font-medium whitespace-nowrap">支付配置</span>
            </a>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 flex items-center justify-between">
                <h3 class="font-medium text-gray-800">最近订单</h3>
                <a href="./record.php" class="text-xs text-indigo-500 hover:text-indigo-700">查看全部</a>
            </div>
            <div class="divide-y divide-gray-100">
                <?php
                if($recent_orders):
                foreach($recent_orders as $order):
                    $order_name = str_replace('99^|^', '', $order['name']);
                ?>
                <div class="px-4 py-3 flex items-center justify-between hover:bg-gray-50 cursor-pointer order-item"
                     data-trade_no="<?php echo htmlspecialchars($order['trade_no']); ?>"
                     data-name="<?php echo htmlspecialchars($order_name); ?>"
                     data-money="<?php echo $order['money']; ?>"
                     data-zid="<?php echo $order['zid']; ?>"
                     data-input="<?php echo htmlspecialchars($order['input'] ?? '-'); ?>"
                     data-type="<?php echo htmlspecialchars($order['type'] ?? '-'); ?>"
                     data-addtime="<?php echo $order['addtime']; ?>"
                     data-endtime="<?php echo $order['endtime']; ?>">
                    <div class="flex items-center gap-3 min-w-0">
                        <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                            <i class="fas fa-check text-green-500 text-xs"></i>
                        </div>
                        <div class="min-w-0">
                            <p class="text-sm text-gray-800 truncate"><?php echo htmlspecialchars($order_name); ?></p>
                            <p class="text-xs text-gray-400"><?php echo substr($order['endtime'], 0, 16); ?></p>
                        </div>
                    </div>
                    <div class="text-right flex-shrink-0">
                        <p class="text-sm font-semibold text-green-600">+¥<?php echo $order['money']; ?></p>
                    </div>
                </div>
                <?php endforeach; else: ?>
                <div class="px-4 py-8 text-center text-gray-400 text-sm">暂无订单数据</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 flex items-center justify-between">
                <h3 class="font-medium text-gray-800">最近注册</h3>
                <a href="./user.php" class="text-xs text-indigo-500 hover:text-indigo-700">查看全部</a>
            </div>
            <div class="divide-y divide-gray-100">
                <?php if($recent_users): foreach($recent_users as $user): ?>
                <div class="px-4 py-3 flex items-center justify-between hover:bg-gray-50">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-user text-blue-500 text-xs"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-800"><?php echo htmlspecialchars($user['user']); ?></p>
                            <p class="text-xs text-gray-400"><?php echo substr($user['addtime'], 5, 11); ?></p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="px-2 py-0.5 bg-indigo-100 text-indigo-600 rounded text-xs font-medium">VIP<?php echo $user['vip']; ?></span>
                        <span class="text-sm text-gray-600">¥<?php echo $user['rmb']; ?></span>
                    </div>
                </div>
                <?php endforeach; else: ?>
                <div class="px-4 py-8 text-center text-gray-400 text-sm">暂无用户数据</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800">系统信息</h3>
        </div>
        <div class="p-4 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div class="flex items-center gap-2">
                <i class="fas fa-code-branch text-gray-400"></i>
                <span class="text-gray-500">版本</span>
                <span class="text-gray-800 font-medium ml-auto"><?php echo htmlspecialchars($conf['version'] ?? '7.0'); ?></span>
            </div>
            <div class="flex items-center gap-2">
                <i class="fab fa-php text-gray-400"></i>
                <span class="text-gray-500">PHP</span>
                <span class="text-gray-800 font-medium ml-auto"><?php echo phpversion(); ?></span>
            </div>
            <div class="flex items-center gap-2">
                <i class="fas fa-clock text-gray-400"></i>
                <span class="text-gray-500">时间</span>
                <span class="text-gray-800 font-medium ml-auto"><?php echo date('H:i:s'); ?></span>
            </div>
            <div class="flex items-center gap-2">
                <i class="fas fa-palette text-gray-400"></i>
                <span class="text-gray-500">模板</span>
                <span class="text-gray-800 font-medium ml-auto"><?php echo htmlspecialchars($conf['template'] ?? 'default'); ?></span>
            </div>
        </div>
    </div>
</div>

<div id="appModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div id="modalBody" class="px-5 py-4 overflow-y-auto overflow-x-hidden min-w-0" style="word-break:break-word;overflow-wrap:break-word;"></div>
            <div id="modalFooter" class="px-5 py-3 border-t border-gray-100 hidden"></div>
        </div>
    </div>
</div>

<script src="../assets/js/chart.umd.min.js"></script>
<script>
function checkUpdateNotice() {
    $.ajax({
        url: 'ajax.php?act=check_update',
        type: 'POST',
        dataType: 'json',
        success: function(res) {
            if(!res || res.code !== 1 || !res.data) return;
            var version = res.data.version || '';
            var text = version ? ('检测到新版本 V' + version + '，建议尽快更新。') : '检测到新版本，建议尽快更新。';
            $('#updateNoticeText').text(text);
            $('#updateNotice').removeClass('hidden');
        }
    });
}

function renderWeeklyChart() {
    var labels = <?php echo json_encode($weekly_labels, JSON_UNESCAPED_UNICODE); ?>;
    var regs = <?php echo json_encode($weekly_regs); ?>;
    var income = <?php echo json_encode($weekly_income); ?>;
    var ctx = document.getElementById('weeklyChart').getContext('2d');
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '注册数',
                    data: regs,
                    backgroundColor: '#4f46e5'
                },
                {
                    label: '收入(¥)',
                    data: income,
                    backgroundColor: '#f59e0b'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: { boxWidth: 12, boxHeight: 12 }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

function openModal(title, content) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

$('.order-item').on('click', function() {
    var trade_no = $(this).data('trade_no');
    var name = $(this).data('name');
    var money = $(this).data('money');
    var zid = $(this).data('zid');
    var input = $(this).data('input');
    var type = $(this).data('type');
    var addtime = $(this).data('addtime');
    var endtime = $(this).data('endtime');

    var wrap = 'word-break:break-word;overflow-wrap:break-word;';
    var html = '<div class="space-y-3 min-w-0" style="' + wrap + '">';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">订单号</div><div class="font-mono text-sm text-gray-800">' + trade_no + '</div></div>';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">商品名称</div><div class="text-gray-800" style="white-space:pre-wrap;' + wrap + '">' + name + '</div></div>';
    html += '<div class="grid grid-cols-2 gap-3">';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">支付金额</div><div class="font-bold text-lg text-green-600">¥' + money + '</div></div>';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">支付方式</div><div class="text-gray-800">' + type + '</div></div>';
    html += '</div>';
    html += '<div class="grid grid-cols-2 gap-3">';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">用户ID</div><div class="text-gray-800">' + zid + '</div></div>';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">购买QQ</div><div class="text-gray-800">' + input + '</div></div>';
    html += '</div>';
    html += '<div class="grid grid-cols-2 gap-3">';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">下单时间</div><div class="text-sm text-gray-800">' + addtime + '</div></div>';
    html += '<div class="bg-gray-50 rounded-lg p-3"><div class="text-xs text-gray-500 mb-1">完成时间</div><div class="text-sm text-gray-800">' + endtime + '</div></div>';
    html += '</div>';
    html += '</div>';

    openModal('订单详情', html);
});

$(function() {
    setTimeout(checkUpdateNotice, 300);
    loadSystemSwitches();
    renderWeeklyChart();
});

function loadSystemSwitches() {
    $.ajax({
        url: 'ajax.php?act=get_system_switches',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.code === 1 && res.data) {
                if (res.data.cloud_enabled !== undefined) {
                    document.getElementById('cloud_enabled').checked = res.data.cloud_enabled === '1';
                    setSwitchChip('cloud_enabled_chip', res.data.cloud_enabled === '1');
                }
                if (res.data.dg_open !== undefined) {
                    document.getElementById('dg_open').checked = res.data.dg_open === '1';
                    setSwitchChip('dg_open_chip', res.data.dg_open === '1');
                }
                if (res.data.qzone_open !== undefined) {
                    document.getElementById('qzone_open').checked = res.data.qzone_open === '1';
                    setSwitchChip('qzone_open_chip', res.data.qzone_open === '1');
                }
            }
        }
    });
}

function saveSystemSwitch(name, value) {
    $.ajax({
        url: 'ajax.php?act=save_system_switch',
        type: 'POST',
        data: { name: name, value: value ? '1' : '0' },
        dataType: 'json',
        success: function(res) {
            if (res.code === 1) {
                showToast('保存成功', 'success');
                updateSwitchChip(name, value);
            } else {
                showToast(res.msg || '保存失败', 'error');
            }
        },
        error: function() {
            showToast('服务器错误', 'error');
        }
    });
}

function setSwitchChip(id, enabled) {
    var el = document.getElementById(id);
    if (!el) return;
    if (enabled) {
        el.textContent = '已启用';
        el.className = 'ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700';
    } else {
        el.textContent = '已关闭';
        el.className = 'ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600';
    }
}

function updateSwitchChip(name, enabled) {
    if (name === 'cloud_enabled') setSwitchChip('cloud_enabled_chip', enabled);
    if (name === 'dg_open') setSwitchChip('dg_open_chip', enabled);
    if (name === 'qzone_open') setSwitchChip('qzone_open_chip', enabled);
}
</script>

<!-- 右侧悬浮反馈按钮 -->
<div class="fixed right-4 bottom-20 flex flex-col items-center z-40">
    <button onclick="openFeedbackModal()" class="w-12 h-12 bg-purple-500 hover:bg-purple-600 text-white rounded-full shadow-lg flex flex-col items-center justify-center transition-transform hover:scale-110" title="意见反馈" aria-label="意见反馈">
        <i class="fas fa-comment-dots text-base"></i>
        <span class="text-[8px] leading-none mt-[1px]">反馈</span>
    </button>
</div>

<!-- 反馈弹窗 -->
<div id="feedbackModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeFeedbackModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 class="text-lg font-semibold text-gray-800"><i class="fas fa-comment-dots text-purple-500 mr-2"></i>意见反馈</h3>
                <button onclick="closeFeedbackModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div class="px-5 py-4 overflow-y-auto overflow-x-hidden">
                <form id="feedbackForm" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">您的QQ号 <span class="text-red-500">*</span></label>
                        <input type="text" name="feedback_qq" id="feedback_qq" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="请输入您的QQ号" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">反馈内容 <span class="text-red-500">*</span></label>
                        <textarea name="feedback_content" id="feedback_content" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="请详细描述您遇到的问题或建议..." required></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Bug触发时间 <span class="text-gray-400">(登录问题请选择时间)</span></label>
                        <input type="datetime-local" name="feedback_time" id="feedback_time" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">上传图片或视频</label>
                        <div class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-purple-500 transition-colors cursor-pointer" onclick="document.getElementById('feedback_files').click()">
                            <input type="file" id="feedback_files" name="feedback_files[]" multiple accept="image/*,video/*" class="hidden" onchange="previewFeedbackFiles(this)">
                            <div id="feedback_upload_area">
                                <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                                <p class="text-sm text-gray-500">点击上传图片或视频</p>
                                <p class="text-xs text-gray-400 mt-1">支持多文件（图片/视频）</p>
                            </div>
                        </div>
                        <div id="feedback_preview" class="mt-3 grid grid-cols-3 gap-2"></div>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 pt-2">
                        <span class="text-xs text-gray-500">提交即表示同意<a href="javascript:void(0)" class="text-purple-500 hover:underline" onclick="showPrivacyPolicy()">《隐私政策》</a></span>
                        <button type="button" onclick="submitFeedback()" class="px-4 py-2 bg-purple-500 hover:bg-purple-600 text-white rounded-lg transition-colors inline-flex items-center justify-center gap-1 leading-tight">
                            <i class="fas fa-paper-plane"></i>
                            <span>提交反馈</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 隐私政策弹窗 -->
<div id="privacyModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closePrivacyModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 class="text-lg font-semibold text-gray-800">隐私政策</h3>
                <button onclick="closePrivacyModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div class="px-5 py-4 overflow-y-auto text-sm text-gray-600 space-y-3">
                <p>我们非常重视您的隐私保护。</p>
                <p>1. 您提交的个人信息（QQ号、反馈内容、附件）仅用于处理和回复您的反馈。</p>
                <p>2. 未经您同意，我们不会向第三方透露您的个人信息。</p>
                <p>3. 您可以随时联系我们删除您的反馈数据。</p>
                <p class="text-gray-500 text-xs mt-4">提交反馈即表示您同意我们的隐私政策</p>
            </div>
            <div class="px-5 py-3 border-t border-gray-100">
                <button onclick="closePrivacyModal()" class="w-full px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors">我知道了</button>
            </div>
        </div>
    </div>
</div>

<script>
var feedbackFiles = [];

function openFeedbackModal() {
    document.getElementById('feedbackModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeFeedbackModal() {
    document.getElementById('feedbackModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function closePrivacyModal() {
    document.getElementById('privacyModal').classList.add('hidden');
}

function showPrivacyPolicy() {
    document.getElementById('privacyModal').classList.remove('hidden');
}

function previewFeedbackFiles(input) {
    var preview = document.getElementById('feedback_preview');
    var files = input.files;
    if (!files.length) return;

    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        feedbackFiles.push(file);

        var reader = new FileReader();
        reader.onload = function(e) {
            var div = document.createElement('div');
            div.className = 'relative';
            if (file.type.startsWith('video/')) {
                div.innerHTML = '<video src="' + e.target.result + '" class="w-full h-20 object-cover rounded"></video><button type="button" onclick="removeFeedbackFile(' + (feedbackFiles.length - 1) + ', this)" class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center">×</button>';
            } else {
                div.innerHTML = '<img src="' + e.target.result + '" class="w-full h-20 object-cover rounded"><button type="button" onclick="removeFeedbackFile(' + (feedbackFiles.length - 1) + ', this)" class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center">×</button>';
            }
            preview.appendChild(div);
        };
        reader.readAsDataURL(file);
    }
    input.value = '';
}

function removeFeedbackFile(index, btn) {
    feedbackFiles.splice(index, 1);
    btn.parentElement.remove();
}

function submitFeedback() {
    var qq = document.getElementById('feedback_qq').value.trim();
    var content = document.getElementById('feedback_content').value.trim();
    var bugTimeInput = document.getElementById('feedback_time').value;
    var bugTime = '';

    // 将datetime-local格式转换为后端需要的格式
    if (bugTimeInput) {
        var date = new Date(bugTimeInput);
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(date.getHours()).padStart(2, '0');
        var minutes = String(date.getMinutes()).padStart(2, '0');
        var seconds = String(date.getSeconds()).padStart(2, '0');
        bugTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }

    if (!qq) {
        showToast('请输入您的QQ号', 'error');
        return;
    }
    if (!content) {
        showToast('请输入反馈内容', 'error');
        return;
    }

    // 检查是否为登录相关问题，如果是则必须填写时间
    var loginKeywords = ['登录', '登陆', '登录不上', '登陆不上', '登录失败', '登陆失败', '登入', 'cookie', 'skey', 'token'];
    var isLoginIssue = loginKeywords.some(keyword => content.includes(keyword));
    if (isLoginIssue && !bugTime) {
        showToast('登录问题请填写Bug触发时间', 'error');
        return;
    }

    var formData = new FormData();
    formData.append('qq', qq);
    formData.append('content', content);
    var feedbackDomain = (function() {
        try {
            var u = new URL(window.location.href);
            return u.host || window.location.host;
        } catch (e) {
            return window.location.host;
        }
    })();
    formData.append('domain', feedbackDomain);
    if (bugTime) {
        formData.append('bug_time', bugTime);
    }
    for (var i = 0; i < feedbackFiles.length; i++) {
        formData.append('files[]', feedbackFiles[i]);
    }

    var btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>提交中...';

    $.ajax({
        url: 'ajax_fankui.php?act=submit',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(res) {
            if (res.code === 1) {
                showToast('反馈提交成功！', 'success');
                closeFeedbackModal();
                document.getElementById('feedbackForm').reset();
                feedbackFiles = [];
                document.getElementById('feedback_preview').innerHTML = '';
            } else {
                showToast(res.msg || '提交失败，请重试', 'error');
            }
        },
        error: function() {
            showToast('网络错误，请检查网络后重试', 'error');
        },
        complete: function() {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-paper-plane mr-1"></i>提交反馈';
        }
    });
}
</script>
<?php include 'foot.php'; ?>
