<?php
ob_start();
require_once 'config.php';
requireEncryptLogin();

$user = getEncryptUser();

// 检查管理员权限（role=admin 或 is_agent=1）
if ($user['role'] !== 'admin' && $user['is_agent'] != 1) {
    header('Location: /encrypt/index.php');
    exit;
}

$is_super_admin = ($user['role'] == 'admin');
$active_tab = $_GET['tab'] ?? 'dashboard';
$message = '';
$error = '';

// ========== 处理优惠码添加 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_coupon' && $is_super_admin) {
    $code = strtoupper(trim($_POST['code']));
    $name = trim($_POST['name']);
    $type = $_POST['type'];
    $value = floatval($_POST['value']);
    $min_amount = floatval($_POST['min_amount']);
    $usage_limit = intval($_POST['usage_limit']);
    $expire_days = intval($_POST['expire_days']);
    
    $expire_date = $expire_days > 0 ? date('Y-m-d H:i:s', strtotime("+$expire_days days")) : 'NULL';
    
    $check = $db->fetchOne("SELECT id FROM encrypt_coupons WHERE code = '$code'");
    if ($check) {
        $error = '优惠码已存在';
    } else {
        $db->query("INSERT INTO encrypt_coupons (code, name, type, value, min_amount, usage_limit, expire_date) 
                    VALUES ('$code', '$name', '$type', $value, $min_amount, $usage_limit, " . ($expire_date === 'NULL' ? 'NULL' : "'$expire_date'") . ")");
        $message = '优惠码添加成功';
    }
}

// ========== 处理优惠码删除 ==========
if (isset($_GET['delete_coupon']) && $is_super_admin) {
    $id = intval($_GET['delete_coupon']);
    $db->query("DELETE FROM encrypt_coupons WHERE id = $id");
    $message = '优惠码已删除';
    header('Location: /encrypt/admin.php?tab=coupons');
    exit;
}

// ========== 处理优惠码启用/禁用 ==========
if (isset($_GET['toggle_coupon']) && $is_super_admin) {
    $id = intval($_GET['toggle_coupon']);
    $status = intval($_GET['status']);
    $db->query("UPDATE encrypt_coupons SET status = $status WHERE id = $id");
    $message = '状态已更新';
    header('Location: /encrypt/admin.php?tab=coupons');
    exit;
}

// ========== 处理套餐价格修改 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_package' && $is_super_admin) {
    $id = intval($_POST['package_id']);
    $price = floatval($_POST['price']);
    $name = trim($_POST['name']);
    $days = $_POST['days'] === '' ? 'NULL' : intval($_POST['days']);
    
    $db->query("UPDATE encrypt_packages SET name = '$name', price = $price, days = $days WHERE id = $id");
    $message = '套餐已更新';
}

// ========== 处理套餐添加 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_package' && $is_super_admin) {
    $name = trim($_POST['name']);
    $days = $_POST['days'] === '' ? 'NULL' : intval($_POST['days']);
    $price = floatval($_POST['price']);
    $sort_order = intval($_POST['sort_order']);
    
    $db->query("INSERT INTO encrypt_packages (name, days, price, sort_order) VALUES ('$name', $days, $price, $sort_order)");
    $message = '套餐添加成功';
}

// ========== 处理套餐删除 ==========
if (isset($_GET['delete_package']) && $is_super_admin) {
    $id = intval($_GET['delete_package']);
    $db->query("DELETE FROM encrypt_packages WHERE id = $id");
    $message = '套餐已删除';
    header('Location: /encrypt/admin.php?tab=packages');
    exit;
}

// ========== 处理用户服务授予 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'grant_service' && $is_super_admin) {
    $target_user_id = intval($_POST['user_id']);
    $package_id = intval($_POST['package_id']);
    $package = getPackageById($package_id);
    
    if ($package) {
        $expire_date = null;
        if (!is_null($package['days'])) {
            $expire_date = date('Y-m-d H:i:s', strtotime("+{$package['days']} days"));
        }
        
        $target_user = $db->fetchOne("SELECT id, username FROM users WHERE id = $target_user_id");
        if (!$target_user) {
            $error = '用户不存在';
        } else {
            $exist = $db->fetchOne("SELECT id FROM encrypt_services WHERE user_id = $target_user_id AND service_name = 'php_encrypt'");
            if ($exist) {
                if (is_null($expire_date)) {
                    $db->query("UPDATE encrypt_services SET expire_date = NULL, status = 1 WHERE user_id = $target_user_id AND service_name = 'php_encrypt'");
                } else {
                    $db->query("UPDATE encrypt_services SET expire_date = '$expire_date', status = 1 WHERE user_id = $target_user_id AND service_name = 'php_encrypt'");
                }
                $message = "已为用户 {$target_user['username']} 更新服务";
            } else {
                if (is_null($expire_date)) {
                    $db->query("INSERT INTO encrypt_services (user_id, service_name, status, expire_date) VALUES ($target_user_id, 'php_encrypt', 1, NULL)");
                } else {
                    $db->query("INSERT INTO encrypt_services (user_id, service_name, status, expire_date) VALUES ($target_user_id, 'php_encrypt', 1, '$expire_date')");
                }
                $message = "已为用户 {$target_user['username']} 授予服务";
            }
        }
    }
}

// ========== 处理用户余额修改 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_balance' && $is_super_admin) {
    $target_user_id = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']);
    $remark = trim($_POST['remark']);
    
    $target_user = $db->fetchOne("SELECT id, username FROM users WHERE id = $target_user_id");
    if (!$target_user) {
        $error = '用户不存在';
    } else {
        updateUserBalance($target_user_id, $amount, "管理员操作: $remark");
        $message = "已为用户 {$target_user['username']} " . ($amount >= 0 ? "增加" : "扣除") . " ¥" . number_format(abs($amount), 2);
    }
}

// ========== 处理邮件配置保存 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_mail_config' && $is_super_admin) {
    updateSiteConfig('smtp_host', trim($_POST['smtp_host']));
    updateSiteConfig('smtp_port', intval($_POST['smtp_port']));
    updateSiteConfig('smtp_user', trim($_POST['smtp_user']));
    updateSiteConfig('smtp_pass', trim($_POST['smtp_pass']));
    updateSiteConfig('smtp_from', trim($_POST['smtp_from']));
    updateSiteConfig('smtp_name', trim($_POST['smtp_name']));
    $message = '邮件配置已保存';
}

// ========== 处理测试邮件发送 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test_mail' && $is_super_admin) {
    $test_email = trim($_POST['test_email']);
    if (empty($test_email)) {
        $error = '请输入测试邮箱';
    } else {
        $subject = '邮件测试 - ' . ENCRYPT_SITE_NAME;
        $content = '
        <html>
        <head><style>
            body { font-family: Arial, sans-serif; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
            .content { background: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
            .footer { background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 10px 10px; }
        </style></head>
        <body>
        <div class="container">
            <div class="header"><h2>📧 邮件测试</h2></div>
            <div class="content">
                <p>您好！</p>
                <p>这是一封来自 <strong>' . ENCRYPT_SITE_NAME . '</strong> 的测试邮件。</p>
                <p>如果您收到此邮件，说明邮件配置正确，可以正常发送通知了。</p>
                <p>发送时间：' . date('Y-m-d H:i:s') . '</p>
            </div>
            <div class="footer"><p>此邮件由系统自动发送，请勿回复</p></div>
        </div>
        </body>
        </html>';
        
        if (sendMail($test_email, $subject, $content)) {
            $message = "测试邮件已发送至 {$test_email}，请查收";
        } else {
            $error = "测试邮件发送失败，请检查SMTP配置";
        }
    }
}

// 获取统计数据
$total_users = $db->fetchOne("SELECT COUNT(*) as count FROM users")['count'];
$total_services = $db->fetchOne("SELECT COUNT(*) as count FROM encrypt_services WHERE status = 1")['count'];
$total_encrypts = $db->fetchOne("SELECT COUNT(*) as count FROM encrypt_history")['count'];
$total_revenue = $db->fetchOne("SELECT SUM(discount_amount) as total FROM encrypt_coupon_usage")['total'] ?? 0;

// 获取最近加密记录
$recent_encrypts = $db->fetchAll("
    SELECT h.*, u.username 
    FROM encrypt_history h 
    LEFT JOIN users u ON h.user_id = u.id 
    ORDER BY h.id DESC LIMIT 10
");

// 获取最近购买记录
$recent_services = $db->fetchAll("
    SELECT s.*, u.username 
    FROM encrypt_services s 
    LEFT JOIN users u ON s.user_id = u.id 
    ORDER BY s.id DESC LIMIT 10
");

// 获取所有套餐
$packages = getEncryptPackages();

// 获取所有优惠码
$coupons = $db->fetchAll("SELECT * FROM encrypt_coupons ORDER BY id DESC");

// 获取邮件配置
$mail_config = getMailConfig();

// 搜索用户
$search_user = '';
$search_result = null;
if (isset($_GET['search_user']) && $is_super_admin) {
    $search_user = trim($_GET['search_user']);
    if ($search_user) {
        $search_result = $db->fetchAll("SELECT id, username, email, balance, role, is_agent, status FROM users WHERE username LIKE '%$search_user%' OR email LIKE '%$search_user%' LIMIT 20");
    }
}

$quick_login_types = [
    'qq' => ['name' => 'QQ登录', 'icon' => 'qq', 'color' => '#12B7F5'],
    'wx' => ['name' => '微信登录', 'icon' => 'wechat', 'color' => '#07C160'],
    'alipay' => ['name' => '支付宝登录', 'icon' => 'alipay', 'color' => '#1677FF'],
    'gitee' => ['name' => 'Gitee登录', 'icon' => 'gitee', 'color' => '#C71D23'],
    'sina' => ['name' => '微博登录', 'icon' => 'weibo', 'color' => '#FF8200'],
    'baidu' => ['name' => '百度登录', 'icon' => 'baidu', 'color' => '#2932E1'],
    'xiaomi' => ['name' => '小米登录', 'icon' => 'xiaomi', 'color' => '#FF6900'],
    'huawei' => ['name' => '华为登录', 'icon' => 'huawei', 'color' => '#FF0000'],
    'douyin' => ['name' => '抖音登录', 'icon' => 'douyin', 'color' => '#000000'],
    'google' => ['name' => '谷歌登录', 'icon' => 'google', 'color' => '#4285F4'],
    'microsoft' => ['name' => '微软登录', 'icon' => 'microsoft', 'color' => '#00A4EF'],
    'facebook' => ['name' => 'Facebook登录', 'icon' => 'facebook', 'color' => '#1877F2'],
    'twitter' => ['name' => 'Twitter登录', 'icon' => 'twitter', 'color' => '#1DA1F2'],
    'feishu' => ['name' => '飞书登录', 'icon' => 'feishu', 'color' => '#00C4A0'],
    'wework' => ['name' => '企业微信登录', 'icon' => 'wework', 'color' => '#2C7A3E'],
    'dingtalk' => ['name' => '钉钉登录', 'icon' => 'dingtalk', 'color' => '#1E9AEF'],
    'github' => ['name' => 'GitHub登录', 'icon' => 'github', 'color' => '#24292E'],
];

// 处理保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_config'])) {
    foreach ($quick_login_types as $type => $info) {
        $enabled = isset($_POST['enabled_' . $type]) ? 1 : 0;
        $db->query("UPDATE quick_login_config SET enabled = $enabled WHERE type = '$type'");
    }
    $message = '快捷登录配置已保存';
}

// 获取当前配置
$configs = [];
$result = $db->query("SELECT type, enabled FROM quick_login_config");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $configs[$row['type']] = $row['enabled'];
    }
}

// 确保邮件模板表存在
$db->query("CREATE TABLE IF NOT EXISTS `email_templates` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `type` VARCHAR(50) NOT NULL UNIQUE,
    `name` VARCHAR(100) NOT NULL,
    `subject` VARCHAR(255) NOT NULL,
    `content` TEXT NOT NULL,
    `variables` TEXT,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// 插入默认模板
$check = $db->fetchOne("SELECT id FROM email_templates LIMIT 1");
if (!$check) {
    $db->query("INSERT INTO `email_templates` (`type`, `name`, `subject`, `content`, `variables`) VALUES
    ('recharge', '充值成功通知', '【{site_name}】充值成功通知', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #10b981, #059669); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">✅ 充值成功</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您的账户已成功充值：</p><div style=\"text-align: center; margin: 30px 0;\"><span style=\"font-size: 36px; font-weight: bold; color: #10b981;\">¥{amount}</span></div><p>订单号：{order_no}</p><p>当前余额：<strong>¥{balance}</strong></p><hr style=\"margin: 30px 0;\"><p style=\"color: #9ca3af; font-size: 12px;\">此邮件由系统自动发送，请勿回复。</p></div></div></body></html>', '{site_name}, {username}, {amount}, {order_no}, {balance}'),
    ('card_recharge', '卡密充值成功通知', '【{site_name}】卡密充值成功通知', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #f59e0b, #ef4444); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">🎫 卡密充值成功</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您已通过卡密成功充值：</p><div style=\"text-align: center; margin: 30px 0;\"><span style=\"font-size: 36px; font-weight: bold; color: #f59e0b;\">¥{amount}</span></div><p>卡密：{card_code}</p><p>当前余额：<strong>¥{balance}</strong></p><hr style=\"margin: 30px 0;\"><p style=\"color: #9ca3af; font-size: 12px;\">此邮件由系统自动发送，请勿回复。</p></div></div></body></html>', '{site_name}, {username}, {amount}, {card_code}, {balance}'),
    ('login_alert', '登录提醒', '【{site_name}】登录提醒', '<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body style=\"font-family: Arial, sans-serif; padding: 20px;\"><div style=\"max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;\"><div style=\"background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;\"><h2 style=\"color: white; margin: 0;\">🔐 登录提醒</h2></div><div style=\"padding: 30px;\"><p>尊敬的 {username}，您好！</p><p>您的账号刚刚登录：</p><div style=\"margin: 20px 0; padding: 15px; background: #f3f4f6; border-radius: 12px;\"><p>📅 登录时间：{login_time}</p><p>📍 登录位置：{city}</p><p>📱 设备信息：{device}</p><p>🌐 IP地址：{ip}</p></div><p>如果这是您本人操作，请忽略此邮件。</p><p style=\"color: #ef4444;\">⚠️ 如果不是您本人操作，请立即修改密码。</p></div></div></body></html>', '{site_name}, {username}, {login_time}, {city}, {device}, {ip}')");
}

// 处理邮件模板保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_template'])) {
    $type = $_POST['type'];
    $subject = addslashes($_POST['subject']);
    $content = addslashes($_POST['content']);
    $db->query("UPDATE email_templates SET subject = '$subject', content = '$content' WHERE type = '$type'");
    $message = '模板保存成功';
}

// 获取所有模板
$templates = $db->fetchAll("SELECT * FROM email_templates ORDER BY id");
$current_type = $_GET['template_type'] ?? ($templates[0]['type'] ?? 'recharge');
$current = $db->fetchOne("SELECT * FROM email_templates WHERE type = '$current_type'");

// 处理提现审核
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'audit_withdraw') {
    $withdraw_id = intval($_POST['withdraw_id']);
    $status = intval($_POST['status']);
    $remark = trim($_POST['remark'] ?? '');
    
    if ($status == 1) {
        $withdraw = $db->fetchOne("SELECT * FROM withdraw_records WHERE id = $withdraw_id AND status = 0");
        if ($withdraw) {
            $db->query("UPDATE users SET rebate_balance = rebate_balance - {$withdraw['amount']} WHERE id = {$withdraw['user_id']}");
            $db->query("UPDATE withdraw_records SET status = 1, processed_at = NOW(), remark = '$remark' WHERE id = $withdraw_id");
            $message = '提现申请已通过';
        }
    } elseif ($status == 2) {
        $db->query("UPDATE withdraw_records SET status = 2, processed_at = NOW(), remark = '$remark' WHERE id = $withdraw_id");
        $message = '提现申请已拒绝';
    }
}

// 获取提现列表
$status_filter = isset($_GET['status']) ? intval($_GET['status']) : 0;
$status_sql = $status_filter >= 0 ? "AND w.status = $status_filter" : "";
$withdraws = $db->fetchAll("
    SELECT w.*, u.username, u.email 
    FROM withdraw_records w
    LEFT JOIN users u ON w.user_id = u.id
    WHERE 1=1 $status_sql
    ORDER BY w.id DESC LIMIT 50
");
?>

<?php include 'header.php'; ?>
<div class="encrypt-container">
    <div class="admin-wrapper">
        <div class="admin-sidebar">
            <a href="?tab=dashboard" class="admin-sidebar-item <?php echo $active_tab == 'dashboard' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:view-dashboard.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                控制台
            </a>
            <?php if ($is_super_admin): ?>
            <a href="?tab=packages" class="admin-sidebar-item <?php echo $active_tab == 'packages' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:package-variant.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                套餐管理
            </a>
            <a href="?tab=coupons" class="admin-sidebar-item <?php echo $active_tab == 'coupons' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:ticket-percent.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                优惠码管理
            </a>
            <a href="?tab=announcement" class="admin-sidebar-item <?php echo $active_tab == 'announcement' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:bullhorn.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                平台公告
            </a>
            <a href="?tab=quick_login" class="admin-sidebar-item <?php echo $active_tab == 'quick_login' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:login.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                登录配置
            </a>
            <a href="?tab=mail" class="admin-sidebar-item <?php echo $active_tab == 'mail' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:email.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                邮件配置
            </a>
            <a href="?tab=email_template" class="admin-sidebar-item <?php echo $active_tab == 'email_template' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:email-edit.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                邮件模板
            </a>
            <a href="?tab=withdraw" class="admin-sidebar-item <?php echo $active_tab == 'withdraw' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:cash-check.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                提现审核
            </a>
            <a href="?tab=users" class="admin-sidebar-item <?php echo $active_tab == 'users' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:account-group.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                用户管理
            </a>
            <a href="?tab=cron" class="admin-sidebar-item <?php echo $active_tab == 'cron' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                定时任务
            </a>
            <?php endif; ?>
            <a href="?tab=records" class="admin-sidebar-item <?php echo $active_tab == 'records' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:history.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                加密记录
            </a>
            <a href="?tab=services" class="admin-sidebar-item <?php echo $active_tab == 'services' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:cog.svg?color=currentColor" width="18" height="18" style="margin-right: 8px;" alt="">
                服务记录
            </a>
        </div>
        
        <div class="admin-content">
            <?php if ($message): ?>
                <div class="alert alert-success">
                    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" style="margin-right: 8px;" alt="">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert alert-error">
                    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <!-- 控制台 -->
            <?php if ($active_tab == 'dashboard'): ?>
                <div class="admin-stats">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="36" height="36" alt="">
                        </div>
                        <div class="stat-info">
                            <div class="stat-value"><?php echo $total_users; ?></div>
                            <div class="stat-label">总用户数</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="36" height="36" alt="">
                        </div>
                        <div class="stat-info">
                            <div class="stat-value"><?php echo $total_services; ?></div>
                            <div class="stat-label">激活服务</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <img src="https://api.iconify.design/mdi:shield-lock.svg?color=%23f59e0b" width="36" height="36" alt="">
                        </div>
                        <div class="stat-info">
                            <div class="stat-value"><?php echo $total_encrypts; ?></div>
                            <div class="stat-label">加密次数</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="36" height="36" alt="">
                        </div>
                        <div class="stat-info">
                            <div class="stat-value">¥<?php echo number_format($total_revenue, 2); ?></div>
                            <div class="stat-label">优惠总额</div>
                        </div>
                    </div>
                </div>
                
                <div class="admin-quick-links">
                    <h3>快速操作</h3>
                    <div class="quick-grid">
                        <a href="?tab=packages" class="quick-card">
                            <img src="https://api.iconify.design/mdi:package-variant.svg?color=currentColor" width="20" height="20" style="margin-right: 6px;" alt="">
                            管理套餐
                        </a>
                        <a href="?tab=coupons" class="quick-card">
                            <img src="https://api.iconify.design/mdi:ticket-percent.svg?color=currentColor" width="20" height="20" style="margin-right: 6px;" alt="">
                            添加优惠码
                        </a>
                        <a href="?tab=mail" class="quick-card">
                            <img src="https://api.iconify.design/mdi:email.svg?color=currentColor" width="20" height="20" style="margin-right: 6px;" alt="">
                            邮件配置
                        </a>
                        <a href="?tab=users" class="quick-card">
                            <img src="https://api.iconify.design/mdi:account-group.svg?color=currentColor" width="20" height="20" style="margin-right: 6px;" alt="">
                            管理用户
                        </a>
                        <a href="/encrypt/encrypt.php" class="quick-card">
                            <img src="https://api.iconify.design/mdi:shield-lock.svg?color=currentColor" width="20" height="20" style="margin-right: 6px;" alt="">
                            加密工具
                        </a>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 套餐管理 -->
            <?php if ($active_tab == 'packages' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        套餐管理
                    </h2>
                    
                    <form method="POST" class="admin-form">
                        <input type="hidden" name="action" value="add_package">
                        <h3>添加新套餐</h3>
                        <div class="form-grid">
                            <div>
                                <label>套餐名称</label>
                                <input type="text" name="name" placeholder="套餐名称" required>
                            </div>
                            <div>
                                <label>有效天数</label>
                                <input type="number" name="days" placeholder="留空为永久" step="1">
                            </div>
                            <div>
                                <label>价格</label>
                                <input type="number" name="price" placeholder="价格" step="0.01" required>
                            </div>
                            <div>
                                <label>排序</label>
                                <input type="number" name="sort_order" placeholder="排序" value="0">
                            </div>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                                    添加套餐
                                </button>
                            </div>
                        </div>
                    </form>
                    
                    <table class="admin-table">
                        <thead>
                            <tr><th>ID</th><th>套餐名称</th><th>有效天数</th><th>价格</th><th>排序</th><th>操作</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($packages as $p): ?>
                            <form method="POST" style="display: contents;">
                                <input type="hidden" name="action" value="update_package">
                                <input type="hidden" name="package_id" value="<?php echo $p['id']; ?>">
                                <tr>
                                    <td><?php echo $p['id']; ?></td>
                                    <td><input type="text" name="name" value="<?php echo htmlspecialchars($p['name']); ?>" style="width: 100px;"></td>
                                    <td><input type="number" name="days" value="<?php echo $p['days']; ?>" style="width: 80px;" placeholder="永久"></td>
                                    <td><input type="number" name="price" value="<?php echo $p['price']; ?>" step="0.01" style="width: 80px;"></td>
                                    <td><input type="number" name="sort_order" value="<?php echo $p['sort_order']; ?>" style="width: 60px;"></td>
                                    <td>
                                        <button type="submit" class="btn btn-sm btn-primary">
                                            <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="14" height="14" alt="">
                                        </button>
                                        <a href="?delete_package=<?php echo $p['id']; ?>&tab=packages" class="btn btn-sm btn-danger" onclick="return confirm('确定删除？')">
                                            <img src="https://api.iconify.design/mdi:delete.svg?color=white" width="14" height="14" alt="">
                                        </a>
                                    </td>
                                </tr>
                            </form>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            
            <!-- 优惠码管理 -->
            <?php if ($active_tab == 'coupons' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:ticket-percent.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        优惠码管理
                    </h2>
                    
                    <form method="POST" class="admin-form">
                        <input type="hidden" name="action" value="add_coupon">
                        <h3>添加优惠码</h3>
                        <div class="form-grid">
                            <div>
                                <label>优惠码</label>
                                <input type="text" name="code" placeholder="如: SUMMER50" required>
                            </div>
                            <div>
                                <label>名称</label>
                                <input type="text" name="name" placeholder="如: 夏季特惠">
                            </div>
                            <div>
                                <label>类型</label>
                                <select name="type">
                                    <option value="fixed">固定金额</option>
                                    <option value="percent">百分比 (%)</option>
                                </select>
                            </div>
                            <div>
                                <label>优惠值</label>
                                <input type="number" name="value" placeholder="优惠金额/百分比" step="0.01" required>
                            </div>
                            <div>
                                <label>最低消费</label>
                                <input type="number" name="min_amount" placeholder="最低消费" step="0.01" value="0">
                            </div>
                            <div>
                                <label>可使用次数</label>
                                <input type="number" name="usage_limit" placeholder="可使用次数" value="1">
                            </div>
                            <div>
                                <label>有效期</label>
                                <select name="expire_days">
                                    <option value="7">7天过期</option>
                                    <option value="30">30天过期</option>
                                    <option value="90">90天过期</option>
                                    <option value="0">永不过期</option>
                                </select>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                                    添加优惠码
                                </button>
                            </div>
                        </div>
                    </form>
                    
                    <table class="admin-table">
                        <thead>
                            <tr><th>ID</th><th>优惠码</th><th>名称</th><th>类型</th><th>优惠值</th><th>最低消费</th><th>已用/总次数</th><th>过期时间</th><th>状态</th><th>操作</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($coupons as $c): ?>
                            <tr>
                                <td><?php echo $c['id']; ?></td>
                                <td><strong><?php echo $c['code']; ?></strong></td>
                                <td><?php echo $c['name']; ?></td>
                                <td><?php echo $c['type'] == 'fixed' ? '固定金额' : '百分比'; ?></td>
                                <td><?php echo $c['type'] == 'fixed' ? '¥'.$c['value'] : $c['value'].'%'; ?></td>
                                <td><?php echo $c['min_amount'] > 0 ? '¥'.$c['min_amount'] : '无'; ?></td>
                                <td><?php echo $c['used_count']; ?>/<?php echo $c['usage_limit'] ?: '∞'; ?></td>
                                <td><?php echo $c['expire_date'] ? date('Y-m-d', strtotime($c['expire_date'])) : '永久'; ?></td>
                                <td>
                                    <?php if ($c['status']): ?>
                                        <a href="?toggle_coupon=<?php echo $c['id']; ?>&status=0&tab=coupons" class="badge-success">启用</a>
                                    <?php else: ?>
                                        <a href="?toggle_coupon=<?php echo $c['id']; ?>&status=1&tab=coupons" class="badge-error">禁用</a>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="?delete_coupon=<?php echo $c['id']; ?>&tab=coupons" class="btn btn-sm btn-danger" onclick="return confirm('确定删除？')">
                                        <img src="https://api.iconify.design/mdi:delete.svg?color=white" width="14" height="14" alt="">
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            
            <!-- 平台公告设置 -->
            <?php if ($active_tab == 'announcement' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        加密平台公告
                    </h2>
                    <p style="color: var(--text-secondary); margin-bottom: 20px;">设置在加密工具首页顶部显示的公告内容</p>
                    
                    <?php
                    $current_announcement = getSiteConfig('encrypt_announcement') ?? '';
                    $announcement_enabled = getSiteConfig('encrypt_announcement_enabled') == '1';
                    
                    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_announcement'])) {
                        $announcement = trim($_POST['announcement']);
                        $enabled = isset($_POST['enabled']) ? 1 : 0;
                        updateSiteConfig('encrypt_announcement', $announcement);
                        updateSiteConfig('encrypt_announcement_enabled', $enabled);
                        echo '<div class="alert alert-success"><img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="18" height="18" style="margin-right: 6px;" alt="">公告保存成功</div>';
                        $current_announcement = $announcement;
                        $announcement_enabled = $enabled;
                    }
                    ?>
                    
                    <form method="POST" class="admin-form">
                        <div style="margin-bottom: 20px; padding: 15px; background: var(--bg-secondary); border-radius: 12px;">
                            <label style="display: flex; align-items: center; gap: 12px; cursor: pointer;">
                                <input type="checkbox" name="enabled" value="1" <?php echo $announcement_enabled ? 'checked' : ''; ?> style="width: 18px; height: 18px; cursor: pointer;">
                                <span style="font-weight: 600;">
                                    <img src="https://api.iconify.design/mdi:bell.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                                    启用公告显示
                                </span>
                                <span style="font-size: 12px; color: var(--text-muted);">关闭后前台将不显示公告</span>
                            </label>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">公告内容</label>
                            <textarea name="announcement" rows="5" style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary); font-size: 14px;" placeholder="输入公告内容，支持HTML代码" <?php echo !$announcement_enabled ? 'disabled style="background: var(--bg-tertiary); opacity: 0.6;"' : ''; ?>><?php echo htmlspecialchars($current_announcement); ?></textarea>
                            <small style="display: block; margin-top: 8px; color: var(--text-muted);">
                                <img src="https://api.iconify.design/mdi:lightbulb.svg?color=%23f59e0b" width="14" height="14" style="margin-right: 4px;" alt="">
                                提示：支持HTML代码，留空则不显示公告。
                            </small>
                        </div>
                        
                        <div style="display: flex; gap: 15px; flex-wrap: wrap;">
                            <button type="submit" name="save_announcement" class="btn btn-primary">
                                <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                                保存公告
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="previewAnnouncement()">
                                <img src="https://api.iconify.design/mdi:eye.svg?color=currentColor" width="18" height="18" style="margin-right: 6px;" alt="">
                                预览效果
                            </button>
                        </div>
                    </form>
                    
                    <div style="margin-top: 30px;">
                        <h4 style="margin-bottom: 15px;">预览效果</h4>
                        <div id="previewArea" style="background: linear-gradient(135deg, #fef3c7, #fde68a); padding: 20px; border-radius: 16px; border-left: 5px solid #f59e0b; color: #92400e;">
                            <?php if (!$announcement_enabled): ?>
                                <span style="color: #9ca3af;">🔕 公告已关闭，前台不显示</span>
                            <?php elseif (empty($current_announcement)): ?>
                                <span style="color: #9ca3af;">暂无公告内容</span>
                            <?php else: ?>
                                <?php echo $current_announcement; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 快捷登录配置 -->
            <?php if ($active_tab == 'quick_login' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:login.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        快捷登录管理
                    </h2>
                    <p style="color: var(--text-secondary); margin-bottom: 20px;">统一管理第三方快捷登录方式</p>
                    
                    <form method="POST" class="quick-login-form">
                        <div class="quick-login-grid">
                            <?php foreach ($quick_login_types as $type => $info): 
                                $enabled = isset($configs[$type]) ? $configs[$type] : 0;
                            ?>
                                <div class="quick-login-item">
                                    <label class="quick-login-switch">
                                        <input type="checkbox" name="enabled_<?php echo $type; ?>" value="1" <?php echo $enabled ? 'checked' : ''; ?>>
                                        <span class="switch-slider"></span>
                                    </label>
                                    <div class="quick-login-info">
                                        <div class="quick-login-icon" style="background: <?php echo $info['color']; ?>;">
                                            <img src="/assets/svg/<?php echo $info['icon']; ?>.svg" alt="<?php echo $info['name']; ?>" style="width: 24px; height: 24px;">
                                        </div>
                                        <span class="quick-login-name"><?php echo $info['name']; ?></span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <div style="margin-top: 30px; text-align: center;">
                            <button type="submit" name="save_config" class="btn btn-primary">
                                <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                                保存配置
                            </button>
                        </div>
                    </form>
                </div>
            <?php endif; ?>

            <!-- 邮件配置 -->
            <?php if ($active_tab == 'mail' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:email.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        邮件配置
                    </h2>
                    <p style="color: var(--text-secondary); margin-bottom: 20px;">配置SMTP服务，用于发送购买确认、到期提醒等邮件</p>
                    
                    <form method="POST" class="admin-form">
                        <input type="hidden" name="action" value="save_mail_config">
                        <h3>SMTP 服务器设置</h3>
                        <div class="form-grid">
                            <div>
                                <label>SMTP服务器</label>
                                <input type="text" name="smtp_host" value="<?php echo htmlspecialchars($mail_config['host']); ?>" placeholder="smtp.qq.com" required>
                                <small>例如：smtp.qq.com</small>
                            </div>
                            <div>
                                <label>SMTP端口</label>
                                <input type="number" name="smtp_port" value="<?php echo $mail_config['port']; ?>" placeholder="465" required>
                                <small>通常使用 465</small>
                            </div>
                            <div>
                                <label>发件邮箱</label>
                                <input type="email" name="smtp_user" value="<?php echo htmlspecialchars($mail_config['user']); ?>" placeholder="your@email.com" required>
                                <small>完整的邮箱地址</small>
                            </div>
                            <div>
                                <label>授权码 / 密码</label>
                                <input type="password" name="smtp_pass" value="<?php echo htmlspecialchars($mail_config['pass']); ?>" placeholder="邮箱授权码" required>
                                <small>不是登录密码，是SMTP授权码</small>
                            </div>
                            <div>
                                <label>发件人地址（可选）</label>
                                <input type="email" name="smtp_from" value="<?php echo htmlspecialchars($mail_config['from']); ?>" placeholder="留空则使用发件邮箱">
                            </div>
                            <div>
                                <label>发件人名称</label>
                                <input type="text" name="smtp_name" value="<?php echo htmlspecialchars($mail_config['name']); ?>" placeholder="PHP加密工具">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary" style="margin-top: 15px;">
                            <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                            保存配置
                        </button>
                    </form>
                    
                    <form method="POST" class="admin-form" style="margin-top: 20px;">
                        <input type="hidden" name="action" value="test_mail">
                        <h3>
                            <img src="https://api.iconify.design/mdi:email-send.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                            发送测试邮件
                        </h3>
                        <div style="display: flex; gap: 10px; margin-top: 15px;">
                            <input type="email" name="test_email" placeholder="接收测试邮件的邮箱" class="form-control" required style="flex: 1;">
                            <button type="submit" class="btn btn-secondary">
                                <img src="https://api.iconify.design/mdi:send.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                                发送测试
                            </button>
                        </div>
                    </form>
                </div>
            <?php endif; ?>
            
            <!-- 邮件模板管理 -->
            <?php if ($active_tab == 'email_template' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:email-edit.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        邮件模板管理
                    </h2>
                    
                    <div class="template-tabs" style="display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 25px; border-bottom: 1px solid var(--border-color); padding-bottom: 15px;">
                        <?php foreach ($templates as $tpl): ?>
                            <a href="?tab=email_template&template_type=<?php echo $tpl['type']; ?>" 
                               class="template-tab" style="padding: 8px 20px; background: var(--bg-secondary); border-radius: 20px; text-decoration: none; color: var(--text-primary); font-size: 13px; <?php echo $current_type == $tpl['type'] ? 'background: linear-gradient(135deg, #667eea, #764ba2); color: white;' : ''; ?>">
                                <?php echo htmlspecialchars($tpl['name']); ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                    
                    <form method="POST" class="template-form" style="background: var(--bg-primary); border-radius: 16px; padding: 25px; border: 1px solid var(--border-color);">
                        <input type="hidden" name="type" value="<?php echo $current['type']; ?>">
                        <input type="hidden" name="save_template" value="1">
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">模板名称</label>
                            <input type="text" value="<?php echo htmlspecialchars($current['name']); ?>" disabled style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-secondary);">
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">邮件主题</label>
                            <input type="text" name="subject" value="<?php echo htmlspecialchars($current['subject']); ?>" style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary);" required>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">邮件内容 (HTML)</label>
                            <textarea name="content" rows="12" id="emailContent" style="width: 100%; padding: 12px; border-radius: 12px; border: 1px solid var(--border-color); background: var(--bg-primary); font-family: monospace; resize: vertical;"><?php echo htmlspecialchars($current['content']); ?></textarea>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">可用变量</label>
                            <div style="background: var(--bg-secondary); padding: 12px; border-radius: 12px; margin-bottom: 8px;">
                                <?php 
                                $vars = explode(',', $current['variables']);
                                foreach ($vars as $var):
                                    $var = trim($var);
                                ?>
                                    <code style="display: inline-block; background: rgba(102,126,234,0.1); color: #667eea; padding: 4px 10px; border-radius: 20px; font-size: 12px; margin: 3px; cursor: pointer;" onclick="insertVariable('{<?php echo $var; ?>}')">{<?php echo $var; ?>}</code>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <button type="button" class="btn btn-secondary" id="previewBtn" style="padding: 10px 24px; border-radius: 10px; cursor: pointer; background: var(--bg-secondary); border: 1px solid var(--border-color); margin-right: 10px;">
                                <img src="https://api.iconify.design/mdi:eye.svg?color=currentColor" width="16" height="16" style="margin-right: 6px;" alt="">
                                预览邮件
                            </button>
                            <button type="submit" class="btn btn-primary" style="padding: 10px 24px; border-radius: 10px; cursor: pointer; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none;">
                                <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="16" height="16" style="margin-right: 6px;" alt="">
                                保存模板
                            </button>
                        </div>
                    </form>
                    
                    <div id="previewModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: var(--bg-primary); border-radius: 20px; max-width: 600px; width: 90%; max-height: 80vh; overflow: auto;">
                            <div style="padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center;">
                                <h3 style="margin: 0;">邮件预览</h3>
                                <button onclick="closePreview()" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
                            </div>
                            <div style="padding: 20px;" id="previewContent"></div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 提现审核 -->
            <?php if ($active_tab == 'withdraw' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:cash-check.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        提现审核
                    </h2>
                    
                    <div class="filter-bar" style="margin-bottom: 20px;">
                        <a href="?tab=withdraw&status=0" class="btn btn-sm <?php echo $status_filter == 0 ? 'btn-primary' : 'btn-secondary'; ?>">
                            <img src="https://api.iconify.design/mdi:timer-sand.svg?color=currentColor" width="14" height="14" style="margin-right: 4px;" alt="">
                            待审核
                        </a>
                        <a href="?tab=withdraw&status=1" class="btn btn-sm <?php echo $status_filter == 1 ? 'btn-primary' : 'btn-secondary'; ?>">
                            <img src="https://api.iconify.design/mdi:check-circle.svg?color=currentColor" width="14" height="14" style="margin-right: 4px;" alt="">
                            已通过
                        </a>
                        <a href="?tab=withdraw&status=2" class="btn btn-sm <?php echo $status_filter == 2 ? 'btn-primary' : 'btn-secondary'; ?>">
                            <img src="https://api.iconify.design/mdi:close-circle.svg?color=currentColor" width="14" height="14" style="margin-right: 4px;" alt="">
                            已拒绝
                        </a>
                        <a href="?tab=withdraw&status=-1" class="btn btn-sm <?php echo $status_filter == -1 ? 'btn-primary' : 'btn-secondary'; ?>">
                            <img src="https://api.iconify.design/mdi:format-list-bulleted.svg?color=currentColor" width="14" height="14" style="margin-right: 4px;" alt="">
                            全部
                        </a>
                    </div>
                    
                    <div class="table-container">
                        <table class="admin-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户</th>
                                    <th>邮箱</th>
                                    <th>提现金额</th>
                                    <th>申请时间</th>
                                    <th>状态</th>
                                    <th>备注</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($withdraws as $w): ?>
                                <tr id="withdraw-row-<?php echo $w['id']; ?>">
                                    <td><?php echo $w['id']; ?></td>
                                    <td><?php echo htmlspecialchars($w['username']); ?></td>
                                    <td><?php echo htmlspecialchars($w['email']); ?></td>
                                    <td><strong style="color: #f59e0b;">¥<?php echo number_format($w['amount'], 2); ?></strong></td>
                                    <td><?php echo $w['created_at']; ?></td>
                                    <td>
                                        <?php if ($w['status'] == 0): ?>
                                            <span class="badge-warning">⏳ 待审核</span>
                                        <?php elseif ($w['status'] == 1): ?>
                                            <span class="badge-success">✅ 已通过</span>
                                        <?php else: ?>
                                            <span class="badge-error">❌ 已拒绝</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($w['remark'] ?: '-'); ?></td>
                                    <td class="action-buttons">
                                        <?php if ($w['status'] == 0): ?>
                                            <button class="action-btn approve-btn" data-id="<?php echo $w['id']; ?>" data-amount="<?php echo $w['amount']; ?>" data-user="<?php echo htmlspecialchars($w['username']); ?>">
                                                <img src="https://api.iconify.design/mdi:check.svg?color=%2310b981" width="16" height="16" alt="">
                                                通过
                                            </button>
                                            <button class="action-btn reject-btn" data-id="<?php echo $w['id']; ?>" data-user="<?php echo htmlspecialchars($w['username']); ?>">
                                                <img src="https://api.iconify.design/mdi:close.svg?color=%23ef4444" width="16" height="16" alt="">
                                                拒绝
                                            </button>
                                        <?php else: ?>
                                            <span style="color: var(--text-muted);">已处理</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div id="auditModal" class="modal" style="display: none;">
                    <div class="modal-content" style="max-width: 400px;">
                        <div class="modal-header">
                            <h3 id="modalTitle">审核提现</h3>
                            <span class="close" onclick="closeAuditModal()">&times;</span>
                        </div>
                        <form method="POST" id="auditForm">
                            <input type="hidden" name="withdraw_id" id="audit_id">
                            <input type="hidden" name="action" value="audit_withdraw">
                            <input type="hidden" name="status" id="audit_status">
                            <div class="modal-body">
                                <p id="audit_info"></p>
                                <div class="form-group">
                                    <label>备注（可选）</label>
                                    <textarea name="remark" id="audit_remark" rows="3" style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid var(--border-color);" placeholder="填写备注信息..."></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" onclick="closeAuditModal()">取消</button>
                                <button type="submit" class="btn btn-primary" id="submitBtn">确认</button>
                            </div>
                        </form>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 用户管理 -->
            <?php if ($active_tab == 'users' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        用户管理
                    </h2>
                    
                    <form method="GET" class="admin-search">
                        <input type="hidden" name="tab" value="users">
                        <input type="text" name="search_user" placeholder="搜索用户名或邮箱" value="<?php echo htmlspecialchars($search_user); ?>">
                        <button type="submit" class="btn btn-primary">
                            <img src="https://api.iconify.design/mdi:magnify.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                            搜索
                        </button>
                    </form>
                    
                    <?php if ($search_result !== null): ?>
                        <h3>搜索结果</h3>
                        <table class="admin-table">
                            <thead>
                                <tr><th>ID</th><th>用户名</th><th>邮箱</th><th>余额</th><th>角色</th><th>状态</th><th>操作</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($search_result as $u): ?>
                                <tr>
                                    <td><?php echo $u['id']; ?></td>
                                    <td><?php echo htmlspecialchars($u['username']); ?></td>
                                    <td><?php echo htmlspecialchars($u['email']); ?></td>
                                    <td>¥<?php echo number_format($u['balance'], 2); ?></td>
                                    <td>
                                        <?php if ($u['role'] == 'admin'): ?>管理员
                                        <?php elseif ($u['is_agent'] == 1): ?>代理商
                                        <?php else: ?>普通用户
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $u['status'] ? '正常' : '禁用'; ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="showUserModal(<?php echo $u['id']; ?>, '<?php echo htmlspecialchars($u['username']); ?>')">
                                            <img src="https://api.iconify.design/mdi:cog.svg?color=white" width="14" height="14" style="margin-right: 4px;" alt="">
                                            管理
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
                
                <div id="userModal" class="modal" style="display: none;">
                    <div class="modal-content">
                        <span class="modal-close" onclick="closeModal()">&times;</span>
                        <h3 id="modalTitle">管理用户服务</h3>
                        <form method="POST">
                            <input type="hidden" name="action" value="grant_service" id="grant_user_id">
                            <div class="form-group">
                                <label>选择套餐</label>
                                <select name="package_id" class="form-control" required>
                                    <option value="">请选择套餐</option>
                                    <?php foreach ($packages as $p): ?>
                                        <option value="<?php echo $p['id']; ?>">
                                            <?php echo $p['name']; ?> - ¥<?php echo $p['price']; ?>
                                            (<?php echo $p['days'] ? $p['days'].'天' : '永久'; ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <img src="https://api.iconify.design/mdi:gift.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                                授予服务
                            </button>
                        </form>
                        <hr>
                        <form method="POST">
                            <input type="hidden" name="action" value="update_balance" id="balance_user_id">
                            <div class="form-group">
                                <label>修改余额</label>
                                <div style="display: flex; gap: 10px;">
                                    <input type="number" name="amount" step="0.01" placeholder="金额（正数增加，负数扣除）" class="form-control" required>
                                    <input type="text" name="remark" placeholder="备注" class="form-control">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <img src="https://api.iconify.design/mdi:cash.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                                修改余额
                            </button>
                        </form>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 定时任务管理 -->
            <?php if ($active_tab == 'cron' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        定时任务管理
                    </h2>
                    
                    <?php
                    if (isset($_GET['run_cancel_orders'])) {
                        ob_start();
                        include '/www/wwwroot/auth.lhwks.cn/cron/cancel_expired_orders.php';
                        $output = ob_get_clean();
                        echo '<div class="alert alert-success"><img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="18" height="18" style="margin-right: 6px;" alt="">已执行过期订单取消任务</div>';
                    }
                    
                    $stats = [];
                    $stats_content = @file_get_contents(SITE_URL . 'api/order_stats.php');
                    if ($stats_content) $stats = json_decode($stats_content, true);
                    ?>
                    
                    <div class="cron-card">
                        <h3>
                            <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="20" height="20" style="margin-right: 6px;" alt="">
                            订单超时自动取消
                        </h3>
                        <p>自动取消超过30分钟未支付的订单</p>
                        <div class="cron-info">
                            <div class="cron-stat">
                                <span class="stat-label">待支付订单</span>
                                <span class="stat-number" id="pending_count"><?php echo $stats['pending_count'] ?? '-'; ?></span>
                            </div>
                            <div class="cron-stat">
                                <span class="stat-label">已过期订单</span>
                                <span class="stat-number" id="expired_count"><?php echo $stats['expired_count'] ?? '-'; ?></span>
                            </div>
                            <div class="cron-stat">
                                <span class="stat-label">今日取消</span>
                                <span class="stat-number" id="today_cancelled"><?php echo $stats['today_cancelled'] ?? '-'; ?></span>
                            </div>
                        </div>
                        <div class="cron-actions">
                            <a href="?tab=cron&run_cancel_orders=1" class="btn btn-primary" onclick="return confirm('确定立即执行吗？')">
                                <img src="https://api.iconify.design/mdi:play.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                                立即执行
                            </a>
                            <button class="btn btn-secondary" onclick="refreshStats()">
                                <img src="https://api.iconify.design/mdi:refresh.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                                刷新统计
                            </button>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 加密记录 -->
            <?php if ($active_tab == 'records'): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:history.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        最近加密记录
                    </h2>
                    <table class="admin-table">
                        <thead>
                            <tr><th>ID</th><th>用户</th><th>文件名</th><th>原始大小</th><th>加密后大小</th><th>时间</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_encrypts as $r): ?>
                            <tr>
                                <td><?php echo $r['id']; ?></td>
                                <td><?php echo htmlspecialchars($r['username'] ?? '未知'); ?></td>
                                <td><?php echo htmlspecialchars($r['original_name']); ?></td>
                                <td><?php echo $r['file_size'] ? round($r['file_size']/1024,2).' KB' : '-'; ?></td>
                                <td><?php echo $r['encrypted_size'] ? round($r['encrypted_size']/1024,2).' KB' : '-'; ?></td>
                                <td><?php echo $r['created_at']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            
            <!-- 服务记录 -->
            <?php if ($active_tab == 'services'): ?>
                <div class="admin-section">
                    <h2>
                        <img src="https://api.iconify.design/mdi:cog.svg?color=%23667eea" width="22" height="22" style="margin-right: 8px;" alt="">
                        服务购买记录
                    </h2>
                    <table class="admin-table">
                        <thead>
                            <tr><th>ID</th><th>用户</th><th>状态</th><th>过期时间</th><th>创建时间</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_services as $s): ?>
                            <tr>
                                <td><?php echo $s['id']; ?></td>
                                <td><?php echo htmlspecialchars($s['username'] ?? '未知'); ?></td>
                                <td><?php echo $s['status'] ? '✅ 激活' : '❌ 禁用'; ?></td>
                                <td><?php echo $s['expire_date'] ?: '永久'; ?></td>
                                <td><?php echo $s['created_at']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.quick-login-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}
.quick-login-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 12px 15px;
    background: var(--bg-secondary);
    border-radius: 12px;
    border: 1px solid var(--border-color);
    transition: all 0.2s;
}
.quick-login-item:hover {
    border-color: var(--primary-color);
    transform: translateY(-2px);
}
.quick-login-info {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
}
.quick-login-icon {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.quick-login-name {
    font-weight: 500;
    color: var(--text-primary);
}
.quick-login-switch {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 26px;
    flex-shrink: 0;
}
.quick-login-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}
.switch-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.3s;
    border-radius: 34px;
}
.switch-slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.3s;
    border-radius: 50%;
}
.quick-login-switch input:checked + .switch-slider {
    background-color: #667eea;
}
.quick-login-switch input:checked + .switch-slider:before {
    transform: translateX(24px);
}

.cron-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 24px;
    border: 1px solid var(--border-color);
}
.cron-card h3 {
    margin-bottom: 8px;
    display: flex;
    align-items: center;
}
.cron-info {
    display: flex;
    gap: 40px;
    margin: 20px 0;
    flex-wrap: wrap;
}
.cron-stat {
    text-align: center;
}
.cron-stat .stat-label {
    display: block;
    font-size: 13px;
    color: var(--text-muted);
}
.cron-stat .stat-number {
    display: block;
    font-size: 28px;
    font-weight: 700;
    color: var(--primary-color);
}
.cron-actions {
    display: flex;
    gap: 10px;
    margin: 15px 0;
}

.admin-wrapper {
    display: flex;
    gap: 30px;
    min-height: 500px;
}
.admin-sidebar {
    width: 220px;
    flex-shrink: 0;
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 16px;
    border: 1px solid var(--border-color);
}
.admin-sidebar-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    color: var(--text-primary);
    text-decoration: none;
    border-radius: 10px;
    margin-bottom: 4px;
    transition: all 0.2s;
}
.admin-sidebar-item:hover,
.admin-sidebar-item.active {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}
.admin-content {
    flex: 1;
    min-width: 0;
}
.admin-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    border: 1px solid var(--border-color);
}
.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #667eea;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
}
.admin-quick-links {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 20px;
    border: 1px solid var(--border-color);
}
.quick-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-top: 15px;
}
.quick-card {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px;
    background: var(--bg-secondary);
    border-radius: 12px;
    text-align: center;
    text-decoration: none;
    color: var(--text-primary);
    transition: all 0.2s;
}
.quick-card:hover {
    transform: translateY(-2px);
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}
.admin-section {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 20px;
    border: 1px solid var(--border-color);
}
.admin-section h2 {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}
.admin-form {
    background: var(--bg-secondary);
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 30px;
}
.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-top: 15px;
}
.form-grid input,
.form-grid select {
    padding: 10px 12px;
    border-radius: 8px;
    border: 1px solid var(--border-color);
    background: var(--bg-primary);
    color: var(--text-primary);
    width: 100%;
}
.form-grid label {
    display: block;
    margin-bottom: 5px;
    font-size: 13px;
    font-weight: 500;
}
.form-grid small {
    font-size: 11px;
    color: var(--text-muted);
}
.admin-table {
    width: 100%;
    border-collapse: collapse;
}
.admin-table th,
.admin-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid var(--border-color);
}
.admin-table th {
    background: var(--bg-secondary);
    font-weight: 600;
}
.admin-table input {
    width: 100%;
    padding: 6px;
    border-radius: 6px;
    border: 1px solid var(--border-color);
    background: var(--bg-primary);
    color: var(--text-primary);
}
.admin-search {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}
.admin-search input {
    flex: 1;
    padding: 10px;
    border-radius: 8px;
    border: 1px solid var(--border-color);
    background: var(--bg-primary);
    color: var(--text-primary);
}
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    padding: 8px 16px;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    border: 1px solid transparent;
}
.btn-sm {
    padding: 4px 12px;
    font-size: 12px;
}
.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border: none;
}
.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    color: var(--text-primary);
}
.btn-danger {
    background: #ef4444;
    color: white;
}
.badge-success {
    background: #10b981;
    color: white;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
    text-decoration: none;
}
.badge-error {
    background: #ef4444;
    color: white;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
    text-decoration: none;
}
.badge-warning {
    background: rgba(245,158,11,0.1);
    color: #f59e0b;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
}
.alert {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-radius: 12px;
    margin-bottom: 20px;
}
.alert-success {
    background: rgba(16,185,129,0.1);
    border: 1px solid #10b981;
    color: #10b981;
}
.alert-error {
    background: rgba(239,68,68,0.1);
    border: 1px solid #ef4444;
    color: #ef4444;
}
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: none;
    border: 1px solid var(--border-color);
    padding: 4px 12px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
}
.approve-btn:hover {
    background: #10b981;
    border-color: #10b981;
    color: white;
}
.reject-btn:hover {
    background: #ef4444;
    border-color: #ef4444;
    color: white;
}
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 24px;
    max-width: 500px;
    width: 90%;
    position: relative;
}
.modal-close {
    position: absolute;
    top: 15px;
    right: 20px;
    font-size: 24px;
    cursor: pointer;
}
.form-group {
    margin-bottom: 15px;
}
.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
}
.form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--bg-primary);
    color: var(--text-primary);
}

@media (max-width: 768px) {
    .admin-wrapper {
        flex-direction: column;
    }
    .admin-sidebar {
        width: 100%;
    }
    .admin-sidebar-item {
        display: inline-flex;
        margin-right: 8px;
    }
    .form-grid {
        grid-template-columns: 1fr;
    }
    .quick-grid {
        grid-template-columns: 1fr 1fr;
    }
}
</style>

<script>
function insertVariable(varText) {
    const textarea = document.getElementById('emailContent');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    const newText = text.substring(0, start) + varText + text.substring(end);
    textarea.value = newText;
    textarea.focus();
    textarea.selectionStart = start + varText.length;
    textarea.selectionEnd = start + varText.length;
}

function closePreview() {
    document.getElementById('previewModal').style.display = 'none';
}

document.getElementById('previewBtn')?.addEventListener('click', function() {
    const subject = document.querySelector('input[name="subject"]').value;
    const content = document.getElementById('emailContent').value;
    const modal = document.getElementById('previewModal');
    const previewContent = document.getElementById('previewContent');
    previewContent.innerHTML = `
        <div style="background: #f0f0f0; padding: 10px; border-radius: 8px; margin-bottom: 15px;">
            <strong>主题：</strong> ${escapeHtml(subject)}
        </div>
        <div style="border: 1px solid #ddd; border-radius: 8px; padding: 15px;">
            ${content}
        </div>
        <div style="margin-top: 15px; font-size: 12px; color: #999; text-align: center;">
            ⚠️ 预览仅供参考，实际发送时会替换变量
        </div>
    `;
    modal.style.display = 'flex';
});

function escapeHtml(text) {
    return text.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

document.getElementById('previewModal')?.addEventListener('click', function(e) {
    if (e.target === this) closePreview();
});

function previewAnnouncement() {
    const enabled = document.querySelector('input[name="enabled"]').checked;
    const content = document.querySelector('textarea[name="announcement"]').value;
    const previewArea = document.getElementById('previewArea');
    if (!enabled) {
        previewArea.innerHTML = '<span style="color: #9ca3af;">🔕 公告已关闭，前台不显示</span>';
    } else if (content.trim() === '') {
        previewArea.innerHTML = '<span style="color: #9ca3af;">暂无公告内容</span>';
    } else {
        previewArea.innerHTML = content;
    }
}

document.querySelector('input[name="enabled"]')?.addEventListener('change', function() {
    const textarea = document.querySelector('textarea[name="announcement"]');
    if (this.checked) {
        textarea.disabled = false;
        textarea.style.background = 'var(--bg-primary)';
        textarea.style.opacity = '1';
    } else {
        textarea.disabled = true;
        textarea.style.background = 'var(--bg-tertiary)';
        textarea.style.opacity = '0.6';
    }
    previewAnnouncement();
});

let currentWithdraw = null;
function openAuditModal(id, username, amount, isApprove) {
    document.getElementById('audit_id').value = id;
    document.getElementById('audit_status').value = isApprove ? 1 : 2;
    document.getElementById('audit_info').innerHTML = isApprove 
        ? `确认通过 <strong>${username}</strong> 的提现申请？<br>提现金额：<strong style="color: #f59e0b;">¥${parseFloat(amount).toFixed(2)}</strong>`
        : `确认拒绝 <strong>${username}</strong> 的提现申请？`;
    document.getElementById('modalTitle').innerText = isApprove ? '通过提现' : '拒绝提现';
    document.getElementById('submitBtn').innerHTML = isApprove 
        ? '<img src="https://api.iconify.design/mdi:check.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">确认通过'
        : '<img src="https://api.iconify.design/mdi:close.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">确认拒绝';
    document.getElementById('audit_remark').value = '';
    document.getElementById('auditModal').style.display = 'flex';
}

function closeAuditModal() {
    document.getElementById('auditModal').style.display = 'none';
}

document.querySelectorAll('.approve-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        const amount = this.dataset.amount;
        const username = this.dataset.user;
        openAuditModal(id, username, amount, true);
    });
});

document.querySelectorAll('.reject-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        const username = this.dataset.user;
        openAuditModal(id, username, 0, false);
    });
});

document.getElementById('auditModal')?.addEventListener('click', function(e) {
    if (e.target === this) closeAuditModal();
});

function showUserModal(userId, username) {
    document.getElementById('modalTitle').innerText = '管理用户: ' + username;
    document.getElementById('grant_user_id').value = userId;
    document.getElementById('balance_user_id').value = userId;
    document.getElementById('userModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('userModal').style.display = 'none';
}

window.onclick = function(e) {
    const modal = document.getElementById('userModal');
    if (e.target === modal) closeModal();
}

function refreshStats() {
    fetch('/api/order_stats.php')
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                document.getElementById('pending_count').innerText = data.pending_count || '0';
                document.getElementById('expired_count').innerText = data.expired_count || '0';
                document.getElementById('today_cancelled').innerText = data.today_cancelled || '0';
            }
        })
        .catch(err => console.error('请求错误:', err));
}

if (document.getElementById('pending_count')) refreshStats();
</script>
<?php include 'footer.php'; ?>