<?php
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'");
    }
    echo '<div class="alert alert-success" style="background: rgba(16,185,129,0.1); border: 1px solid #10b981; border-radius: 12px; padding: 12px 16px; margin-bottom: 20px; color: #10b981;">
            ✅ 快捷登录配置已保存
          </div>';
}

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

<?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' : ''; ?>">
                📊 控制台
            </a>
            <?php if ($is_super_admin): ?>
            <a href="?tab=packages" class="admin-sidebar-item <?php echo $active_tab == 'packages' ? 'active' : ''; ?>">
                🎁 套餐管理
            </a>
            <a href="?tab=coupons" class="admin-sidebar-item <?php echo $active_tab == 'coupons' ? 'active' : ''; ?>">
                🎟️ 优惠码管理
            </a>
            <a href="?tab=announcement" class="admin-sidebar-item <?php echo $active_tab == 'announcement' ? 'active' : ''; ?>">
    📢 平台公告
</a>
<a href="?tab=quick_login" class="admin-sidebar-item <?php echo $active_tab == 'quick_login' ? 'active' : ''; ?>">
    🔐 登录配置
</a>
            <a href="?tab=mail" class="admin-sidebar-item <?php echo $active_tab == 'mail' ? 'active' : ''; ?>">
                📧 邮件配置
            </a>
            <a href="?tab=email_template" class="admin-sidebar-item <?php echo $active_tab == 'email_template' ? 'active' : ''; ?>">📧 邮件模板
            </a>
            <a href="?tab=withdraw" class="admin-sidebar-item <?php echo $active_tab == 'withdraw' ? 'active' : ''; ?>">
    💰 提现审核
</a>
            <a href="?tab=users" class="admin-sidebar-item <?php echo $active_tab == 'users' ? 'active' : ''; ?>">
                👥 用户管理
            </a>
            <a href="?tab=cron" class="admin-sidebar-item <?php echo $active_tab == 'cron' ? 'active' : ''; ?>">
    ⏰ 定时任务
</a>
            <?php endif; ?>
            <a href="?tab=records" class="admin-sidebar-item <?php echo $active_tab == 'records' ? 'active' : ''; ?>">
                📋 加密记录
            </a>
            <a href="?tab=services" class="admin-sidebar-item <?php echo $active_tab == 'services' ? 'active' : ''; ?>">
                🔧 服务记录
            </a>
        </div>
        
        <div class="admin-content">
            <?php if ($message): ?>
                <div class="alert alert-success">✅ <?php echo $message; ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert alert-error">❌ <?php echo $error; ?></div>
            <?php endif; ?>
            
            <!-- 控制台 -->
            <?php if ($active_tab == 'dashboard'): ?>
                <div class="admin-stats">
                    <div class="stat-card">
                        <div class="stat-icon">👥</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">✅</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">🔒</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">💰</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">🎁 管理套餐</a>
                        <a href="?tab=coupons" class="quick-card">🎟️ 添加优惠码</a>
                        <a href="?tab=mail" class="quick-card">📧 邮件配置</a>
                        <a href="?tab=users" class="quick-card">👥 管理用户</a>
                        <a href="/encrypt/encrypt.php" class="quick-card">🔒 加密工具</a>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 套餐管理 -->
            <?php if ($active_tab == 'packages' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>🎁 套餐管理</h2>
                    
                    <form method="POST" class="admin-form">
                        <input type="hidden" name="action" value="add_package">
                        <h3>添加新套餐</h3>
                        <div class="form-grid">
                            <input type="text" name="name" placeholder="套餐名称" required>
                            <input type="number" name="days" placeholder="有效天数（留空为永久）" step="1">
                            <input type="number" name="price" placeholder="价格" step="0.01" required>
                            <input type="number" name="sort_order" placeholder="排序" value="0">
                            <button type="submit" class="btn btn-primary">➕ 添加套餐</button>
                        </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">保存</button>
                                        <a href="?delete_package=<?php echo $p['id']; ?>&tab=packages" class="btn btn-sm btn-danger" onclick="return confirm('确定删除？')">删除</a>
                                    </td>
                                </tr>
                            </form>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            
            <!-- 优惠码管理 -->
            <?php if ($active_tab == 'coupons' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>🎟️ 优惠码管理</h2>
                    
                    <form method="POST" class="admin-form">
                        <input type="hidden" name="action" value="add_coupon">
                        <h3>添加优惠码</h3>
                        <div class="form-grid">
                            <input type="text" name="code" placeholder="优惠码 (如: SUMMER50)" required>
                            <input type="text" name="name" placeholder="名称 (如: 夏季特惠)">
                            <select name="type">
                                <option value="fixed">固定金额</option>
                                <option value="percent">百分比 (%)</option>
                            </select>
                            <input type="number" name="value" placeholder="优惠金额/百分比" step="0.01" required>
                            <input type="number" name="min_amount" placeholder="最低消费" step="0.01" value="0">
                            <input type="number" name="usage_limit" placeholder="可使用次数" value="1">
                            <select name="expire_days">
                                <option value="7">7天过期</option>
                                <option value="30">30天过期</option>
                                <option value="90">90天过期</option>
                                <option value="0">永不过期</option>
                            </select>
                            <button type="submit" class="btn btn-primary">➕ 添加优惠码</button>
                        </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('确定删除？')">删除</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            <!-- 平台公告设置 -->
<?php if ($active_tab == 'announcement' && $is_super_admin): ?>
<div class="admin-section">
    <h2>📢 加密平台公告</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" style="background: rgba(16,185,129,0.1); border: 1px solid #10b981; border-radius: 12px; padding: 12px 16px; margin-bottom: 20px; color: #10b981;">
                ✅ 公告保存成功
              </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;">🔔 启用公告显示</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);">
                💡 提示：支持HTML代码，留空则不显示公告。例如：&lt;strong&gt;重要通知&lt;/strong&gt; 系统升级维护中
            </small>
        </div>
        
        <div style="display: flex; gap: 15px; flex-wrap: wrap;">
            <button type="submit" name="save_announcement" class="btn btn-primary">💾 保存公告</button>
            <button type="button" class="btn btn-secondary" onclick="previewAnnouncement()">👁️ 预览效果</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>

<script>
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();
});
</script>
<?php endif; ?>
<?php if ($active_tab == 'quick_login' && $is_super_admin): ?>
<div class="admin-section">
    <h2>🔐 快捷登录管理</h2>
    <p style="color: var(--text-secondary); margin-bottom: 20px;">统一管理第三方快捷登录方式，支持QQ、微信、支付宝、Gitee等17种登录方式</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] : ($info['enabled'] ?? 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">💾 保存配置</button>
        </div>
    </form>
    
    <div style="margin-top: 30px; padding: 15px; background: var(--bg-secondary); border-radius: 12px;">
        <h4>📋 使用说明</h4>
        <ul style="color: var(--text-secondary); font-size: 13px; margin-left: 20px;">
            <li>开启后，登录页面会自动显示对应的快捷登录按钮</li>
            <li>QQ、微信、支付宝、Gitee 默认开启，其他默认关闭</li>
            <li>需要先在彩虹聚合登录后台配置对应的登录方式</li>
            <li>建议只开启用户常用的几种登录方式，避免界面拥挤</li>
        </ul>
    </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);
}
</style>
<?php endif; ?>

            <!-- 邮件配置 -->
            <?php if ($active_tab == 'mail' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>📧 邮件配置</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;">💾 保存配置</button>
                    </form>
                    
                    <form method="POST" class="admin-form" style="margin-top: 20px;">
                        <input type="hidden" name="action" value="test_mail">
                        <h3>📨 发送测试邮件</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">发送测试邮件</button>
                        </div>
                    </form>
                    
                    <div style="margin-top: 20px; padding: 15px; background: var(--bg-secondary); border-radius: 12px;">
                        <h4>📖 常见邮箱SMTP配置</h4>
                        <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
                            <thead>
                                <tr style="background: var(--bg-tertiary);">
                                    <th style="padding: 8px; text-align: left;">邮箱类型</th>
                                    <th style="padding: 8px; text-align: left;">SMTP服务器</th>
                                    <th style="padding: 8px; text-align: left;">端口</th>
                                    <th style="padding: 8px; text-align: left;">说明</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr><td style="padding: 6px; border-bottom: 1px solid var(--border);">QQ邮箱</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">smtp.qq.com</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">465</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">需要生成授权码</td></tr>
                                <tr><td style="padding: 6px; border-bottom: 1px solid var(--border);">163邮箱</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">smtp.163.com</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">465</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">需要开启客户端授权</td></tr>
                                <tr><td style="padding: 6px; border-bottom: 1px solid var(--border);">腾讯企业邮</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">smtp.exmail.qq.com</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">465</td><td style="padding: 6px; border-bottom: 1px solid var(--border);">使用企业邮箱密码</td></tr>
                                <tr><td style="padding: 6px;">阿里企业邮</td><td style="padding: 6px;">smtp.mxhichina.com</td><td style="padding: 6px;">465</td><td style="padding: 6px;">使用企业邮箱密码</td></tr>
                            </tbody>
                        </table>
                        <div style="margin-top: 15px; padding: 10px; background: rgba(245,158,11,0.1); border-radius: 8px;">
                            <strong>💡 温馨提示：</strong> QQ邮箱需要登录网页版 → 设置 → 账户 → 开启POP3/SMTP服务 → 获取授权码，将授权码填入"授权码/密码"字段。
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            <!-- 邮件模板管理 -->
<?php if ($active_tab == 'email_template' && $is_super_admin): ?>
<div class="admin-section">
    <h2>📧 邮件模板管理</h2>
    <p style="color: var(--text-secondary); margin-bottom: 20px;">自定义邮件通知内容，支持HTML和变量替换</p>
    
    <?php
    // 确保邮件模板表存在
    $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'");
        echo '<div class="alert alert-success" style="background: rgba(16,185,129,0.1); border: 1px solid #10b981; border-radius: 12px; padding: 12px 16px; margin-bottom: 20px; color: #10b981;">
                ✅ 模板保存成功
              </div>';
    }
    
    // 获取所有模板
    $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'");
    ?>
    
    <!-- 模板切换标签 -->
    <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>
            <small style="color: var(--text-muted);">点击变量可插入到内容中</small>
        </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;">👁️ 预览邮件</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;">💾 保存模板</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>

<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();
    }
});
</script>
<?php endif; ?>
<?php if ($active_tab == 'withdraw' && $is_super_admin): ?>
<div class="admin-section">
    <h2>💰 提现审核</h2>
    <p style="color: var(--text-secondary); margin-bottom: 20px;">审核用户的提现申请</p>
    
    <?php
    // 处理审核
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
        $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");
                echo '<div class="alert alert-success">✅ 提现申请已通过</div>';
            }
        } elseif ($status == 2) {
            // 拒绝审核
            $db->query("UPDATE withdraw_records SET status = 2, processed_at = NOW(), remark = '$remark' WHERE id = $withdraw_id");
            echo '<div class="alert alert-warning">⏸ 提现申请已拒绝</div>';
        }
    }
    
    // 获取提现列表（修复 status 歧义）
    $status_filter = isset($_GET['status']) ? intval($_GET['status']) : 0;
    if ($status_filter >= 0) {
        $status_sql = "AND w.status = $status_filter";
    } else {
        $status_sql = "";
    }
    
    $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
    ");
    
    $status_map = [
        0 => '<span class="badge-warning">⏳ 待审核</span>',
        1 => '<span class="badge-success">✅ 已通过</span>',
        2 => '<span class="badge-error">❌ 已拒绝</span>'
    ];
    ?>
    
    <!-- 筛选 -->
    <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'; ?>">待审核</a>
        <a href="?tab=withdraw&status=1" class="btn btn-sm <?php echo $status_filter == 1 ? 'btn-primary' : 'btn-secondary'; ?>">已通过</a>
        <a href="?tab=withdraw&status=2" class="btn btn-sm <?php echo $status_filter == 2 ? 'btn-primary' : 'btn-secondary'; ?>">已拒绝</a>
        <a href="?tab=withdraw&status=-1" class="btn btn-sm <?php echo $status_filter == -1 ? 'btn-primary' : 'btn-secondary'; ?>">全部</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 echo $status_map[$w['status']]; ?></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']); ?>">✅ 通过</button>
                            <button class="action-btn reject-btn" data-id="<?php echo $w['id']; ?>" data-user="<?php echo htmlspecialchars($w['username']); ?>">❌ 拒绝</button>
                        <?php else: ?>
                            <span style="color: var(--text-muted);">已处理</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($withdraws)): ?>
                <tr>
                    <td colspan="8" style="text-align: center;">暂无提现记录</td>
                </tr>
                <?php endif; ?>
            </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="1">
            <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>

<style>
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.action-btn {
    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;
}
.badge-warning {
    background: rgba(245,158,11,0.1);
    color: #f59e0b;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
}
.badge-success {
    background: rgba(16,185,129,0.1);
    color: #10b981;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
}
.badge-error {
    background: rgba(239,68,68,0.1);
    color: #ef4444;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
}
</style>

<script>
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').innerText = isApprove ? '确认通过' : '确认拒绝';
    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();
    }
});
</script>
<?php endif; ?>  
            <!-- 用户管理 -->
            <?php if ($active_tab == 'users' && $is_super_admin): ?>
                <div class="admin-section">
                    <h2>👥 用户管理</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">搜索</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']); ?>')">管理服务</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">授予服务</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">修改余额</button>
                        </form>
                    </div>
                </div>
                
                <style>
                .modal {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.5);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 1000;
                }
                .modal-content {
                    background: var(--bg-primary);
                    border-radius: 16px;
                    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);
                }
                </style>
                
                <script>
                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();
                    }
                }
                </script>
            <?php endif; ?>
            
            <!-- 定时任务管理 -->
<?php if ($active_tab == 'cron' && $is_super_admin): ?>
<div class="admin-section">
    <h2>⏰ 定时任务管理</h2>
    <p style="color: var(--text-secondary); margin-bottom: 20px;">管理订单超时自动取消等定时任务</p>
    
    <?php
    // 手动执行取消过期订单（不使用 shell_exec）
    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" style="background: rgba(16,185,129,0.1); border: 1px solid #10b981; border-radius: 12px; padding: 12px 16px; margin-bottom: 20px; color: #10b981;">
                ✅ 已执行过期订单取消任务<br>
                <pre style="margin-top: 10px; font-size: 12px; white-space: pre-wrap;">' . htmlspecialchars($output) . '</pre>
              </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>📦 订单超时自动取消</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('确定立即执行吗？')">▶ 立即执行</a>
            <button class="btn btn-secondary" onclick="refreshStats()">🔄 刷新统计</button>
        </div>
        <div class="cron-tip">
            <p>💡 提示：宝塔计划任务已配置，每5分钟自动执行</p>
            <code style="display: block; background: var(--bg-secondary); padding: 10px; border-radius: 8px; margin-top: 8px; font-size: 12px;">
                */5 * * * * php /www/wwwroot/auth.lhwks.cn/cron/cancel_expired_orders.php >> /www/wwwroot/auth.lhwks.cn/storage/logs/cron.log 2>&1
            </code>
        </div>
    </div>
</div>

<style>
.cron-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 24px;
    border: 1px solid var(--border-color);
}
.cron-card h3 {
    margin-bottom: 8px;
}
.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;
}
.cron-tip {
    margin-top: 15px;
    padding: 15px;
    background: var(--bg-secondary);
    border-radius: 12px;
    font-size: 13px;
}
</style>

<script>
function refreshStats() {
    fetch('/api/order_stats.php')
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // 使用正确的元素ID
                const pendingEl = document.getElementById('pending_count');
                const expiredEl = document.getElementById('expired_count');
                const cancelledEl = document.getElementById('today_cancelled');
                
                if (pendingEl) pendingEl.innerText = data.pending_count;
                if (expiredEl) expiredEl.innerText = data.expired_count;
                if (cancelledEl) cancelledEl.innerText = data.today_cancelled;
                
                console.log('统计已更新:', data);
            } else {
                console.error('获取统计失败:', data.message);
            }
        })
        .catch(err => {
            console.error('请求错误:', err);
            // 显示默认值
            document.getElementById('pending_count').innerText = '0';
            document.getElementById('expired_count').innerText = '0';
            document.getElementById('today_cancelled').innerText = '0';
        });
}

// 页面加载时获取数据
refreshStats();
</script>
<?php endif; ?>
            <!-- 加密记录 -->
            <?php if ($active_tab == 'records'): ?>
                <div class="admin-section">
                    <h2>📋 最近加密记录</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>🔧 服务购买记录</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>
.admin-wrapper {
    display: flex;
    gap: 30px;
    min-height: 500px;
}

.admin-sidebar {
    width: 200px;
    flex-shrink: 0;
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 16px;
    border: 1px solid var(--border-color);
}

.admin-sidebar-item {
    display: block;
    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;
}

.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-icon {
    font-size: 40px;
}

.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: block;
    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 {
    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: 8px 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-sm {
    padding: 4px 12px;
    font-size: 12px;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border: none;
    padding: 8px 20px;
    border-radius: 8px;
    cursor: pointer;
}

.btn-secondary {
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    color: var(--text-primary);
    padding: 8px 20px;
    border-radius: 8px;
    cursor: pointer;
}

.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;
}

.alert {
    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;
}

@media (max-width: 768px) {
    .admin-wrapper {
        flex-direction: column;
    }
    .admin-sidebar {
        width: 100%;
    }
    .admin-sidebar-item {
        display: inline-block;
        margin-right: 8px;
    }
}
</style>
<?php include 'footer.php'; ?>