<?php
/**
 * 用户中心 - QQ空间秒赞配置页面
 */
$title = '功能配置';
include __DIR__ . '/head.php';

if (($conf['qzone_open'] ?? ($conf['qzone_enabled'] ?? '0')) != '1') {
    echo '<div class="p-4 text-center text-gray-500">功能未开启</div>';
    include __DIR__ . '/foot.php';
    exit;
}

$user_id = intval($userrow['zid'] ?? 0);
$qid = intval($_GET['qid'] ?? 0);

if (!$qid) {
    echo '<div class="p-4 text-center text-gray-500">参数错误</div>';
    include __DIR__ . '/foot.php';
    exit;
}

$qq = $DB->getRow("SELECT * FROM " . DBQZ . "qzone_qq WHERE id='{$qid}'");
if (!$qq) {
    echo '<div class="p-4 text-center text-gray-500">QQ不存在</div>';
    include __DIR__ . '/foot.php';
    exit;
}

if ($qq['user_id'] == 0) {
    $DB->exec("UPDATE " . DBQZ . "qzone_qq SET user_id='{$user_id}' WHERE id='{$qid}'");
    $qq['user_id'] = $user_id;
}

if ($qq['user_id'] != $user_id) {
    echo '<div class="p-4 text-center text-gray-500">无权访问</div>';
    include __DIR__ . '/foot.php';
    exit;
}
$isVip = $qq['vip_time'] && strtotime($qq['vip_time']) > time();

$qzoneConfigCols = getConfigColumns();
if (empty($qzoneConfigCols['cloud_auto_update_ck'])) {
    $DB->exec("ALTER TABLE " . DBQZ . "qzone_config ADD COLUMN `cloud_auto_update_ck` tinyint(1) NOT NULL DEFAULT 0 COMMENT '云端自动更新CK开关' AFTER `invalid_remind_switch`");
}
$requiredSwitchCols = [
    'zdfss_switch' => "`zdfss_switch` tinyint(1) NOT NULL DEFAULT 0 COMMENT '自动发说说开关'",
    'zdfss_delete_prev' => "`zdfss_delete_prev` tinyint(1) NOT NULL DEFAULT 0 COMMENT '发说说前删除上一条'",
    'clear_ss_switch' => "`clear_ss_switch` tinyint(1) NOT NULL DEFAULT 0 COMMENT '自动清空说说开关'",
    'clear_ly_switch' => "`clear_ly_switch` tinyint(1) NOT NULL DEFAULT 0 COMMENT '自动清空留言开关'"
];
foreach ($requiredSwitchCols as $col => $sqlDef) {
    if (empty($qzoneConfigCols[$col])) {
        $DB->exec("ALTER TABLE " . DBQZ . "qzone_config ADD COLUMN {$sqlDef}");
    }
}

$cloudQueryQQ = daddslashes($qq['qq']);
$cloudEnabled = (($conf['cloud_enabled'] ?? '1') == '1');
$dgEnabled = (($conf['dg_open'] ?? '0') == '1');
$cloudDgTitle = ($cloudEnabled && $dgEnabled) ? '云端/代挂' : ($cloudEnabled ? '云端' : '代挂');
$cloudQQ = $cloudEnabled ? $DB->getRow("SELECT id,cityid,login_zt FROM pre_qq WHERE qq='{$cloudQueryQQ}' AND zid='{$user_id}' LIMIT 1") : null;
$dgQQ = null;
if ($dgEnabled) {
    $dgQQ = $DB->getRow("SELECT id,cityid,login_zt FROM pre_dg_qq WHERE qq='{$cloudQueryQQ}' AND zid='{$user_id}' LIMIT 1");
}
$cloudUpdateStatusEnabled = (($conf['qzone_cloud_update_status'] ?? '1') == '1');
$cloudVipRequired = (($conf['qzone_cloud_cookie'] ?? '0') == '1');
$cloudVipAllowed = !$cloudVipRequired || $isVip;
$cloudOnline = $cloudQQ && intval($cloudQQ['login_zt']) === 1;
$dgOnline = $dgQQ && intval($dgQQ['login_zt']) === 1;
$showCloudCookieBtn = $cloudUpdateStatusEnabled && $cloudVipAllowed && ($cloudOnline || $dgOnline);
$cloudCookieHintClass = 'text-sm text-gray-500 bg-gray-100 px-2.5 py-1 rounded-full inline-flex items-center';
$cloudCookieHintIcon = 'fas fa-info-circle text-gray-400';
if (!$cloudUpdateStatusEnabled) {
    $cloudCookieHint = '功能未开启';
} elseif (!$cloudVipAllowed) {
    $cloudCookieHint = '需VIP';
    $cloudCookieHintClass = 'text-sm text-amber-600 bg-amber-50 border border-amber-100 px-2.5 py-1 rounded-full inline-flex items-center';
    $cloudCookieHintIcon = 'fas fa-crown text-amber-500';
} elseif (!$cloudEnabled && !$dgEnabled) {
    $cloudCookieHint = '云端/代挂功能未开启';
} elseif (!$cloudQQ && !$dgQQ) {
    $cloudCookieHint = ($cloudEnabled && $dgEnabled) ? '云端/代挂未添加该QQ' : ($cloudEnabled ? '云端版未添加该QQ' : '代挂版未添加该QQ');
} elseif ($cloudOnline) {
    $cloudCookieHint = '云端在线';
    $cloudCookieHintClass = 'text-sm text-emerald-600 bg-emerald-50 border border-emerald-100 px-2.5 py-1 rounded-full inline-flex items-center';
    $cloudCookieHintIcon = 'fas fa-check-circle text-emerald-500';
} elseif ($dgOnline) {
    $cloudCookieHint = '代挂在线';
    $cloudCookieHintClass = 'text-sm text-emerald-600 bg-emerald-50 border border-emerald-100 px-2.5 py-1 rounded-full inline-flex items-center';
    $cloudCookieHintIcon = 'fas fa-check-circle text-emerald-500';
} else {
    if ($cloudEnabled && $dgEnabled && $cloudQQ && $dgQQ) $cloudCookieHint = '云端/代挂离线';
    elseif ($cloudQQ) $cloudCookieHint = '云端版离线';
    else $cloudCookieHint = '代挂版离线';
    $cloudCookieHintClass = 'text-sm text-rose-600 bg-rose-50 border border-rose-100 px-2.5 py-1 rounded-full inline-flex items-center';
    $cloudCookieHintIcon = 'fas fa-cloud-slash text-rose-500';
}

$config = $DB->getRow("SELECT * FROM " . DBQZ . "qzone_config WHERE qid='{$qid}'");
if (!$config) {
    $DB->exec("INSERT INTO " . DBQZ . "qzone_config (qid) VALUES ('{$qid}')");
    $config = [];
}

$cloudAutoUpdateChecked = intval($config['cloud_auto_update_ck'] ?? 0) === 1;

$vipConfig = [
    'ssmz' => ($conf['qzone_ssmz_vip'] ?? '1') == '1',
    'ssmz_hourly' => ($conf['qzone_ssmz_hourly_vip'] ?? '0') == '1',
    'ssmp' => ($conf['qzone_ssmp_vip'] ?? '1') == '1',
    'ssmp_hourly' => ($conf['qzone_ssmp_hourly_vip'] ?? '0') == '1',
    'ssmz_cycle' => ($conf['qzone_ssmz_cycle_vip'] ?? '0') == '1',
    'ssmp_cycle' => ($conf['qzone_ssmp_cycle_vip'] ?? '0') == '1',
    'zdfss' => ($conf['qzone_zdfss_vip'] ?? '1') == '1',
    'zdfss_delete_prev' => ($conf['qzone_zdfss_delete_vip'] ?? '1') == '1',
    'zfss' => ($conf['qzone_zfss_vip'] ?? '1') == '1',
    'sign' => ($conf['qzone_sign_vip'] ?? '0') == '1',
    'clear_ss' => ($conf['qzone_clear_ss_vip'] ?? '1') == '1',
    'clear_ly' => ($conf['qzone_clear_ly_vip'] ?? '1') == '1',
    'cloud_cookie' => ($conf['qzone_cloud_cookie'] ?? '0') == '1',
];
$freeSsmzCycle = max(20, intval($conf['qzone_free_ssmz_cycle'] ?? 60));
$freeSsmpCycle = max(20, intval($conf['qzone_free_ssmp_cycle'] ?? 60));
$freeHourlySsmz = max(0, intval($conf['qzone_free_hourly_ssmz'] ?? 0));
$freeHourlySsmp = max(0, intval($conf['qzone_free_hourly_ssmp'] ?? 0));

function getVipBadge($feature, $isVip, $vipConfig) {
    $needVip = $vipConfig[$feature] ?? false;
    if (!$needVip) return '<span class="ml-2 px-1.5 py-0.5 bg-green-100 text-green-700 text-xs rounded-full">免费</span>';
    if ($isVip) return '<span class="ml-2 px-1.5 py-0.5 bg-yellow-100 text-yellow-700 text-xs rounded-full">VIP</span>';
    return '<span class="ml-2 px-1.5 py-0.5 bg-red-100 text-red-700 text-xs rounded-full">需VIP</span>';
}

function parseWhitelistValue($val) {
    return array_values(array_unique(array_filter(array_map('trim', preg_split('/[\*\s,，\r\n]+/', (string)($val ?? ''))))));
}

function parseImageValue($val) {
    $raw = trim((string)($val ?? ''));
    if (!$raw) return [];
    $parsed = json_decode($raw, true);
    $arr = is_array($parsed) ? $parsed : preg_split('/[\r\n,，]+/', $raw);
    return array_values(array_unique(array_filter(array_map('trim', $arr), function($v) {
        return preg_match('/^https?:\/\//i', $v);
    })));
}

$ssmzWhitelistCount = count(parseWhitelistValue($config['ssmz_whitelist'] ?? ''));
$ssmzBlacklistCount = count(parseWhitelistValue($config['ssmz_blacklist'] ?? ''));

// 秒赞频率
$ssmzCycleSeconds = intval($config['ssmz_cycle'] ?? 60);
if ($ssmzCycleSeconds < 20) $ssmzCycleSeconds = 60;
if ($vipConfig['ssmz_cycle'] && !$isVip) $ssmzCycleSeconds = $freeSsmzCycle;

// 秒评频率
$ssmpCycleSeconds = intval($config['ssmp_cycle'] ?? 60);
if ($ssmpCycleSeconds < 20) $ssmpCycleSeconds = 60;
if ($vipConfig['ssmp_cycle'] && !$isVip) $ssmpCycleSeconds = $freeSsmpCycle;
$ssmpWhitelistCount = count(parseWhitelistValue($config['ssmp_whitelist'] ?? ''));
$ssmpBlacklistCount = count(parseWhitelistValue($config['ssmp_blacklist'] ?? ''));
$zfssWhitelistCount = count(parseWhitelistValue($config['zfss_forward_list'] ?? ''));

$ssmpImagesText = $config['ssmp_pic_url'] ?? '';
$ssmpImagesArr = parseImageValue($ssmpImagesText);
$zdfssImagesText = $config['zdfss_pic_url'] ?? '';
$zdfssImagesArr = parseImageValue($zdfssImagesText);

$zdfssCycleSeconds = intval($config['zdfss_exec_cycle'] ?? 3600);
$zdfssCycleMinutes = max(1, intval(floor($zdfssCycleSeconds / 60)));
$zdfssCycleUnit = 'minute';
$zdfssCycleNum = $zdfssCycleMinutes;
if ($zdfssCycleMinutes % 1440 === 0) { $zdfssCycleUnit = 'day'; $zdfssCycleNum = intval($zdfssCycleMinutes / 1440); }
elseif ($zdfssCycleMinutes % 60 === 0) { $zdfssCycleUnit = 'hour'; $zdfssCycleNum = intval($zdfssCycleMinutes / 60); }

// 优先使用 sign_cycle(分钟)，兼容旧 sign_exec_cycle(秒)
$signCycleMinutes = intval($config['sign_cycle'] ?? 0);
if ($signCycleMinutes < 1) {
    $signCycleSeconds = intval($config['sign_exec_cycle'] ?? 86400);
    $signCycleMinutes = max(1, intval(floor($signCycleSeconds / 60)));
}
$signCycleUnit = 'minute';
$signCycleNum = $signCycleMinutes;
if ($signCycleMinutes % 1440 === 0) { $signCycleUnit = 'day'; $signCycleNum = intval($signCycleMinutes / 1440); }
elseif ($signCycleMinutes % 60 === 0) { $signCycleUnit = 'hour'; $signCycleNum = intval($signCycleMinutes / 60); }


$ssmzHourlyValue = intval($config['ssmz_hourly_max'] ?? 300);
if ($vipConfig['ssmz_hourly'] && !$isVip) $ssmzHourlyValue = $freeHourlySsmz;

$ssmpHourlyValue = intval($config['ssmp_hourly_max'] ?? 0);
if ($vipConfig['ssmp_hourly'] && !$isVip) $ssmpHourlyValue = $freeHourlySsmp;

$ssmzDisabled = $vipConfig['ssmz'] && !$isVip ? 'disabled' : '';
$ssmzClass = $vipConfig['ssmz'] && !$isVip ? 'opacity-50' : '';
$ssmzHourlyDisabled = ($ssmzDisabled || ($vipConfig['ssmz_hourly'] && !$isVip)) ? 'disabled' : '';

$ssmpDisabled = $vipConfig['ssmp'] && !$isVip ? 'disabled' : '';
$ssmpClass = $vipConfig['ssmp'] && !$isVip ? 'opacity-50' : '';
$ssmpHourlyDisabled = ($ssmpDisabled || ($vipConfig['ssmp_hourly'] && !$isVip)) ? 'disabled' : '';

$zdfssDisabled = $vipConfig['zdfss'] && !$isVip ? 'disabled' : '';
$zdfssClass = $vipConfig['zdfss'] && !$isVip ? 'opacity-50' : '';
$zdfssDeletePrevVipLocked = ($vipConfig['zdfss_delete_prev'] && !$isVip);
$zdfssDeletePrevDisabled = $zdfssDeletePrevVipLocked ? 'disabled' : '';

$zfssDisabled = $vipConfig['zfss'] && !$isVip ? 'disabled' : '';
$zfssClass = $vipConfig['zfss'] && !$isVip ? 'opacity-50' : '';

$signDisabled = $vipConfig['sign'] && !$isVip ? 'disabled' : '';
$signClass = $vipConfig['sign'] && !$isVip ? 'opacity-50' : '';

$ssmzCycleDisabled = $vipConfig['ssmz_cycle'] && !$isVip ? 'disabled' : '';
$ssmzCycleClass = $vipConfig['ssmz_cycle'] && !$isVip ? 'opacity-50' : '';

$ssmpCycleDisabled = $vipConfig['ssmp_cycle'] && !$isVip ? 'disabled' : '';
$ssmpCycleClass = $vipConfig['ssmp_cycle'] && !$isVip ? 'opacity-50' : '';

$clearSsDisabled = $vipConfig['clear_ss'] && !$isVip ? 'disabled' : '';
$clearLyDisabled = $vipConfig['clear_ly'] && !$isVip ? 'disabled' : '';
$clearClass = ($clearSsDisabled && $clearLyDisabled) ? 'opacity-50' : '';
?>

<div class="space-y-5">
    <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5">
        <div class="flex items-center gap-4">
            <a href="qzone.php" class="w-10 h-10 flex items-center justify-center rounded-full bg-gray-100 hover:bg-gray-200 transition-colors flex-shrink-0">
                <i class="fas fa-arrow-left text-gray-600"></i>
            </a>
            <div class="relative flex-shrink-0">
                <img src="https://q1.qlogo.cn/g?b=qq&nk=<?php echo $qq['qq']; ?>&s=100"
                     class="w-14 h-14 rounded-full border-2 border-indigo-100 object-cover shadow-sm"
                     onerror="this.src='https://q1.qlogo.cn/g?b=qq&nk=0&s=100'">
                <div class="absolute -bottom-1 -right-1 w-4 h-4 rounded-full border-2 border-white <?php echo $qq['login_status'] == 0 ? 'bg-green-500' : 'bg-gray-400'; ?>"></div>
            </div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2">
                    <h1 class="text-xl font-bold text-gray-800"><?php echo htmlspecialchars($qq['qq']); ?></h1>
                    <?php if ($isVip): ?><span class="px-2 py-0.5 text-xs font-bold text-white bg-gradient-to-r from-yellow-400 to-yellow-500 rounded">VIP</span><?php endif; ?>
                </div>
                <p class="text-sm text-gray-500 mt-0.5 truncate">昵称：<?php echo htmlspecialchars($qq['nickname'] ?? ''); ?></p>
            </div>
        </div>
    </div>

    <?php if (!$isVip && ($vipConfig['ssmz'] || $vipConfig['ssmp'] || $vipConfig['zdfss'] || $vipConfig['zfss'] || $vipConfig['sign'] || $vipConfig['ssmz_cycle'] || $vipConfig['ssmp_cycle'] || $vipConfig['clear_ss'] || $vipConfig['clear_ly'])): ?>
    <div class="bg-gradient-to-r from-yellow-50 to-orange-50 rounded-xl border border-yellow-200 p-4">
        <div class="flex items-center">
            <i class="fas fa-crown text-yellow-500 text-xl mr-3"></i>
            <div>
                <p class="font-medium text-yellow-800">升级VIP解锁更多功能</p>
                <p class="text-sm text-yellow-600 mt-1">部分高级功能需要VIP才能使用</p>
            </div>
        </div>
        <a href="./shop.php" class="mt-3 inline-block px-4 py-2 bg-yellow-500 text-white rounded-lg text-sm hover:bg-yellow-600">立即开通</a>
    </div>
    <?php endif; ?>

    <form method="post" id="config_form" class="space-y-5">
        <input type="hidden" name="qid" value="<?php echo $qid; ?>">

        <!-- 顶部功能卡 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- 失效邮件通知 -->
            <div class="bg-gradient-to-br from-white to-orange-50/40 rounded-2xl border border-orange-100 shadow-sm p-4 md:p-5">
                <div class="flex items-center justify-between">
                    <div>
                        <h4 class="font-medium text-gray-800"><i class="fas fa-envelope text-orange-500 mr-2"></i>失效邮件通知</h4>
                        <p class="text-xs text-gray-400 mt-1">Cookie失效时发送邮件提醒</p>
                    </div>
                    <label class="flex items-center cursor-pointer">
                        <input type="checkbox" name="invalid_remind_switch" value="1" <?php echo ($config['invalid_remind_switch'] ?? 0) == 1 ? 'checked' : ''; ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                        <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo ($config['invalid_remind_switch'] ?? 0) == 1 ? '#3b82f6' : '#e5e7eb' ?>">
                            <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo ($config['invalid_remind_switch'] ?? 0) == 1 ? '20px' : '0' ?>)"></div>
                        </div>
                        <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo ($config['invalid_remind_switch'] ?? 0) == 1 ? '已开启' : '已关闭' ?></span>
                    </label>
                </div>
            </div>

            <!-- 云端/代挂取CK -->
            <div class="bg-gradient-to-br from-white to-blue-50/50 rounded-2xl border border-blue-100 shadow-sm p-4 md:p-5">
                <div class="flex items-center justify-between mb-3">
                    <div>
                        <h4 class="font-medium text-gray-800"><i class="fas fa-cloud text-blue-500 mr-2"></i>从<?php echo $cloudDgTitle; ?>更新状态<?php echo getVipBadge('cloud_cookie', $isVip, $vipConfig) ?></h4>
                        <p class="text-xs text-gray-400 mt-1"><?php echo ($cloudEnabled && $dgEnabled) ? '云端和代挂任一在线即可更新CK' : ($cloudEnabled ? '云端在线即可更新CK' : '代挂在线即可更新CK'); ?></p>
                    </div>
                    <label class="flex items-center cursor-pointer">
                        <input type="checkbox" name="cloud_auto_update_ck" value="1" <?php echo $cloudAutoUpdateChecked ? 'checked' : '' ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                        <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo $cloudAutoUpdateChecked ? '#3b82f6' : '#e5e7eb' ?>">
                            <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo $cloudAutoUpdateChecked ? '20px' : '0' ?>)"></div>
                        </div>
                        <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo $cloudAutoUpdateChecked ? '已开启' : '已关闭' ?></span>
                    </label>
                </div>
                <div class="flex items-center justify-between gap-3">
                    <span class="<?php echo $cloudCookieHintClass ?>">
                        <i class="<?php echo $cloudCookieHintIcon ?> mr-1.5"></i><?php echo $cloudCookieHint ?>
                    </span>
                    <?php if ($showCloudCookieBtn): ?>
                    <button type="button" onclick="getCloudCookie()" class="px-3 py-1.5 bg-blue-500 hover:bg-blue-600 text-white rounded-lg text-xs transition-colors whitespace-nowrap">
                        <i class="fas fa-sync-alt mr-1"></i>立即获取CK
                    </button>
                    <?php endif; ?>
                </div>
            </div>

        </div>

        <!-- 主体两栏布局 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
            <!-- 左侧 -->
            <div class="space-y-5">
                <!-- 说说秒赞 -->
                <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5 <?php echo $ssmzClass ?>">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="font-medium text-gray-800"><i class="fas fa-heart text-red-500 mr-2"></i>说说秒赞<?php echo getVipBadge('ssmz', $isVip, $vipConfig) ?></h4>
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" name="ssmz_switch" value="1" <?php echo ($config['ssmz_switch'] ?? 0) == 1 ? 'checked' : '' ?> <?php echo $ssmzDisabled ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                            <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo ($config['ssmz_switch'] ?? 0) == 1 ? '#3b82f6' : '#e5e7eb' ?>">
                                <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo ($config['ssmz_switch'] ?? 0) == 1 ? '20px' : '0' ?>)"></div>
                            </div>
                            <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo ($config['ssmz_switch'] ?? 0) == 1 ? '已开启' : '已关闭' ?></span>
                        </label>
                    </div>
                    <div class="space-y-3">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm text-gray-600 mb-1">白名单QQ</label>
                                <input type="hidden" name="ssmz_whitelist" id="ssmz_whitelist" value="<?php echo htmlspecialchars($config['ssmz_whitelist'] ?? '') ?>" data-default="<?php echo htmlspecialchars($config['ssmz_whitelist'] ?? '') ?>">
                                <button type="button" onclick="openWhitelist('ssmz_whitelist','说说秒赞白名单')" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $ssmzDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $ssmzDisabled ?>><i class="fas fa-users-cog mr-1 text-indigo-500"></i>管理白名单（<?php echo $ssmzWhitelistCount ?>）</button>
                            </div>
                            <div>
                                <label class="block text-sm text-gray-600 mb-1">黑名单QQ</label>
                                <input type="hidden" name="ssmz_blacklist" id="ssmz_blacklist" value="<?php echo htmlspecialchars($config['ssmz_blacklist'] ?? '') ?>" data-default="<?php echo htmlspecialchars($config['ssmz_blacklist'] ?? '') ?>">
                                <button type="button" onclick="openWhitelist('ssmz_blacklist','说说秒赞黑名单')" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $ssmzDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $ssmzDisabled ?>><i class="fas fa-user-slash mr-1 text-red-500"></i>管理黑名单（<?php echo $ssmzBlacklistCount ?>）</button>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm text-gray-600 mb-1">每小时最大点赞数<?php echo getVipBadge('ssmz_hourly', $isVip, $vipConfig) ?></label>
                            <input type="number" name="ssmz_hourly_max" value="<?php echo $ssmzHourlyValue ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $ssmzHourlyDisabled ?>>
                            <p class="mt-1 text-xs text-gray-400">0为不限</p>
                        </div>

                        <div class="<?php echo $ssmzCycleClass ?>">
                            <label class="block text-sm text-gray-600 mb-1">执行频率（秒）<?php echo getVipBadge('ssmz_cycle', $isVip, $vipConfig) ?></label>
                            <input type="number" min="20" name="ssmz_cycle" value="<?php echo $ssmzCycleSeconds ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $ssmzCycleDisabled ?>>
                            <p class="mt-1 text-xs text-gray-400"><?php echo $vipConfig['ssmz_cycle'] && !$isVip ? '免费用户固定为 ' . $freeSsmzCycle . ' 秒' : '最低20秒，建议60秒' ?></p>
                        </div>
                    </div>
                </div>

                <!-- 自动发说说 -->
                <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5 <?php echo $zdfssClass ?>">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="font-medium text-gray-800"><i class="fas fa-edit text-green-500 mr-2"></i>自动发说说<?php echo getVipBadge('zdfss', $isVip, $vipConfig) ?></h4>
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" id="zdfss_switch" name="zdfss_switch" value="1" <?php echo ($config['zdfss_switch'] ?? 0) == 1 ? 'checked' : '' ?> <?php echo $zdfssDisabled ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                            <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo ($config['zdfss_switch'] ?? 0) == 1 ? '#3b82f6' : '#e5e7eb' ?>">
                                <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo ($config['zdfss_switch'] ?? 0) == 1 ? '20px' : '0' ?>)"></div>
                            </div>
                            <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo ($config['zdfss_switch'] ?? 0) == 1 ? '已开启' : '已关闭' ?></span>
                        </label>
                    </div>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">发布频率</label>
                            <div class="grid grid-cols-2 gap-2">
                                <input type="number" min="1" name="zdfss_cycle_num" value="<?php echo $zdfssCycleNum ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $zdfssDisabled ?>>
                                <select name="zdfss_cycle_unit" data-default="<?php echo $zdfssCycleUnit ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $zdfssDisabled ?>>
                                    <option value="minute" <?php echo $zdfssCycleUnit === 'minute' ? 'selected' : '' ?>>分钟</option>
                                    <option value="hour" <?php echo $zdfssCycleUnit === 'hour' ? 'selected' : '' ?>>小时</option>
                                    <option value="day" <?php echo $zdfssCycleUnit === 'day' ? 'selected' : '' ?>>天</option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">说说内容</label>
                            <textarea name="zdfss_content" rows="2" placeholder="每行一条，随机发送" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $zdfssDisabled ?>><?php echo htmlspecialchars($config['zdfss_content'] ?? '') ?></textarea>
                            <p class="text-xs text-gray-400 mt-1">支持变量：[当前时间]、[随机表情]、[随机一言]、[网易云热评]</p>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">说说图片</label>
                            <input type="hidden" name="zdfss_pic_url" id="zdfss_pic_url" value="<?php echo htmlspecialchars($zdfssImagesText) ?>" data-default="<?php echo htmlspecialchars($zdfssImagesText) ?>">
                            <button type="button" id="zdfss_pic_url_btn" onclick="openImage('zdfss_pic_url','说说图片','zdfss_pic_url_btn',<?php echo $zdfssDisabled ? 'true' : 'false' ?>)" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $zdfssDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $zdfssDisabled ?>><i class="far fa-image mr-1 text-green-500"></i>编辑图片（<?php echo count($zdfssImagesArr) ?>）</button>
                        </div>
                        <label id="zdfss_delete_prev_label" class="flex items-center text-sm text-gray-600">
                            <input type="checkbox" id="zdfss_delete_prev" name="zdfss_delete_prev" value="1" <?php echo ($config['zdfss_delete_prev'] ?? 0) == 1 ? 'checked' : '' ?> class="mr-2 rounded" <?php echo $zdfssDeletePrevDisabled ?> data-vip-locked="<?php echo $zdfssDeletePrevVipLocked ? '1' : '0' ?>">
                            发说说前删除上一条<?php echo getVipBadge('zdfss_delete_prev', $isVip, $vipConfig) ?>
                        </label>
                    </div>
                </div>

                <!-- 空间签到 -->
                <div class="bg-gradient-to-br from-white to-purple-50/40 rounded-2xl border border-purple-100 shadow-sm p-4 md:p-5 <?php echo $signClass ?>">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="font-medium text-gray-800"><i class="fas fa-calendar-check text-purple-500 mr-2"></i>空间签到<?php echo getVipBadge('sign', $isVip, $vipConfig) ?></h4>
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" name="sign_switch" value="1" <?php echo ($config['sign_switch'] ?? 0) == 1 ? 'checked' : '' ?> <?php echo $signDisabled ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                            <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo ($config['sign_switch'] ?? 0) == 1 ? '#3b82f6' : '#e5e7eb' ?>">
                                <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo ($config['sign_switch'] ?? 0) == 1 ? '20px' : '0' ?>)"></div>
                            </div>
                            <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo ($config['sign_switch'] ?? 0) == 1 ? '已开启' : '已关闭' ?></span>
                        </label>
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">签到频率</label>
                        <div class="grid grid-cols-2 gap-2">
                            <input type="number" min="1" name="sign_cycle_num" value="<?php echo $signCycleNum ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $signDisabled ?>>
                            <select name="sign_cycle_unit" data-default="<?php echo $signCycleUnit ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $signDisabled ?>>
                                <option value="minute" <?php echo $signCycleUnit === 'minute' ? 'selected' : '' ?>>分钟</option>
                                <option value="hour" <?php echo $signCycleUnit === 'hour' ? 'selected' : '' ?>>小时</option>
                                <option value="day" <?php echo $signCycleUnit === 'day' ? 'selected' : '' ?>>天</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧 -->
            <div class="space-y-5">
                <!-- 说说秒评 -->
                <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5 <?php echo $ssmpClass ?>">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="font-medium text-gray-800"><i class="fas fa-comment text-blue-500 mr-2"></i>说说秒评<?php echo getVipBadge('ssmp', $isVip, $vipConfig) ?></h4>
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" name="ssmp_switch" value="1" <?php echo ($config['ssmp_switch'] ?? 0) == 1 ? 'checked' : '' ?> <?php echo $ssmpDisabled ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                            <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo ($config['ssmp_switch'] ?? 0) == 1 ? '#3b82f6' : '#e5e7eb' ?>">
                                <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo ($config['ssmp_switch'] ?? 0) == 1 ? '20px' : '0' ?>)"></div>
                            </div>
                            <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo ($config['ssmp_switch'] ?? 0) == 1 ? '已开启' : '已关闭' ?></span>
                        </label>
                    </div>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">评论内容</label>
                            <textarea name="ssmp_comment" rows="2" placeholder="每行一条，随机发送" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $ssmpDisabled ?>><?php echo htmlspecialchars($config['ssmp_comment'] ?? '') ?></textarea>
                            <p class="mt-1 text-xs text-gray-400">支持变量：[随机一言] [网易云热评] [随机表情] [当前时间]</p>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm text-gray-600 mb-1">评论图片</label>
                                <input type="hidden" name="ssmp_pic_url" id="ssmp_pic_url" value="<?php echo htmlspecialchars($ssmpImagesText) ?>" data-default="<?php echo htmlspecialchars($ssmpImagesText) ?>">
                                <button type="button" id="ssmp_pic_url_btn" onclick="openImage('ssmp_pic_url','评论图片','ssmp_pic_url_btn',<?php echo $ssmpDisabled ? 'true' : 'false' ?>)" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $ssmpDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $ssmpDisabled ?>><i class="far fa-image mr-1 text-blue-500"></i>编辑图片（<?php echo count($ssmpImagesArr) ?>）</button>
                            </div>
                            <div>
                                <label class="block text-sm text-gray-600 mb-1">白名单QQ</label>
                                <input type="hidden" name="ssmp_whitelist" id="ssmp_whitelist" value="<?php echo htmlspecialchars($config['ssmp_whitelist'] ?? '') ?>" data-default="<?php echo htmlspecialchars($config['ssmp_whitelist'] ?? '') ?>">
                                <button type="button" onclick="openWhitelist('ssmp_whitelist','说说秒评白名单')" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $ssmpDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $ssmpDisabled ?>><i class="fas fa-users-cog mr-1 text-blue-500"></i>管理白名单（<?php echo $ssmpWhitelistCount ?>）</button>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">黑名单QQ</label>
                            <input type="hidden" name="ssmp_blacklist" id="ssmp_blacklist" value="<?php echo htmlspecialchars($config['ssmp_blacklist'] ?? '') ?>" data-default="<?php echo htmlspecialchars($config['ssmp_blacklist'] ?? '') ?>">
                            <button type="button" onclick="openWhitelist('ssmp_blacklist','说说秒评黑名单')" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $ssmpDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $ssmpDisabled ?>><i class="fas fa-user-slash mr-1 text-red-500"></i>管理黑名单（<?php echo $ssmpBlacklistCount ?>）</button>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">每小时最大评论数<?php echo getVipBadge('ssmp_hourly', $isVip, $vipConfig) ?></label>
                            <input type="number" name="ssmp_hourly_max" value="<?php echo $ssmpHourlyValue ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $ssmpHourlyDisabled ?>>
                            <p class="mt-1 text-xs text-gray-400">0为不限</p>
                        </div>

                        <div class="<?php echo $ssmpCycleClass ?>">
                            <label class="block text-sm text-gray-600 mb-1">执行频率（秒）<?php echo getVipBadge('ssmp_cycle', $isVip, $vipConfig) ?></label>
                            <input type="number" min="20" name="ssmp_cycle" value="<?php echo $ssmpCycleSeconds ?>" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $ssmpCycleDisabled ?>>
                            <p class="mt-1 text-xs text-gray-400"><?php echo $vipConfig['ssmp_cycle'] && !$isVip ? '免费用户固定为 ' . $freeSsmpCycle . ' 秒' : '最低20秒，建议60秒' ?></p>
                        </div>
                    </div>
                </div>

                <!-- 转发说说 -->
                <div class="bg-white rounded-2xl border border-indigo-100 shadow-sm p-4 md:p-5 <?php echo $zfssClass ?>">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="font-medium text-gray-800"><i class="fas fa-share text-cyan-500 mr-2"></i>转发说说<?php echo getVipBadge('zfss', $isVip, $vipConfig) ?></h4>
                        <label class="flex items-center cursor-pointer">
                            <input type="checkbox" name="zfss_switch" value="1" <?php echo ($config['zfss_switch'] ?? 0) == 1 ? 'checked' : '' ?> <?php echo $zfssDisabled ?> class="sr-only peer" onchange="updateToggle(this);autoSave()">
                            <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors toggle-bg" style="background-color:<?php echo ($config['zfss_switch'] ?? 0) == 1 ? '#3b82f6' : '#e5e7eb' ?>">
                                <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform toggle-dot" style="transform:translateX(<?php echo ($config['zfss_switch'] ?? 0) == 1 ? '20px' : '0' ?>)"></div>
                            </div>
                            <span class="ml-2 text-sm text-gray-600 toggle-label"><?php echo ($config['zfss_switch'] ?? 0) == 1 ? '已开启' : '已关闭' ?></span>
                        </label>
                    </div>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">转发附加内容</label>
                            <input type="text" name="zfss_content" value="<?php echo htmlspecialchars($config['zfss_content'] ?? '') ?>" placeholder="转发时附加的文字，可为空" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" <?php echo $zfssDisabled ?>>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">转发白名单QQ</label>
                            <input type="hidden" name="zfss_forward_list" id="zfss_forward_list" value="<?php echo htmlspecialchars($config['zfss_forward_list'] ?? '') ?>" data-default="<?php echo htmlspecialchars($config['zfss_forward_list'] ?? '') ?>">
                            <button type="button" onclick="openWhitelist('zfss_forward_list','转发说说白名单')" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-left hover:bg-gray-50 <?php echo $zfssDisabled ? 'opacity-50 pointer-events-none' : '' ?>" <?php echo $zfssDisabled ?>><i class="fas fa-users-cog mr-1 text-cyan-500"></i>管理白名单（<?php echo $zfssWhitelistCount ?>）</button>
                        </div>
                        <p class="text-xs text-gray-400">每次任务最多转发3条，未填写白名单将不会执行转发</p>
                    </div>
                </div>

                <!-- 危险操作 -->
                <div class="bg-red-50 rounded-2xl border border-red-200 shadow-sm p-4 md:p-5 <?php echo $clearClass ?>">
                    <h4 class="font-medium text-red-700 mb-3"><i class="fas fa-exclamation-triangle mr-2"></i>危险操作</h4>
                    <div class="space-y-2">
                        <label class="flex items-center text-sm text-gray-700">
                            <input type="checkbox" name="clear_ss_switch" value="1" <?php echo ($config['clear_ss_switch'] ?? 0) == 1 ? 'checked' : '' ?> class="mr-2 rounded" <?php echo $clearSsDisabled ?>>
                            自动清空说说<?php echo getVipBadge('clear_ss', $isVip, $vipConfig) ?>
                        </label>
                        <label class="flex items-center text-sm text-gray-700">
                            <input type="checkbox" name="clear_ly_switch" value="1" <?php echo ($config['clear_ly_switch'] ?? 0) == 1 ? 'checked' : '' ?> class="mr-2 rounded" <?php echo $clearLyDisabled ?>>
                            自动清空留言<?php echo getVipBadge('clear_ly', $isVip, $vipConfig) ?>
                        </label>
                    </div>
                </div>

            </div>
        </div>

        <div class="flex gap-3">
            <a href="qzone.php" class="flex-1 py-3 border border-gray-300 text-gray-700 rounded-xl text-center font-medium hover:bg-gray-50 transition-colors">
                <i class="fas fa-arrow-left mr-1"></i>返回列表
            </a>
        </div>
    </form>
</div>

<!-- 白名单弹窗 -->
<div id="wl_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">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold" id="wl_title">白名单管理</h3>
            <button onclick="closeWL(false)" class="text-gray-500 hover:text-gray-700 text-xl">&times;</button>
        </div>
        <div class="p-4 space-y-3">
            <div class="flex gap-2">
                <input type="text" id="wl_input" class="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="输入QQ号，回车或点添加">
                <button type="button" onclick="addWL()" class="px-3 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700">添加</button>
            </div>
            <div class="border-t pt-3">
                <label class="block text-xs text-gray-500 mb-1">批量添加（每行一个QQ号，或用逗号/空格分隔）</label>
                <textarea id="wl_batch_input" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" rows="3" placeholder="123456789&#10;987654321&#10;或: 123456789, 987654321"></textarea>
                <button type="button" onclick="batchAddWL()" class="mt-2 px-3 py-1.5 text-xs bg-green-600 text-white rounded-lg hover:bg-green-700">批量添加</button>
            </div>
            <div id="wl_list" class="space-y-2 max-h-48 overflow-y-auto"></div>
            <div class="flex items-center justify-between text-xs text-gray-400">
                <span>仅支持5-12位QQ号</span>
                <span id="wl_count">共0个</span>
            </div>
        </div>
        <div class="p-4 border-t flex gap-2">
            <button onclick="exportWL()" class="flex-1 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm"><i class="fas fa-download mr-1"></i>导出</button>
            <button onclick="closeWL(false)" class="flex-1 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200">取消</button>
            <button onclick="closeWL(true)" class="flex-1 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">保存</button>
        </div>
    </div>
</div>

<!-- 图片弹窗 -->
<div id="img_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-2xl mx-4 shadow-2xl">
        <div class="p-4 border-b flex justify-between items-center">
            <h3 class="font-bold text-xl" id="img_title">图片管理</h3>
            <button onclick="closeImg(false)" class="text-gray-500 hover:text-gray-700 text-3xl leading-none">&times;</button>
        </div>
        <div class="p-4 space-y-3">
            <div class="flex gap-2">
                <input type="text" id="img_input" class="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="请输入图片URL">
                <button type="button" onclick="addImg()" class="px-5 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700">添加</button>
                <button type="button" onclick="uploadImg()" class="px-5 py-2 text-sm bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">上传</button>
                <input type="file" id="img_file" class="hidden" accept="image/*" onchange="doUpload(this)">
            </div>
            <div id="img_list" class="space-y-2 max-h-64 overflow-y-auto border border-gray-200 rounded-xl p-3 bg-gray-50/60"></div>
        </div>
        <div class="p-4 border-t flex items-center justify-end gap-3">
            <button type="button" onclick="closeImg(false)" class="px-6 py-2 border border-blue-400 text-blue-600 rounded-xl hover:bg-blue-50">取消</button>
            <button type="button" onclick="closeImg(true)" class="px-6 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700">保存</button>
        </div>
    </div>
</div>

<style>
.toggle-bg{transition:background-color .2s}
.toggle-dot{transition:transform .2s}
</style>

<script>
var wlCtx={field:'',list:[]},imgCtx={field:'',list:[],btn:''},saveTimer=null,saving=false;

function $(id){return document.getElementById(id)}
function esc(s){return(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;')}

function updateToggle(cb){
    var div=cb.nextElementSibling;
    if(!div||!div.classList.contains('toggle-bg'))return;
    var span=div.nextElementSibling;
    div.style.backgroundColor=cb.checked?'#3b82f6':'#e5e7eb';
    var dot=div.querySelector('div');if(dot)dot.style.transform=cb.checked?'translateX(20px)':'translateX(0)';
    if(span)span.textContent=cb.checked?'已开启':'已关闭';
}

function parseWL(v){return(v||'').split(/[\*\s,，\r\n]+/).map(function(x){return x.trim()}).filter(Boolean).filter(function(x,i,a){return a.indexOf(x)===i})}
function toWL(a){return(a||[]).join('*')}

function openWhitelist(f,t){
    wlCtx.field=f;$('wl_title').textContent=t;$('wl_input').value='';$('wl_batch_input').value='';
    wlCtx.list=parseWL($(f).value);renderWL();
    $('wl_modal').classList.remove('hidden');$('wl_modal').classList.add('flex');
}
function closeWL(save){
    $('wl_modal').classList.add('hidden');$('wl_modal').classList.remove('flex');
    if(save){
        $(wlCtx.field).value=toWL(wlCtx.list);
        autoSave();
        refreshWLBtn();
    }else{
        $(wlCtx.field).value=$(wlCtx.field).getAttribute('data-default')||'';
    }
}
function refreshWLBtn(){
    var cnt=wlCtx.list.length;
    var btn=$(wlCtx.field).nextElementSibling;
    if(btn&&btn.tagName==='BUTTON'){
        var html=btn.innerHTML;
        btn.innerHTML=html.replace(/\（\d+\）/,'（'+cnt+'）');
    }
}
function renderWL(){
    var h=$('wl_list');if(!wlCtx.list.length){h.innerHTML='<p class="text-sm text-gray-400 text-center py-4">暂无数据</p>';$('wl_count').textContent='共0个';return}
    h.innerHTML=wlCtx.list.map(function(q,i){return'<div class="flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg"><span class="text-sm">'+esc(q)+'</span><button type="button" onclick="rmWL('+i+')" class="text-xs px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600">删除</button></div>'}).join('');
    $('wl_count').textContent='共'+wlCtx.list.length+'个';
}
function addWL(){var v=$('wl_input').value.trim();if(!/^\d{5,12}$/.test(v)){toast('请输入正确的QQ号','error');return}if(wlCtx.list.indexOf(v)<0)wlCtx.list.push(v);$('wl_input').value='';renderWL()}
function batchAddWL(){
    var v=$('wl_batch_input').value.trim();
    if(!v){toast('请输入QQ号','error');return}
    var arr=v.split(/[\r\n,，\s]+/).map(function(x){return x.trim()}).filter(function(x){return/^\d{5,12}$/.test(x)});
    if(!arr.length){toast('未找到有效的QQ号','error');return}
    var added=0;
    arr.forEach(function(q){if(wlCtx.list.indexOf(q)<0){wlCtx.list.push(q);added++}});
    $('wl_batch_input').value='';
    renderWL();
    toast('成功添加'+added+'个QQ号','success');
}
function exportWL(){
    if(!wlCtx.list.length){toast('暂无数据可导出','error');return}
    var text=wlCtx.list.join('\n');
    if(navigator.clipboard&&navigator.clipboard.writeText){
        navigator.clipboard.writeText(text).then(function(){toast('已复制到剪贴板','success')}).catch(function(){fallbackCopy(text)});
    }else{fallbackCopy(text)}
}
function fallbackCopy(text){
    var ta=document.createElement('textarea');
    ta.value=text;ta.style.position='fixed';ta.style.left='-9999px';
    document.body.appendChild(ta);ta.select();
    try{document.execCommand('copy');toast('已复制到剪贴板','success')}catch(e){toast('复制失败，请手动复制','error')}
    document.body.removeChild(ta);
}
function rmWL(i){wlCtx.list.splice(i,1);renderWL()}
$('wl_input').onkeypress=function(e){if(e.key==='Enter'){e.preventDefault();addWL()}};

function parseImg(v){
    var r=(v||'').trim();if(!r)return[];
    try{var p=JSON.parse(r);if(Array.isArray(p))return p.filter(function(x){return/^https?:\/\//i.test(x)})}catch(e){}
    return r.split(/[\r\n,，]+/).map(function(x){return x.trim()}).filter(function(x){return/^https?:\/\//i.test(x)});
}
function openImage(f,t,b,dis){
    if(dis)return;imgCtx.field=f;imgCtx.btn=b;$('img_title').textContent=t;$('img_input').value='';
    imgCtx.list=parseImg($(f).value);renderImg();
    $('img_modal').classList.remove('hidden');$('img_modal').classList.add('flex');
}
function closeImg(save){
    $('img_modal').classList.add('hidden');$('img_modal').classList.remove('flex');
    if(save){$(imgCtx.field).value=imgCtx.list.join(',');autoSave();refreshImgBtn()}
    else{$(imgCtx.field).value=$(imgCtx.field).defaultValue}
}
function refreshImgBtn(){var b=$(imgCtx.btn);if(b)b.innerHTML='<i class="far fa-image mr-1"></i>编辑图片（'+imgCtx.list.length+'）'}
function renderImg(){
    var h=$('img_list');if(!imgCtx.list.length){h.innerHTML='<p class="text-sm text-gray-400 text-center py-6">暂无图片</p>';return}
    h.innerHTML=imgCtx.list.map(function(u,i){return'<div class="flex items-center gap-3 p-3 bg-white rounded-lg border"><img src="'+esc(u)+'" class="w-14 h-14 rounded object-cover border flex-shrink-0" onerror="this.src=\'https://q1.qlogo.cn/g?b=qq&nk=0&s=100\'"><div class="flex-1 min-w-0 text-sm text-gray-700 truncate">'+esc(u)+'</div><button type="button" onclick="rmImg('+i+')" class="w-9 h-9 rounded-full bg-red-500 text-white hover:bg-red-600 flex items-center justify-center"><i class="far fa-trash-alt"></i></button></div>'}).join('');
}
function addImg(){var v=$('img_input').value.trim();if(!/^https?:\/\//i.test(v)){toast('请输入正确的图片URL','error');return}if(imgCtx.list.indexOf(v)<0)imgCtx.list.push(v);$('img_input').value='';renderImg()}
function rmImg(i){imgCtx.list.splice(i,1);renderImg()}
function uploadImg(){$('img_file').click()}
function doUpload(inp){
    if(!inp.files||!inp.files[0])return;
    var fd=new FormData();fd.append('file',inp.files[0]);
    var xhr=new XMLHttpRequest();
    xhr.open('POST','ajax_qzone.php?act=upload_image',true);
    xhr.onload=function(){
        try{var r=JSON.parse(xhr.responseText);if(r.code===1&&r.url){var u=location.protocol+'//'+location.host+r.url;if(imgCtx.list.indexOf(u)<0)imgCtx.list.push(u);renderImg();toast('上传成功','success')}else toast(r.msg||'上传失败','error')}catch(e){toast('上传失败','error')}
        inp.value='';
    };
    xhr.onerror=function(){toast('上传失败','error');inp.value=''};
    xhr.send(fd);
}
$('img_input').onkeypress=function(e){if(e.key==='Enter'){e.preventDefault();addImg()}};

function toast(m,t){
    var d=document.createElement('div');
    d.style.cssText='position:fixed;top:20px;left:50%;transform:translateX(-50%);background:'+(t==='success'?'#10b981':'#ef4444')+';color:white;padding:10px 20px;border-radius:8px;z-index:9999;font-size:14px';
    d.textContent=m;document.body.appendChild(d);setTimeout(function(){d.remove()},3000);
}

function getCloudCookie(){
    var btn=event.target;
    btn.disabled=true;
    btn.innerHTML='<i class="fas fa-spinner fa-spin mr-1"></i>获取中...';
    var xhr=new XMLHttpRequest();
    xhr.open('GET','ajax_qzone.php?act=get_cloud_cookie&qid=<?php echo $qid ?>',true);
    xhr.onload=function(){
        try{
            var r=JSON.parse(xhr.responseText);
            if(r.code===1){
                toast('获取成功','success');
                setTimeout(function(){location.reload()},1000);
            }else{
                toast(r.msg||'获取失败','error');
            }
        }catch(e){
            toast('获取失败','error');
        }
        btn.disabled=false;
        btn.innerHTML='<i class="fas fa-sync-alt mr-1"></i>获取CK';
    };
    xhr.onerror=function(){
        toast('网络错误','error');
        btn.disabled=false;
        btn.innerHTML='<i class="fas fa-sync-alt mr-1"></i>获取CK';
    };
    xhr.send();
}

function autoSave(){if(saveTimer)clearTimeout(saveTimer);saveTimer=setTimeout(doSave,800)}

function syncZdfssDeletePrevState(){
    var sw = $('zdfss_switch');
    var del = $('zdfss_delete_prev');
    var lbl = $('zdfss_delete_prev_label');
    if(!sw || !del || !lbl) return;
    var vipLocked = del.getAttribute('data-vip-locked') === '1';
    var disabled = vipLocked || !sw.checked;
    del.disabled = disabled;
    if(disabled && !vipLocked){
        del.checked = false;
    }
    lbl.classList.toggle('opacity-50', disabled);
}

function doSave(){
    if(saving)return;saving=true;
    var form=$('config_form'),params=new URLSearchParams();
    params.append('qid',<?php echo $qid ?>);
    var changed=false;

    form.querySelectorAll('input[type="hidden"]:not([name="qid"])').forEach(function(i){
        var dv=i.getAttribute('data-default')||'';
        if(dv!==i.value){params.append(i.name,i.value);changed=true}
    });
    form.querySelectorAll('input[type="checkbox"]').forEach(function(c){
        if(c.defaultChecked!==c.checked){params.append(c.name,c.checked?1:0);changed=true}
    });
    form.querySelectorAll('input[type="text"]:not(.sr-only),input[type="number"]:not(.sr-only)').forEach(function(i){
        if(i.defaultValue!==i.value){
            params.append(i.name,i.value);
            changed=true;
            // 如果修改了频率数值，确保对应的单位也被发送（即使单位没变）
            if(i.name==='sign_cycle_num'){
                var unit=form.querySelector('[name="sign_cycle_unit"]');
                if(unit){params.append('sign_cycle_unit',unit.value)}
            }
            if(i.name==='zdfss_cycle_num'){
                var unit=form.querySelector('[name="zdfss_cycle_unit"]');
                if(unit){params.append('zdfss_cycle_unit',unit.value)}
            }
        }
    });
    form.querySelectorAll('textarea').forEach(function(t){
        if(t.defaultValue!==t.value){params.append(t.name,t.value);changed=true}
    });
    form.querySelectorAll('select').forEach(function(s){
        var dv=s.getAttribute('data-default')||s.defaultValue;
        if(dv!==s.value){
            params.append(s.name,s.value);
            changed=true;
            // 如果修改了频率单位，确保对应的数值也被发送（即使数值没变）
            if(s.name==='sign_cycle_unit'){
                var num=form.querySelector('[name="sign_cycle_num"]');
                if(num){params.append('sign_cycle_num',num.value)}
            }
            if(s.name==='zdfss_cycle_unit'){
                var num=form.querySelector('[name="zdfss_cycle_num"]');
                if(num){params.append('zdfss_cycle_num',num.value)}
            }
        }
    });

    if(!changed){saving=false;return}

    var xhr=new XMLHttpRequest();
    xhr.open('POST','ajax_qzone.php?act=save_user_config',true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.onload=function(){
        saving=false;
        try{
            var r=JSON.parse(xhr.responseText);
            if(r.code===1){
                toast('已保存','success');
                form.querySelectorAll('input[type="checkbox"]').forEach(function(c){c.defaultChecked=c.checked});
                form.querySelectorAll('input[type="text"]:not(.sr-only),input[type="number"]:not(.sr-only)').forEach(function(i){i.defaultValue=i.value});
                form.querySelectorAll('textarea').forEach(function(t){t.defaultValue=t.value});
                form.querySelectorAll('input[type="hidden"]:not([name="qid"])').forEach(function(i){i.setAttribute('data-default',i.value)});
                form.querySelectorAll('select').forEach(function(s){s.setAttribute('data-default',s.value)});
            }else toast(r.msg||'保存失败','error');
        }catch(e){toast('保存失败','error')}
    };
    xhr.onerror=function(){saving=false;toast('保存失败','error')};
    xhr.send(params);
}

document.addEventListener('DOMContentLoaded',function(){
    var form=$('config_form');if(!form)return;
    syncZdfssDeletePrevState();
    form.querySelectorAll('input,select,textarea').forEach(function(el){
        if(el.type==='checkbox')el.onchange=function(){updateToggle(this);if(this.name==='zdfss_switch')syncZdfssDeletePrevState();autoSave()};
        else{el.oninput=autoSave;el.onchange=autoSave}
    });
});
</script>

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