<?php
/**
 * 秒赞系统设置
 */
$title = '秒赞系统设置';
include __DIR__ . '/head.php';

// 检查是否安装
$tables = $DB->getColumn("SHOW TABLES LIKE '" . DBQZ . "qzone_qq'", 0);
if (!$tables) {
    include __DIR__ . '/foot.php';
    exit;
}
?>

<div class="p-4 md:p-6 overflow-x-hidden min-w-0">
    <!-- 标签页导航 -->
    <div class="bg-white rounded-lg shadow overflow-hidden min-w-0">
        <div class="border-b border-gray-200 overflow-x-auto">
            <nav class="flex -mb-px min-w-0">
                <button onclick="switchTab('config')" id="tab_config" class="tab-btn active px-3 py-3 sm:px-6 sm:py-4 text-sm sm:text-base text-blue-600 border-b-2 border-blue-600 font-medium whitespace-nowrap flex-shrink-0">
                    <i class="fas fa-cog mr-1 sm:mr-2"></i>全局配置
                </button>
                <button onclick="switchTab('node')" id="tab_node" class="tab-btn px-3 py-3 sm:px-6 sm:py-4 text-sm sm:text-base text-gray-500 hover:text-gray-700 font-medium whitespace-nowrap flex-shrink-0">
                    <i class="fas fa-server mr-1 sm:mr-2"></i>节点设置
                </button>
                <button onclick="switchTab('log')" id="tab_log" class="tab-btn px-3 py-3 sm:px-6 sm:py-4 text-sm sm:text-base text-gray-500 hover:text-gray-700 font-medium whitespace-nowrap flex-shrink-0">
                    <i class="fas fa-history mr-1 sm:mr-2"></i>操作日志
                </button>
            </nav>
        </div>

        <!-- 全局配置 -->
        <div id="panel_config" class="tab-panel p-4 sm:p-6 min-w-0 overflow-hidden">
            <form id="config_form" class="space-y-4">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
                    <!-- 功能收费开关 -->
                    <div>
                        <h3 class="font-medium text-gray-800 mb-3"><i class="fas fa-coins text-yellow-500 mr-2"></i>功能收费设置</h3>
                        <p class="text-sm text-gray-500 mb-4">开启后，只有VIP用户才能使用该功能；关闭则所有用户都可免费使用</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div class="flex items-center justify-between p-3 bg-pink-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">云端取CK收费</p>
                                <p class="text-xs text-gray-500">控制“云端取CK”是否作为收费功能</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_cloud_cookie" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-pink-600"></div>
                            </label>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-indigo-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">秒赞自定义频率</p>
                                <p class="text-xs text-gray-500">VIP用户自定义秒赞执行频率</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_ssmz_cycle_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-indigo-600"></div>
                            </label>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-teal-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">秒评自定义频率</p>
                                <p class="text-xs text-gray-500">VIP用户自定义秒评执行频率</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_ssmp_cycle_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-teal-600"></div>
                            </label>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">说说秒赞</p>
                                <p class="text-xs text-gray-500">自动点赞好友说说</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_ssmz_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">说说秒评</p>
                                <p class="text-xs text-gray-500">自动评论好友说说</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_ssmp_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-green-600"></div>
                            </label>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-sky-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">每小时最大点赞数</p>
                                <p class="text-xs text-gray-500">限制非VIP用户点赞次数</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_ssmz_hourly_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-sky-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-teal-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">每小时最大评论数</p>
                                <p class="text-xs text-gray-500">限制非VIP用户评论次数</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_ssmp_hourly_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-teal-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">自动发说说</p>
                                <p class="text-xs text-gray-500">定时自动发布说说</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_zdfss_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-purple-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-violet-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">自动删除说说</p>
                                <p class="text-xs text-gray-500">发说说前删除上一条</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_zdfss_delete_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-violet-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-orange-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">转发说说</p>
                                <p class="text-xs text-gray-500">自动转发说说</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_zfss_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-orange-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-cyan-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">空间签到</p>
                                <p class="text-xs text-gray-500">每日自动签到</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_sign_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-cyan-600"></div>
                            </label>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-red-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">清空说说</p>
                                <p class="text-xs text-gray-500">一键清空所有说说</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_clear_ss_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-red-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between p-3 bg-pink-50 rounded-lg">
                            <div>
                                <p class="font-medium text-sm">清空留言</p>
                                <p class="text-xs text-gray-500">一键清空所有留言</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="qzone_clear_ly_vip" value="1" class="sr-only peer">
                                <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-pink-600"></div>
                            </label>
                        </div>
                        </div>
                        <div class="mt-4">
                            <h3 class="font-medium text-gray-800 mb-3"><i class="fas fa-sliders-h text-blue-500 mr-2"></i>功能开关</h3>
                            <div class="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                                <div>
                                    <p class="font-medium text-sm">从云端版更新状态</p>
                                    <p class="text-xs text-gray-500">开启后支持从云端版自动更新CK</p>
                                </div>
                                <label class="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" name="qzone_cloud_update_status" value="1" class="sr-only peer">
                                    <div class="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- 免费用户设置 -->
                    <div class="xl:border-l xl:pl-4 border-gray-200">
                        <h3 class="font-medium text-gray-800 mb-3"><i class="fas fa-edit text-gray-500 mr-2"></i>免费用户设置</h3>
                        <div class="bg-gray-50 rounded-lg p-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">秒评尾缀（免费用户）</label>
                            <input type="text" name="qzone_tail_pl" value="" class="w-full border rounded-lg px-3 py-2 bg-white" placeholder="如：来自XX平台">
                            <p class="text-xs text-gray-500 mt-1">免费用户评论时自动添加的尾缀</p>
                        </div>
                        <div class="mt-3 bg-gray-50 rounded-lg p-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">发说说尾缀（免费用户）</label>
                            <input type="text" name="qzone_tail_zdfss" value="" class="w-full border rounded-lg px-3 py-2 bg-white" placeholder="如：来自XX平台">
                            <p class="text-xs text-gray-500 mt-1">免费用户自动发说说时添加的尾缀</p>
                        </div>
                        <div class="mt-3 bg-gray-50 rounded-lg p-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">免费用户秒赞频率（秒）</label>
                            <input type="number" min="20" max="86400" name="qzone_free_ssmz_cycle" value="60" class="w-full border rounded-lg px-3 py-2 bg-white">
                            <p class="text-xs text-gray-500 mt-1">当“秒赞自定义频率”开启会员限制时，免费用户将固定使用该频率</p>
                        </div>
                        <div class="mt-3 bg-gray-50 rounded-lg p-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">免费用户秒评频率（秒）</label>
                            <input type="number" min="20" max="86400" name="qzone_free_ssmp_cycle" value="60" class="w-full border rounded-lg px-3 py-2 bg-white">
                            <p class="text-xs text-gray-500 mt-1">当“秒评自定义频率”开启会员限制时，免费用户将固定使用该频率</p>
                        </div>
                        <div class="mt-3 bg-gray-50 rounded-lg p-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">免费用户每小时最大点赞数</label>
                            <input type="number" min="0" max="9999" name="qzone_free_hourly_ssmz" value="0" class="w-full border rounded-lg px-3 py-2 bg-white">
                            <p class="text-xs text-gray-500 mt-1">0为不限制，配合“每小时最大点赞数”开关生效</p>
                        </div>
                        <div class="mt-3 bg-gray-50 rounded-lg p-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">免费用户每小时最大评论数</label>
                            <input type="number" min="0" max="9999" name="qzone_free_hourly_ssmp" value="0" class="w-full border rounded-lg px-3 py-2 bg-white">
                            <p class="text-xs text-gray-500 mt-1">0为不限制，配合“每小时最大评论数”开关生效</p>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- 节点设置 -->
        <div id="panel_node" class="tab-panel p-4 sm:p-6 hidden min-w-0 overflow-hidden">
            <div class="mb-6 p-4 bg-amber-50 border border-amber-200 rounded-lg">
                <h3 class="font-medium text-amber-800 mb-2"><i class="fas fa-download mr-2"></i>登录节点文件部署</h3>
                <p class="text-sm text-amber-700 mb-3">扫码登录单台服务器可能因限频导致无法登录。可下载「登录节点完整包」部署到其他服务器，作为备用登录节点，用户端扫码时可选择节点以分散请求。节点无需配置数据库，解压即用，主站负责写库。</p>
                <p class="text-sm text-amber-700 mb-3">部署步骤：下载下方完整压缩包 → 解压到节点服务器任意目录（仅需 PHP 环境）→ 将节点访问地址填入下方「节点 URL」并保存。</p>
                <a href="ajax_qzone.php?act=download_node_file" class="inline-flex items-center px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white rounded-lg text-sm font-medium">
                    <i class="fas fa-file-archive mr-2"></i>下载登录节点完整包
                </a>
            </div>
            <div class="mb-6 min-w-0">
                <h3 class="font-medium text-gray-800 mb-3">主站节点</h3>
                <div class="flex flex-col sm:flex-row gap-3 items-start sm:items-center">
                    <div class="w-full sm:w-32">
                        <label class="block text-sm font-medium text-gray-700 mb-1">排序</label>
                        <input type="number" id="node_main_sort" class="border rounded-lg px-3 py-2 w-full" value="0" placeholder="0" onchange="saveMainNode()">
                        <p class="text-xs text-gray-500 mt-1">越小越靠前</p>
                    </div>
                    <label class="inline-flex items-center gap-2 text-sm text-gray-700 flex-shrink-0">
                        <input type="checkbox" id="node_main_enabled" class="rounded border-gray-300" checked onchange="saveMainNode()">
                        启用主站
                    </label>
                    <div class="min-w-0 flex-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">主站节点名称</label>
                        <input type="text" id="node_main_name" class="border rounded-lg px-3 py-2 w-full max-w-xs" placeholder="主站" value="" onchange="saveMainNode()">
                        <p class="text-xs text-gray-500 mt-1">用户端扫码下拉中的主站显示名称，留空则显示「主站」</p>
                    </div>
                </div>
            </div>
            <div class="min-w-0">
                <h3 class="font-medium text-gray-800 mb-3">节点 URL 列表</h3>
                <p class="text-sm text-gray-500 mb-4">添加后，用户扫码时可选择对应节点进行登录。主站无需添加，默认使用当前站点。</p>
                <div class="mb-4 flex gap-2">
                    <button type="button" onclick="showAddNodeModal()" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg text-sm font-medium shadow-sm transition">
                        <i class="fas fa-plus mr-1"></i>添加节点
                    </button>
                    <button type="button" onclick="showImportSocks5Modal()" class="px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg text-sm font-medium shadow-sm transition">
                        <i class="fas fa-file-import mr-1"></i>批量导入SOCKS5
                    </button>
                </div>
                <!-- 节点卡片列表 -->
                <div id="node_list_container" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="col-span-1 md:col-span-2 text-center py-6 text-gray-400">加载中...</div>
                </div>
            </div>
        </div>

        <!-- 操作日志 -->
        <div id="panel_log" class="tab-panel p-4 sm:p-6 hidden min-w-0 overflow-hidden">
            <div class="flex flex-wrap gap-2 mb-4">
                <input type="text" id="log_qq" placeholder="QQ号" class="border rounded-lg px-3 py-2 w-full sm:w-32 min-w-0">
                <select id="log_type" class="border rounded-lg px-3 py-2 min-w-0 flex-1 sm:flex-initial">
                    <option value="">全部类型</option>
                    <option value="ssmz">说说秒赞</option>
                    <option value="ssmp">说说秒评</option>
                    <option value="zdfss">自动发说说</option>
                    <option value="zfss">转发说说</option>
                    <option value="sign">空间签到</option>
                    <option value="clear_ss">清空说说</option>
                    <option value="clear_ly">清空留言</option>
                </select>
                <button onclick="loadLogList(1)" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600">
                    <i class="fas fa-search"></i>
                </button>
                <button onclick="clearLog()" class="bg-red-500 text-white px-3 py-2 rounded-lg hover:bg-red-600 text-sm whitespace-nowrap">
                    <i class="fas fa-trash-alt mr-1"></i>清空日志
                </button>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">ID</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">QQ号</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">类型</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">内容</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">时间</th>
                        </tr>
                    </thead>
                    <tbody id="log_list" class="divide-y divide-gray-200">
                        <tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div id="log_pagination" class="mt-4 flex justify-center"></div>
        </div>

    </div>
</div>

<script>
var logPage = 1;

function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
        btn.classList.add('text-gray-500');
    });
    document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.add('hidden'));

    document.getElementById('tab_' + tab).classList.add('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
    document.getElementById('tab_' + tab).classList.remove('text-gray-500');
    document.getElementById('panel_' + tab).classList.remove('hidden');

    if (tab === 'log') loadLogList(1);
}

var nodeList = [];

// 页面加载时获取配置和节点列表
function loadConfigAndNodes() {
    $.ajax({
        url: 'ajax_qzone.php?act=get_config',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.code === 1 && res.config) {
                var conf = res.config;
                // 设置checkbox
                var checkboxes = ['qzone_ssmz_vip', 'qzone_ssmp_vip', 'qzone_ssmz_hourly_vip', 'qzone_ssmp_hourly_vip', 'qzone_zdfss_vip', 'qzone_zdfss_delete_vip', 'qzone_zfss_vip', 'qzone_sign_vip', 'qzone_ssmz_cycle_vip', 'qzone_ssmp_cycle_vip', 'qzone_clear_ss_vip', 'qzone_clear_ly_vip', 'qzone_cloud_cookie', 'qzone_cloud_update_status'];
                checkboxes.forEach(function(name) {
                    var el = document.querySelector('input[name="' + name + '"]');
                    if (el && (conf[name] === '1' || conf[name] === 1)) {
                        el.checked = true;
                    }
                });
                // 设置文本输入框
                var textFields = ['qzone_tail_pl', 'qzone_tail_zdfss'];
                textFields.forEach(function(name) {
                    var el = document.querySelector('input[name="' + name + '"]');
                    if (el && conf[name]) {
                        el.value = conf[name];
                    }
                });
                // 设置数字输入框
                var numFields = ['qzone_free_ssmz_cycle', 'qzone_free_ssmp_cycle', 'qzone_free_hourly_ssmz', 'qzone_free_hourly_ssmp'];
                numFields.forEach(function(name) {
                    var el = document.querySelector('input[name="' + name + '"]');
                    if (el && conf[name] !== undefined) {
                        el.value = conf[name];
                    }
                });
            }

            // 设置节点列表（合并在同一个接口返回）
            if (res.code === 1) {
                nodeList = res.nodes || [];
                // 设置主站节点
                document.getElementById('node_main_sort').value = res.main_sort || 0;
                document.getElementById('node_main_enabled').checked = res.main_enabled == 1;
                document.getElementById('node_main_name').value = res.main_name || '主站';
                renderNodeList();
            }
        }
    });
}

// 页面加载完成后执行
$(document).ready(function() {
    loadConfigAndNodes();
});

// 显示添加节点弹窗
function showAddNodeModal() {
    document.getElementById('node_edit_index').value = '-1';
    document.getElementById('node_modal_title').innerText = '添加节点';
    document.getElementById('node_modal_name').value = '';
    document.getElementById('node_modal_type').value = 'url';
    document.getElementById('node_modal_url').value = '';
    document.getElementById('node_modal_socks5_host').value = '';
    document.getElementById('node_modal_socks5_port').value = '';
    document.getElementById('node_modal_socks5_user').value = '';
    document.getElementById('node_modal_socks5_pass').value = '';
    document.getElementById('node_modal_sort').value = '0';
    document.getElementById('node_modal_enabled').checked = true;
    toggleNodeTypeFields();
    var m = document.getElementById('node_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}

// 切换节点类型显示
function toggleNodeTypeFields() {
    var type = document.getElementById('node_modal_type').value;
    var urlFields = document.getElementById('node_url_fields');
    var socks5Fields = document.getElementById('node_socks5_fields');
    if (type === 'socks5') {
        urlFields.classList.add('hidden');
        socks5Fields.classList.remove('hidden');
    } else {
        urlFields.classList.remove('hidden');
        socks5Fields.classList.add('hidden');
    }
}

// 显示编辑节点弹窗
function editNode(i) {
    if (i < 0 || i >= nodeList.length) return;
    var node = nodeList[i];
    document.getElementById('node_edit_index').value = i;
    document.getElementById('node_modal_title').innerText = '编辑节点';
    document.getElementById('node_modal_type').value = node.type || 'url';
    document.getElementById('node_modal_name').value = node.name || '';
    document.getElementById('node_modal_url').value = node.url || '';
    document.getElementById('node_modal_socks5_host').value = node.socks5_host || '';
    document.getElementById('node_modal_socks5_port').value = node.socks5_port || '';
    document.getElementById('node_modal_socks5_user').value = node.socks5_user || '';
    document.getElementById('node_modal_socks5_pass').value = node.socks5_pass || '';
    document.getElementById('node_modal_sort').value = (node.sort !== undefined ? node.sort : 0);
    document.getElementById('node_modal_enabled').checked = String(nodeList[i].enabled ?? 1) === '1' || nodeList[i].enabled === 1 || nodeList[i].enabled === true;
    toggleNodeTypeFields();
    var m = document.getElementById('node_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}

// 隐藏节点弹窗
function hideNodeModal() {
    var m = document.getElementById('node_modal');
    m.classList.add('hidden');
    m.classList.remove('flex');
}

// 显示批量导入SOCKS5弹窗
function showImportSocks5Modal() {
    document.getElementById('import_socks5_text').value = '';
    document.getElementById('import_socks5_enabled').checked = true;
    var m = document.getElementById('import_socks5_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}

// 隐藏批量导入SOCKS5弹窗
function hideImportSocks5Modal() {
    var m = document.getElementById('import_socks5_modal');
    m.classList.add('hidden');
    m.classList.remove('flex');
}

// 批量导入SOCKS5节点
function importSocks5Nodes() {
    var text = document.getElementById('import_socks5_text').value;
    var enabled = document.getElementById('import_socks5_enabled').checked ? 1 : 0;

    if (!text || !text.trim()) {
        showToast('请输入SOCKS5节点信息', 'error');
        return;
    }

    var lines = text.trim().split('\n');
    var count = 0;
    var maxSort = 0;

    // 获取当前最大排序值
    nodeList.forEach(function(n) {
        var s = parseInt(n.sort, 10) || 0;
        if (s > maxSort) maxSort = s;
    });

    lines.forEach(function(line) {
        line = line.trim();
        if (!line) return;

        // 格式: 节点名称:IP:端口[:用户名:密码[:排序]]
        var parts = line.split(':');
        if (parts.length < 3) return;

        var len = parts.length;
        var name = parts[0].trim();
        var host = parts[1].trim();
        var port = parseInt(parts[2], 10);

        var user = '', pass = '', sortVal = 0;

        if (len === 3) {
            // 格式: name:host:port
        } else if (len === 4) {
            // 格式: name:host:port:user
            user = parts[3].trim();
        } else if (len === 5) {
            // 格式: name:host:port:user:pass
            user = parts[3].trim();
            pass = parts[4].trim();
        } else if (len >= 6) {
            // 格式: name:host:port:user:pass:sort
            user = parts[3].trim();
            pass = parts[4].trim();
            sortVal = parseInt(parts[5], 10) || 0;
        }

        if (!name || !host || !port || isNaN(port)) return;

        // 如果没有指定排序，则使用递增排序
        if (sortVal === 0) {
            sortVal = ++maxSort;
        } else if (sortVal > maxSort) {
            maxSort = sortVal;
        }

        nodeList.push({
            name: name,
            type: 'socks5',
            socks5_host: host,
            socks5_port: port,
            socks5_user: user,
            socks5_pass: pass,
            sort: sortVal,
            enabled: enabled
        });
        count++;
    });

    if (count > 0) {
        hideImportSocks5Modal();
        renderNodeList();
        autoSaveNodes();
        showToast('成功导入 ' + count + ' 个SOCKS5节点', 'success');
    } else {
        showToast('未找到有效的SOCKS5节点信息', 'error');
    }
}

// 从弹窗保存节点
function saveNodeFromModal(btn) {
    var idx = parseInt(document.getElementById('node_edit_index').value, 10);
    var name = (document.getElementById('node_modal_name').value || '').trim();
    var type = document.getElementById('node_modal_type').value;
    var url = (document.getElementById('node_modal_url').value || '').trim();
    var socks5_host = (document.getElementById('node_modal_socks5_host').value || '').trim();
    var socks5_port = (document.getElementById('node_modal_socks5_port').value || '').trim();
    var socks5_user = (document.getElementById('node_modal_socks5_user').value || '').trim();
    var socks5_pass = (document.getElementById('node_modal_socks5_pass').value || '').trim();
    var sortVal = parseInt((document.getElementById('node_modal_sort').value || '').trim(), 10);
    var enabled = document.getElementById('node_modal_enabled').checked ? 1 : 0;

    if (!name) { showToast('请填写节点名称', 'error'); return; }
    if (type === 'url' && !url) { showToast('请填写节点URL', 'error'); return; }
    if (type === 'socks5' && (!socks5_host || !socks5_port)) { showToast('请填写SOCKS5代理地址和端口', 'error'); return; }
    if (isNaN(sortVal)) sortVal = 0;

    var node = { name: name, type: type, sort: sortVal, enabled: enabled };
    if (type === 'url') {
        node.url = url;
    } else {
        node.socks5_host = socks5_host;
        node.socks5_port = socks5_port;
        node.socks5_user = socks5_user;
        node.socks5_pass = socks5_pass;
    }

    if (idx >= 0 && idx < nodeList.length) {
        nodeList[idx] = node;
    } else {
        nodeList.push(node);
    }
    hideNodeModal();
    renderNodeList();
    autoSaveNodes();
    showToast(idx >= 0 ? '已更新' : '添加成功', 'success');
}

function removeNode(i) {
    showConfirmModal('删除节点', '确定要删除该节点吗？', function(done) {
        nodeList.splice(i, 1);
        renderNodeList();
        autoSaveNodes();
        done();
    });
}
function renderNodeList() {
    var container = document.getElementById('node_list_container');
    var html = '';
    if (nodeList.length === 0) {
        html = '<div class="col-span-1 md:col-span-2 text-center py-6 text-gray-400">暂无节点，请添加</div>';
    } else {
        nodeList.forEach(function(n, i) {
            var sortText = (n.sort !== undefined && n.sort !== null) ? String(n.sort) : '0';
            var enabledText = (String(n.enabled ?? 1) === '1' || n.enabled === 1 || n.enabled === true) ? '启用' : '禁用';
            var enabledClass = (String(n.enabled ?? 1) === '1' || n.enabled === 1 || n.enabled === true) ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700';
            var typeText = n.type === 'socks5' ? '<span class="px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-800">SOCKS5</span>' : '<span class="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800">URL</span>';
            var nodeInfo = n.type === 'socks5' ? (n.socks5_host || '') + ':' + (n.socks5_port || '') : (n.url || '');
            html += '<div class="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">' +
                '<div class="flex items-start justify-between mb-3">' +
                    '<div class="flex items-center gap-2">' +
                        '<span class="text-xs font-medium text-gray-500">排序: ' + sortText.replace(/</g,'&lt;') + '</span>' +
                        '<span class="px-2 py-1 text-xs rounded-full ' + enabledClass + '">' + enabledText + '</span>' +
                        typeText +
                    '</div>' +
                    '<div class="flex items-center gap-2">' +
                        '<button type="button" onclick="editNode('+i+')" class="px-2.5 py-1.5 text-xs bg-amber-500 hover:bg-amber-600 text-white font-medium rounded-lg transition shadow-sm whitespace-nowrap">编辑</button>' +
                        '<button type="button" onclick="removeNode('+i+')" class="px-2.5 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition shadow-sm whitespace-nowrap">删除</button>' +
                    '</div>' +
                '</div>' +
                '<div class="text-sm font-medium text-gray-800 mb-1">' + (n.name || '').replace(/</g,'&lt;') + '</div>' +
                '<div class="text-xs text-gray-500 break-all">' + nodeInfo.replace(/</g,'&lt;') + '</div>' +
                '</div>';
        });
    }
    container.innerHTML = html;
}

// ================== Tailwind 确认弹窗 ==================
var confirmCallback = null;
function showConfirmModal(title, message, onConfirm) {
    confirmCallback = typeof onConfirm === 'function' ? onConfirm : null;
    document.getElementById('confirm_title').innerText = title || '请确认';
    document.getElementById('confirm_message').innerText = message || '';
    var btn = document.getElementById('btn_confirm_ok');
    btn.disabled = false;
    btn.innerHTML = '确定';
    var m = document.getElementById('confirm_modal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}
function hideConfirmModal() {
    var m = document.getElementById('confirm_modal');
    m.classList.add('hidden');
    m.classList.remove('flex');
    confirmCallback = null;
}
function confirmOk(btn) {
    if (!confirmCallback) { hideConfirmModal(); return; }
    if (btn.disabled) return;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>处理中...';
    confirmCallback(function done() {
        hideConfirmModal();
    });
}
// 自动保存节点列表（添加/编辑/删除后调用）
function autoSaveNodes() {
    var mainName = (document.getElementById('node_main_name') && document.getElementById('node_main_name').value) ? document.getElementById('node_main_name').value.trim() : '';
    var mainEnabled = (document.getElementById('node_main_enabled') && document.getElementById('node_main_enabled').checked) ? 1 : 0;
    var mainSort = parseInt((document.getElementById('node_main_sort') && document.getElementById('node_main_sort').value) ? document.getElementById('node_main_sort').value.trim() : '0', 10);
    if (isNaN(mainSort)) mainSort = 0;
    $.post('ajax_qzone.php?act=save_nodes', { nodes: JSON.stringify(nodeList), main_name: mainName, main_enabled: mainEnabled, main_sort: mainSort }, function(res) {
        if (res.code === 1) { showToast('保存成功', 'success'); } else { showToast(res.msg || '保存失败', 'error'); }
    }, 'json');
}

// 保存主站配置
function saveMainNode() {
    autoSaveNodes();
}

function loadLogList(page) {
    logPage = page || 1;
    var qq = document.getElementById('log_qq').value;
    var type = document.getElementById('log_type').value;
    $.post('ajax_qzone.php?act=get_log_list', {page: logPage, qq: qq, type: type}, function(res) {
        if (res.code === 1) {
            var html = '';
            if (res.data.length === 0) {
                html = '<tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">暂无日志</td></tr>';
            } else {
                var typeMap = {ssmz: '说说秒赞', ssmp: '说说秒评', zdfss: '自动发说说', zfss: '转发说说', sign: '空间签到', clear_ss: '清空说说', clear_ly: '清空留言'};
                res.data.forEach(function(item) {
                    html += '<tr class="hover:bg-gray-50">' +
                        '<td class="px-4 py-3 whitespace-nowrap">' + item.id + '</td>' +
                        '<td class="px-4 py-3 whitespace-nowrap">' + item.qq + '</td>' +
                        '<td class="px-4 py-3 whitespace-nowrap">' + (typeMap[item.type] || item.type) + '</td>' +
                        '<td class="px-4 py-3 text-gray-600">' + escHtml(item.content) + '</td>' +
                        '<td class="px-4 py-3 whitespace-nowrap text-gray-500">' + item.create_time + '</td></tr>';
                });
            }
            document.getElementById('log_list').innerHTML = html;
            renderPagination('log_pagination', logPage, res.pages, 'loadLogList');
        }
    }, 'json');
}

function clearLog() {
    showConfirmModal('清空日志', '确定要清空所有操作日志吗？此操作不可恢复！', function(done) {
        $.post('ajax_qzone.php?act=clear_log', {}, function(res) {
            done();
            if (res.code === 1) {
                showToast('日志已清空', 'success');
                loadLogList(1);
            } else {
                showToast(res.msg || '清空失败', 'error');
            }
        }, 'json').fail(function() {
            done();
            showToast('网络错误，请重试', 'error');
        });
    });
}

function renderPagination(container, current, total, callback) {
    var html = '';
    if (total > 1) {
        html += '<div class="flex gap-1">';
        if (current > 1) {
            html += '<button onclick="' + callback + '(' + (current-1) + ')" class="px-3 py-1 border rounded hover:bg-gray-50">&lt;</button>';
        }
        for (var i = 1; i <= total; i++) {
            if (i === current) {
                html += '<button class="px-3 py-1 bg-blue-500 text-white rounded">' + i + '</button>';
            } else if (i <= 3 || i > total - 2 || (i >= current - 1 && i <= current + 1)) {
                html += '<button onclick="' + callback + '(' + i + ')" class="px-3 py-1 border rounded hover:bg-gray-50">' + i + '</button>';
            } else if (i === current - 2 || i === current + 2) {
                html += '<span class="px-2">...</span>';
            }
        }
        if (current < total) {
            html += '<button onclick="' + callback + '(' + (current+1) + ')" class="px-3 py-1 border rounded hover:bg-gray-50">&gt;</button>';
        }
        html += '</div>';
    }
    document.getElementById(container).innerHTML = html;
}

// 配置表单 - 输入框变化自动保存（防抖）
var configSaveTimer = null;
document.getElementById('config_form').addEventListener('change', function(e) {
    if (configSaveTimer) clearTimeout(configSaveTimer);
    configSaveTimer = setTimeout(function() {
        var formData = new FormData(document.getElementById('config_form'));
        $.ajax({
            url: 'ajax_qzone.php?act=save_config',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.code === 1) {
                    showToast('保存成功', 'success');
                } else {
                    showToast(res.msg, 'error');
                }
            }
        });
    }, 800);
});

</script>

<!-- 删除确认弹窗（Tailwind） -->
<div id="confirm_modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-sm mx-4 shadow-2xl overflow-hidden">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-gray-800" id="confirm_title">请确认</h3>
            <button type="button" onclick="hideConfirmModal()" class="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>
        <div class="p-4 text-sm text-gray-700" id="confirm_message"></div>
        <div class="p-4 border-t flex gap-2 justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" onclick="hideConfirmModal()">取消</button>
            <button type="button" id="btn_confirm_ok" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium" onclick="confirmOk(this)">确定</button>
        </div>
    </div>
</div>

<!-- 添加/编辑节点弹窗（Tailwind） -->
<div id="node_modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-md mx-4 shadow-2xl overflow-hidden">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-gray-800" id="node_modal_title">添加节点</h3>
            <button type="button" onclick="hideNodeModal()" class="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>
        <div class="p-4 space-y-3">
            <input type="hidden" id="node_edit_index" value="-1">
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">节点类型</label>
                <select id="node_modal_type" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" onchange="toggleNodeTypeFields()">
                    <option value="url">URL节点（服务器部署）</option>
                    <option value="socks5">SOCKS5代理（主站直连）</option>
                </select>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">节点名称</label>
                <input type="text" id="node_modal_name" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="请输入节点名称">
            </div>
            <!-- URL节点配置 -->
            <div id="node_url_fields">
                <div>
                    <label class="block text-xs font-medium text-gray-700 mb-1">节点URL</label>
                    <input type="text" id="node_modal_url" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="https://节点域名或IP/路径/qzone_node.php">
                </div>
            </div>
            <!-- SOCKS5代理配置 -->
            <div id="node_socks5_fields" class="hidden">
                <div class="grid grid-cols-2 gap-2">
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">代理地址</label>
                        <input type="text" id="node_modal_socks5_host" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="IP或域名">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">代理端口</label>
                        <input type="number" id="node_modal_socks5_port" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="端口">
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-2 mt-2">
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">用户名（可选）</label>
                        <input type="text" id="node_modal_socks5_user" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="可选">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">密码（可选）</label>
                        <input type="text" id="node_modal_socks5_pass" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="可选">
                    </div>
                </div>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">排序（越小越靠前）</label>
                <input type="number" id="node_modal_sort" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="0" value="0">
            </div>
            <div>
                <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                    <input type="checkbox" id="node_modal_enabled" class="rounded border-gray-300" checked>
                    启用节点
                </label>
            </div>
        </div>
        <div class="p-4 border-t flex gap-2 justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" onclick="hideNodeModal()">取消</button>
            <button type="button" id="btn_save_node" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium" onclick="saveNodeFromModal(this)">保存</button>
        </div>
    </div>
</div>

<!-- 批量导入SOCKS5弹窗 -->
<div id="import_socks5_modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-lg mx-4 shadow-2xl overflow-hidden">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-gray-800">批量导入SOCKS5</h3>
            <button type="button" onclick="hideImportSocks5Modal()" class="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
        </div>
        <div class="p-4 space-y-3">
            <p class="text-sm text-gray-600">每行一个节点，格式：<code class="bg-gray-100 px-1 rounded">名称:IP:端口</code> 或 <code class="bg-gray-100 px-1 rounded">名称:IP:端口:用户名:密码</code> 或 <code class="bg-gray-100 px-1 rounded">名称:IP:端口:用户名:密码:排序</code></p>
            <textarea id="import_socks5_text" rows="10" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm font-mono" placeholder="示例：
北京:59.110.19.48:9111:p778688:p778688
香港:192.168.1.1:1080
日本:proxy.example.com:1080:user:pass:10"></textarea>
            <div class="text-sm text-gray-500">
                <label class="inline-flex items-center gap-2">
                    <input type="checkbox" id="import_socks5_enabled" class="rounded border-gray-300" checked>
                    导入后启用
                </label>
            </div>
        </div>
        <div class="p-4 border-t flex gap-2 justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" onclick="hideImportSocks5Modal()">取消</button>
            <button type="button" id="btn_import_socks5" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium" onclick="importSocks5Nodes()">导入</button>
        </div>
    </div>
</div>

<?php include __DIR__ . '/foot.php'; ?>
