<?php
/**
 * 一课 后台管理 API
 * 处理所有后台的 CRUD 请求 + 图片上传 + 前端公共API
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/AdminAuth.php';

header('Content-Type: application/json; charset=utf-8');

// 管理员登录验证
$auth = new AdminAuth();

// logout 和前端公共API不需要验证登录状态
$action = trim($_POST['action'] ?? $_GET['action'] ?? '');

// 前端公共API：获取弹窗/站点配置/维护状态/团队信息/公众号配置
$publicActions = ['get_popups', 'get_site_info', 'get_maintenance', 'get_team_info', 'get_wechat_config'];

if ($action === 'logout') {
    $auth->logout();
    jsonResponse(['code' => 1, 'msg' => '已退出登录']);
}

if (!in_array($action, $publicActions) && !$auth->isLoggedIn()) {
    jsonResponse(['code' => 0, 'msg' => '未登录或登录已过期'], 401);
}

$db = getDB();

switch ($action) {
    // ====== 图片上传 ======
    case 'upload_image':
        $type = cleanInput($_POST['type'] ?? 'general');
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            jsonResponse(['code' => 0, 'msg' => '上传失败，请检查文件']);
        }
        $file = $_FILES['file'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($file['type'], $allowedTypes)) {
            jsonResponse(['code' => 0, 'msg' => '仅支持 jpg/png/gif 格式']);
        }
        if ($file['size'] > 2 * 1024 * 1024) {
            jsonResponse(['code' => 0, 'msg' => '文件大小不能超过2MB']);
        }

        $uploadDir = __DIR__ . '/../uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = $type . '_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
        $filepath = $uploadDir . $filename;

        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            $url = SITE_URL . '/uploads/' . $filename;
            jsonResponse(['code' => 1, 'msg' => '上传成功', 'data' => ['url' => $url]]);
        } else {
            jsonResponse(['code' => 0, 'msg' => '文件保存失败']);
        }
        break;

    // ====== 分类管理 ======
    case 'get_category':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("SELECT * FROM function_categories WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        if ($data) jsonResponse(['code' => 1, 'data' => $data]);
        else jsonResponse(['code' => 0, 'msg' => '分类不存在']);
        break;

    case 'create_category':
        $name = cleanInput($_POST['name'] ?? '');
        $icon = cleanInput($_POST['icon'] ?? 'fa-folder');
        $sort = (int)($_POST['sort_order'] ?? 0);
        if (empty($name)) jsonResponse(['code' => 0, 'msg' => '分类名称不能为空']);
        $stmt = $db->prepare("INSERT INTO function_categories (name, icon, sort_order) VALUES (?, ?, ?)");
        $stmt->execute([$name, $icon, $sort]);
        jsonResponse(['code' => 1, 'msg' => '分类创建成功']);
        break;

    case 'update_category':
        $id = (int)($_POST['id'] ?? 0);
        $name = cleanInput($_POST['name'] ?? '');
        $icon = cleanInput($_POST['icon'] ?? 'fa-folder');
        $sort = (int)($_POST['sort_order'] ?? 0);
        if (empty($name)) jsonResponse(['code' => 0, 'msg' => '分类名称不能为空']);
        $stmt = $db->prepare("UPDATE function_categories SET name = ?, icon = ?, sort_order = ? WHERE id = ?");
        $stmt->execute([$name, $icon, $sort, $id]);
        jsonResponse(['code' => 1, 'msg' => '分类更新成功']);
        break;

    case 'delete_category':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("DELETE FROM function_categories WHERE id = ?");
        $stmt->execute([$id]);
        jsonResponse(['code' => 1, 'msg' => '分类删除成功']);
        break;

    // ====== 菜单管理 ======
    case 'get_function':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("SELECT * FROM functions WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        if ($data) jsonResponse(['code' => 1, 'data' => $data]);
        else jsonResponse(['code' => 0, 'msg' => '菜单不存在']);
        break;

    case 'create_function':
        $catId = (int)($_POST['category_id'] ?? 0);
        $name = cleanInput($_POST['name'] ?? '');
        $icon = cleanInput($_POST['icon'] ?? 'fa-link');
        $pageUrl = cleanInput($_POST['page_url'] ?? '');
        $extUrl = cleanInput($_POST['external_url'] ?? '');
        $isExt = (int)($_POST['is_external'] ?? 0);
        $sort = (int)($_POST['sort_order'] ?? 0);
        if (empty($name) || $catId <= 0) jsonResponse(['code' => 0, 'msg' => '名称和分类不能为空']);
        $stmt = $db->prepare("INSERT INTO functions (category_id, name, icon, page_url, external_url, is_external, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$catId, $name, $icon, $pageUrl, $extUrl, $isExt, $sort]);
        jsonResponse(['code' => 1, 'msg' => '菜单创建成功']);
        break;

    case 'update_function':
        $id = (int)($_POST['id'] ?? 0);
        $catId = (int)($_POST['category_id'] ?? 0);
        $name = cleanInput($_POST['name'] ?? '');
        $icon = cleanInput($_POST['icon'] ?? 'fa-link');
        $pageUrl = cleanInput($_POST['page_url'] ?? '');
        $extUrl = cleanInput($_POST['external_url'] ?? '');
        $isExt = (int)($_POST['is_external'] ?? 0);
        $sort = (int)($_POST['sort_order'] ?? 0);
        if (empty($name) || $catId <= 0) jsonResponse(['code' => 0, 'msg' => '名称和分类不能为空']);
        $stmt = $db->prepare("UPDATE functions SET category_id=?, name=?, icon=?, page_url=?, external_url=?, is_external=?, sort_order=? WHERE id=?");
        $stmt->execute([$catId, $name, $icon, $pageUrl, $extUrl, $isExt, $sort, $id]);
        jsonResponse(['code' => 1, 'msg' => '菜单更新成功']);
        break;

    case 'delete_function':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("DELETE FROM functions WHERE id = ?");
        $stmt->execute([$id]);
        jsonResponse(['code' => 1, 'msg' => '菜单删除成功']);
        break;

    // ====== 课节管理 ======
    case 'get_section':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("SELECT * FROM course_sections WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        if ($data) jsonResponse(['code' => 1, 'data' => $data]);
        else jsonResponse(['code' => 0, 'msg' => '课节不存在']);
        break;

    case 'create_section':
        $num = (int)($_POST['section_number'] ?? 0);
        $name = cleanInput($_POST['section_name'] ?? '');
        $start = cleanInput($_POST['start_time'] ?? '');
        $end = cleanInput($_POST['end_time'] ?? '');
        if ($num <= 0) jsonResponse(['code' => 0, 'msg' => '课节序号必须大于0']);
        if (empty($start) || empty($end)) jsonResponse(['code' => 0, 'msg' => '时间不能为空']);
        $stmt = $db->prepare("INSERT INTO course_sections (section_number, section_name, start_time, end_time, sort_order) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$num, $name ?: '第' . $num . '节', $start, $end, $num]);
        jsonResponse(['code' => 1, 'msg' => '课节创建成功']);
        break;

    case 'update_section':
        $id = (int)($_POST['id'] ?? 0);
        $num = (int)($_POST['section_number'] ?? 0);
        $name = cleanInput($_POST['section_name'] ?? '');
        $start = cleanInput($_POST['start_time'] ?? '');
        $end = cleanInput($_POST['end_time'] ?? '');
        if ($num <= 0) jsonResponse(['code' => 0, 'msg' => '课节序号必须大于0']);
        if (empty($start) || empty($end)) jsonResponse(['code' => 0, 'msg' => '时间不能为空']);
        $stmt = $db->prepare("UPDATE course_sections SET section_number=?, section_name=?, start_time=?, end_time=?, sort_order=? WHERE id=?");
        $stmt->execute([$num, $name ?: '第' . $num . '节', $start, $end, $num, $id]);
        jsonResponse(['code' => 1, 'msg' => '课节更新成功']);
        break;

    case 'delete_section':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("DELETE FROM course_sections WHERE id = ?");
        $stmt->execute([$id]);
        jsonResponse(['code' => 1, 'msg' => '课节删除成功']);
        break;

    // ====== 弹窗管理 ======
    case 'get_popup':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("SELECT * FROM popups WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        if ($data) jsonResponse(['code' => 1, 'data' => $data]);
        else jsonResponse(['code' => 0, 'msg' => '弹窗不存在']);
        break;

    case 'create_popup':
        $title = cleanInput($_POST['title'] ?? '');
        $content = $_POST['content'] ?? '';
        $image = cleanInput($_POST['image'] ?? '');
        $type = (int)($_POST['popup_type'] ?? 1);
        $pages = 'home'; // 弹窗只在首页展示
        $start = !empty($_POST['start_time']) ? str_replace('T', ' ', $_POST['start_time']) . ':00' : null;
        $end = !empty($_POST['end_time']) ? str_replace('T', ' ', $_POST['end_time']) . ':00' : null;
        $active = (int)($_POST['is_active'] ?? 0);
        $sort = (int)($_POST['sort_order'] ?? 0);
        if (empty($title)) jsonResponse(['code' => 0, 'msg' => '弹窗标题不能为空']);
        $stmt = $db->prepare("INSERT INTO popups (title, content, image, popup_type, show_pages, start_time, end_time, is_active, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $content, $image, $type, $pages, $start, $end, $active, $sort]);
        jsonResponse(['code' => 1, 'msg' => '弹窗创建成功']);
        break;

    case 'update_popup':
        $id = (int)($_POST['id'] ?? 0);
        $title = cleanInput($_POST['title'] ?? '');
        $content = $_POST['content'] ?? '';
        $image = cleanInput($_POST['image'] ?? '');
        $type = (int)($_POST['popup_type'] ?? 1);
        $pages = 'home'; // 弹窗只在首页展示
        $start = !empty($_POST['start_time']) ? str_replace('T', ' ', $_POST['start_time']) . ':00' : null;
        $end = !empty($_POST['end_time']) ? str_replace('T', ' ', $_POST['end_time']) . ':00' : null;
        $active = (int)($_POST['is_active'] ?? 0);
        $sort = (int)($_POST['sort_order'] ?? 0);
        if (empty($title)) jsonResponse(['code' => 0, 'msg' => '弹窗标题不能为空']);
        $stmt = $db->prepare("UPDATE popups SET title=?, content=?, image=?, popup_type=?, show_pages=?, start_time=?, end_time=?, is_active=?, sort_order=? WHERE id=?");
        $stmt->execute([$title, $content, $image, $type, $pages, $start, $end, $active, $sort, $id]);
        jsonResponse(['code' => 1, 'msg' => '弹窗更新成功']);
        break;

    case 'toggle_popup':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("SELECT is_active FROM popups WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetch();
        if (!$current) jsonResponse(['code' => 0, 'msg' => '弹窗不存在']);
        $newStatus = $current['is_active'] ? 0 : 1;
        $stmt = $db->prepare("UPDATE popups SET is_active = ? WHERE id = ?");
        $stmt->execute([$newStatus, $id]);
        jsonResponse(['code' => 1, 'msg' => $newStatus ? '弹窗已启用' : '弹窗已禁用']);
        break;

    case 'delete_popup':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("DELETE FROM popups WHERE id = ?");
        $stmt->execute([$id]);
        jsonResponse(['code' => 1, 'msg' => '弹窗删除成功']);
        break;

    // ====== 站点配置 ======
    case 'save_site_config':
        $data = $_POST;
        unset($data['action'], $data['group']);
        foreach ($data as $id => $value) {
            if (!is_numeric($id)) continue;
            $stmt = $db->prepare("UPDATE settings SET value = ? WHERE id = ?");
            $stmt->execute([$value, $id]);
        }
        jsonResponse(['code' => 1, 'msg' => '配置已保存']);
        break;

    // ====== 系统配置 ======
    case 'save_settings':
        $group = cleanInput($_POST['group'] ?? '');
        $data = $_POST;
        unset($data['action'], $data['group']);
        foreach ($data as $id => $value) {
            if (is_numeric($id)) {
                $stmt = $db->prepare("UPDATE settings SET value = ? WHERE id = ?");
                $stmt->execute([$value, $id]);
            }
        }
        jsonResponse(['code' => 1, 'msg' => '配置已保存']);
        break;

    case 'sync_config_file':
        // 从数据库读取知岁OS配置并写入 config.php
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'zsos'");
        $zsosConfig = [];
        foreach ($stmt->fetchAll() as $row) {
            $zsosConfig[$row['key_name']] = $row['value'];
        }

        $configPath = __DIR__ . '/../config.php';
        $configContent = file_get_contents($configPath);

        // 替换知岁OS配置常量
        if (isset($zsosConfig['zsos_base_url'])) {
            $configContent = preg_replace(
                "/define\('ZSOS_BASE_URL',\s*'[^']*'\)/",
                "define('ZSOS_BASE_URL', '" . addslashes($zsosConfig['zsos_base_url']) . "')",
                $configContent
            );
        }
        if (isset($zsosConfig['zsos_uuid'])) {
            $configContent = preg_replace(
                "/define\('ZSOS_UUID',\s*'[^']*'\)/",
                "define('ZSOS_UUID', '" . addslashes($zsosConfig['zsos_uuid']) . "')",
                $configContent
            );
        }
        if (isset($zsosConfig['zsos_secret_key'])) {
            $configContent = preg_replace(
                "/define\('ZSOS_SECRET_KEY',\s*'[^']*'\)/",
                "define('ZSOS_SECRET_KEY', '" . addslashes($zsosConfig['zsos_secret_key']) . "')",
                $configContent
            );
        }

        // 替换站点配置
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'site'");
        foreach ($stmt->fetchAll() as $row) {
            if ($row['key_name'] === 'site_title') {
                $configContent = preg_replace(
                    "/define\('SITE_NAME',\s*'[^']*'\)/",
                    "define('SITE_NAME', '" . addslashes($row['value']) . "')",
                    $configContent
                );
            }
            if ($row['key_name'] === 'site_url') {
                $configContent = preg_replace(
                    "/define\('SITE_URL',\s*'[^']*'\)/",
                    "define('SITE_URL', '" . addslashes($row['value']) . "')",
                    $configContent
                );
            }
        }

        // 添加公众号配置常量（如果不存在）
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'wechat'");
        $wechatConfig = [];
        foreach ($stmt->fetchAll() as $row) {
            $wechatConfig[$row['key_name']] = $row['value'];
        }

        if (!empty($wechatConfig)) {
            // 检查是否已有公众号配置区域
            if (strpos($configContent, 'WECHAT_APPID') === false) {
                // 在知岁OS配置后面添加公众号配置
                $wechatBlock = "\n\n// 微信公众号配置\n";
                $wechatBlock .= "define('WECHAT_APPID', '" . addslashes($wechatConfig['wechat_appid'] ?? '') . "');\n";
                $wechatBlock .= "define('WECHAT_SECRET', '" . addslashes($wechatConfig['wechat_secret'] ?? '') . "');\n";
                $wechatBlock .= "define('WECHAT_ENABLED', '" . addslashes($wechatConfig['wechat_enabled'] ?? '0') . "');\n";
                $wechatBlock .= "define('WECHAT_FORCE_FOLLOW', '" . addslashes($wechatConfig['wechat_force_follow'] ?? '0') . "');\n";
                $wechatBlock .= "define('WECHAT_QRCODE_URL', '" . addslashes($wechatConfig['wechat_qrcode_url'] ?? '') . "');\n";

                $configContent = preg_replace(
                    "/(define\('ZSOS_SECRET_KEY',[^;]+;\n)/",
                    "$1" . $wechatBlock,
                    $configContent
                );
            } else {
                // 更新已有的公众号配置
                if (isset($wechatConfig['wechat_appid'])) {
                    $configContent = preg_replace(
                        "/define\('WECHAT_APPID',\s*'[^']*'\)/",
                        "define('WECHAT_APPID', '" . addslashes($wechatConfig['wechat_appid']) . "')",
                        $configContent
                    );
                }
                if (isset($wechatConfig['wechat_secret'])) {
                    $configContent = preg_replace(
                        "/define\('WECHAT_SECRET',\s*'[^']*'\)/",
                        "define('WECHAT_SECRET', '" . addslashes($wechatConfig['wechat_secret']) . "')",
                        $configContent
                    );
                }
                if (isset($wechatConfig['wechat_enabled'])) {
                    $configContent = preg_replace(
                        "/define\('WECHAT_ENABLED',\s*'[^']*'\)/",
                        "define('WECHAT_ENABLED', '" . addslashes($wechatConfig['wechat_enabled']) . "')",
                        $configContent
                    );
                }
                if (isset($wechatConfig['wechat_force_follow'])) {
                    $configContent = preg_replace(
                        "/define\('WECHAT_FORCE_FOLLOW',\s*'[^']*'\)/",
                        "define('WECHAT_FORCE_FOLLOW', '" . addslashes($wechatConfig['wechat_force_follow']) . "')",
                        $configContent
                    );
                }
                if (isset($wechatConfig['wechat_qrcode_url'])) {
                    $configContent = preg_replace(
                        "/define\('WECHAT_QRCODE_URL',\s*'[^']*'\)/",
                        "define('WECHAT_QRCODE_URL', '" . addslashes($wechatConfig['wechat_qrcode_url']) . "')",
                        $configContent
                    );
                }
            }
        }

        file_put_contents($configPath, $configContent);
        jsonResponse(['code' => 1, 'msg' => '配置已同步到 config.php']);
        break;

    // ====== 用户管理 ======
    case 'get_user':
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $data = $stmt->fetch();
        if ($data) {
            unset($data['password']);
            // 检查封禁是否过期
            if ($data['is_banned'] && $data['ban_expire_at'] && $data['ban_expire_at'] !== '9999-12-31 23:59:59' && $data['ban_expire_at'] < date('Y-m-d H:i:s')) {
                $stmt2 = $db->prepare("UPDATE users SET is_banned = 0, ban_reason = '', ban_expire_at = NULL WHERE id = ?");
                $stmt2->execute([$id]);
                $data['is_banned'] = 0;
                $data['ban_reason'] = '';
                $data['ban_expire_at'] = null;
            }
            jsonResponse(['code' => 1, 'data' => $data]);
        } else {
            jsonResponse(['code' => 0, 'msg' => '用户不存在']);
        }
        break;

    case 'ban_user':
        $id = (int)($_POST['id'] ?? 0);
        $duration = cleanInput($_POST['duration'] ?? '1d');
        $reason = cleanInput($_POST['reason'] ?? '');
        if ($id <= 0) jsonResponse(['code' => 0, 'msg' => '用户ID无效']);
        if (empty($reason)) jsonResponse(['code' => 0, 'msg' => '封禁原因不能为空']);

        // 计算封禁到期时间
        $expireAt = null;
        $now = time();
        switch ($duration) {
            case '1h':    $expireAt = date('Y-m-d H:i:s', $now + 3600); break;
            case '6h':    $expireAt = date('Y-m-d H:i:s', $now + 6 * 3600); break;
            case '1d':    $expireAt = date('Y-m-d H:i:s', $now + 86400); break;
            case '7d':    $expireAt = date('Y-m-d H:i:s', $now + 7 * 86400); break;
            case '30d':   $expireAt = date('Y-m-d H:i:s', $now + 30 * 86400); break;
            case 'forever': $expireAt = '9999-12-31 23:59:59'; break;
            default:      $expireAt = date('Y-m-d H:i:s', $now + 86400); break;
        }

        $stmt = $db->prepare("UPDATE users SET is_banned = 1, ban_reason = ?, ban_expire_at = ? WHERE id = ?");
        $stmt->execute([$reason, $expireAt, $id]);
        jsonResponse(['code' => 1, 'msg' => '用户已封禁']);
        break;

    case 'unban_user':
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) jsonResponse(['code' => 0, 'msg' => '用户ID无效']);
        $stmt = $db->prepare("UPDATE users SET is_banned = 0, ban_reason = '', ban_expire_at = NULL WHERE id = ?");
        $stmt->execute([$id]);
        jsonResponse(['code' => 1, 'msg' => '用户已解封']);
        break;

    case 'delete_user':
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 1) jsonResponse(['code' => 0, 'msg' => '不能删除默认用户']);
        $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);
        jsonResponse(['code' => 1, 'msg' => '用户删除成功']);
        break;

    // ====== 管理员密码修改 ======
    case 'change_password':
        $oldPwd = $_POST['old_password'] ?? '';
        $newPwd = $_POST['new_password'] ?? '';
        $confirmPwd = $_POST['confirm_password'] ?? '';

        if (empty($oldPwd) || empty($newPwd)) {
            jsonResponse(['code' => 0, 'msg' => '旧密码和新密码不能为空']);
        }
        if ($newPwd !== $confirmPwd) {
            jsonResponse(['code' => 0, 'msg' => '新密码与确认密码不一致']);
        }
        if (strlen($newPwd) < 6) {
            jsonResponse(['code' => 0, 'msg' => '新密码长度不能少于6位']);
        }

        $result = $auth->changePassword($oldPwd, $newPwd);
        if ($result) {
            jsonResponse(['code' => 1, 'msg' => '密码修改成功']);
        } else {
            jsonResponse(['code' => 0, 'msg' => '旧密码验证失败']);
        }
        break;

    // ====== 前端公共API ======

    // 获取首页弹窗（只在首页展示的、已启用的、有效期内的）
    case 'get_popups':
        $now = date('Y-m-d H:i:s');
        $stmt = $db->prepare("SELECT * FROM popups WHERE is_active = 1 AND show_pages = 'home' AND (start_time IS NULL OR start_time <= ?) AND (end_time IS NULL OR end_time >= ?) ORDER BY sort_order DESC");
        $stmt->execute([$now, $now]);
        $popups = $stmt->fetchAll();
        jsonResponse(['code' => 1, 'data' => $popups]);
        break;

    // 获取站点信息（logo、标题、公告）
    case 'get_site_info':
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'site'");
        $siteInfo = [];
        foreach ($stmt->fetchAll() as $row) {
            $siteInfo[$row['key_name']] = $row['value'];
        }
        jsonResponse(['code' => 1, 'data' => $siteInfo]);
        break;

    // 获取维护状态
    case 'get_maintenance':
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'site' AND key_name IN ('site_closed', 'site_closed_reason')");
        $maintInfo = [];
        foreach ($stmt->fetchAll() as $row) {
            $maintInfo[$row['key_name']] = $row['value'];
        }
        jsonResponse(['code' => 1, 'data' => $maintInfo]);
        break;

    // 获取团队信息
    case 'get_team_info':
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'team'");
        $teamInfo = [];
        foreach ($stmt->fetchAll() as $row) {
            $teamInfo[$row['key_name']] = $row['value'];
        }
        jsonResponse(['code' => 1, 'data' => $teamInfo]);
        break;

    // 获取公众号配置（前端登录页使用）
    case 'get_wechat_config':
        $stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'wechat'");
        $wechatInfo = [];
        foreach ($stmt->fetchAll() as $row) {
            // 不返回secret给前端
            if ($row['key_name'] !== 'wechat_secret') {
                $wechatInfo[$row['key_name']] = $row['value'];
            }
        }
        jsonResponse(['code' => 1, 'data' => $wechatInfo]);
        break;

    default:
        jsonResponse(['code' => 0, 'msg' => '未知操作: ' . $action]);
}
