<?php
/**
 * HuSNS - 一款免费开源的社交平台
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 * @声明    严禁用于违法违规用途
 */
class AdminController extends Controller
{
    private $userModel;
    private $postModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = new UserModel();
        $this->postModel = new PostModel();
        $this->view->setLayout('admin');
    }

    /**
     * 魔术方法处理短横线分隔的URL动作名
     * 例如: attachment-delete -> attachmentDelete
     *       admin_users -> adminUsers
     */
    public function __call($name, $arguments)
    {
        // 处理斜杠分隔的 action，例如: clearCache/do -> clearCacheDo
        if (strpos($name, '/') !== false) {
            $parts = explode('/', $name);
            $method = $parts[0] . ucfirst($parts[1]);
            if (isset($parts[2])) {
                $method .= ucfirst($parts[2]);
            }
        } else {
            // 将短横线和下划线转为驼峰
            $method = str_replace(['-', '_'], ' ', $name);
            $method = lcfirst(str_replace(' ', '', ucwords($method)));
        }
        
        // 映射到实际方法
        $methodMap = [
            'attachmentDelete' => 'doAttachmentDelete',
            'attachmentDeleteUnused' => 'doAttachmentDeleteUnused',
            'attachmentDeleteBatch' => 'doAttachmentDeleteBatch',
        ];
        
        if (isset($methodMap[$method]) && method_exists($this, $methodMap[$method])) {
            return call_user_func_array([$this, $methodMap[$method]], $arguments);
        }
        
        // 如果转换后的方法存在，直接调用
        if (method_exists($this, $method)) {
            return call_user_func_array([$this, $method], $arguments);
        }
        
        // 转发圈子管理请求到 CircleController
        if (strpos($name, 'circles') === 0) {
            $circleController = new CircleController();
            $circleAction = substr($name, 8); // 去掉 'circles' 前缀
            if (empty($circleAction)) {
                $circleAction = 'adminIndex';
            } else {
                $circleAction = 'admin' . ucfirst(ltrim($circleAction, '/'));
            }
            if (method_exists($circleController, $circleAction)) {
                return call_user_func_array([$circleController, $circleAction], $arguments);
            }
        }
        
        throw new Exception('方法不存在: ' . $name);
    }

    public function index()
    {
        $this->checkAdmin();
        
        $topicCount = $this->getTopicCount();
        
        $stats = [
            'users' => $this->db->count('users'),
            'posts' => $this->db->count('posts', 'status = 1'),
            'comments' => $this->db->count('comments', 'status = 1'),
            'topics' => $topicCount,
            'today_users' => $this->db->count('users', 'created_at > ?', [strtotime('today')]),
            'today_posts' => $this->db->count('posts', 'status = 1 AND created_at > ?', [strtotime('today')])
        ];

        $serverInfo = [
            'php_version' => PHP_VERSION,
            'mysql_version' => $this->getMysqlVersion(),
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'os' => PHP_OS,
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'post_max_size' => ini_get('post_max_size'),
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time') . '秒',
            'disk_free_space' => $this->formatBytes(disk_free_space(ROOT_PATH)),
            'php_extensions' => implode(', ', ['gd' => 'GD', 'pdo' => 'PDO', 'pdo_mysql' => 'PDO MySQL', 'mbstring' => 'Mbstring', 'curl' => 'cURL', 'json' => 'JSON', 'zip' => 'Zip']),
        ];
        
        $versionInfo = $this->checkLatestVersion();

        $this->render('admin/index', [
            'stats' => $stats,
            'serverInfo' => $serverInfo,
            'versionInfo' => $versionInfo
        ]);
    }
    
    /**
     * 检查最新版本
     * 
     * @return array 版本信息
     */
    private function checkLatestVersion()
    {
        $cacheFile = ROOT_PATH . 'temp' . DIRECTORY_SEPARATOR . 'version_check.json';
        $cacheTime = 3600;
        
        // 如果缓存文件存在且未过期，直接返回缓存
        if (file_exists($cacheFile)) {
            $cache = json_decode(file_get_contents($cacheFile), true);
            if ($cache && isset($cache['timestamp']) && (time() - $cache['timestamp']) < $cacheTime) {
                return $cache;
            }
        }
        
        $versionInfo = [
            'current' => APP_VERSION,
            'latest' => null,
            'has_update' => false,
            'release_url' => null,
            'timestamp' => time()
        ];
        
        // 检查 curl 扩展是否可用
        if (!function_exists('curl_init')) {
            return $versionInfo;
        }
        
        try {
            $ch = curl_init();
            if ($ch === false) {
                return $versionInfo;
            }
            
            curl_setopt_array($ch, [
                CURLOPT_URL => 'https://gitee.com/api/v5/repos/youruihu/husns/releases/latest',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_USERAGENT => 'HuSNS/' . APP_VERSION
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200 && $response) {
                $release = json_decode($response, true);
                
                if ($release && isset($release['tag_name'])) {
                    $latestVersion = ltrim($release['tag_name'], 'v');
                    $versionInfo['latest'] = $latestVersion;
                    $versionInfo['has_update'] = version_compare($latestVersion, APP_VERSION, '>');
                    $versionInfo['release_url'] = $release['html_url'] ?? null;
                    $versionInfo['release_notes'] = $release['body'] ?? '';
                }
            }
        } catch (Exception $e) {
            // 忽略异常，返回默认版本信息
        }
        
        // 尝试写入缓存文件，失败不影响功能
        try {
            $cacheDir = dirname($cacheFile);
            if (!is_dir($cacheDir)) {
                @mkdir($cacheDir, 0755, true);
            }
            if (is_dir($cacheDir) && is_writable($cacheDir)) {
                @file_put_contents($cacheFile, json_encode($versionInfo));
            }
        } catch (Exception $e) {
            // 缓存写入失败不影响功能
        }
        
        return $versionInfo;
    }

    private function getMysqlVersion()
    {
        try {
            $result = $this->db->fetch("SELECT VERSION() as version");
            return $result['version'] ?? 'Unknown';
        } catch (Exception $e) {
            return 'Unknown';
        }
    }

    private function formatBytes($bytes)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        return round($bytes, 2) . ' ' . $units[$pow];
    }

    private function getTopicCount()
    {
        $sql = "SELECT content FROM __PREFIX__posts WHERE status = 1";
        $posts = $this->db->fetchAll($sql);
        
        $topics = [];
        foreach ($posts as $post) {
            preg_match_all('/#([^\s#]+)/u', $post['content'], $matches);
            if (!empty($matches[1])) {
                foreach ($matches[1] as $topic) {
                    $topic = trim($topic);
                    if (!empty($topic)) {
                        $topics[$topic] = ($topics[$topic] ?? 0) + 1;
                    }
                }
            }
        }
        
        return count($topics);
    }

    public function verify()
    {
        if (!isset($_SESSION['user_id']) || !isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
            $this->redirect(Helper::url());
        }
        
        $authKey = 'admin_auth_time_' . $_SESSION['user_id'];
        $authExpire = 1800;
        
        if (isset($_SESSION[$authKey]) && (time() - $_SESSION[$authKey]) < $authExpire) {
            $_SESSION[$authKey] = time();
            $this->redirect(Helper::url('admin'));
        }
        
        if ($this->isPost()) {
            $password = Helper::post('password');
            
            $user = $this->userModel->find($_SESSION['user_id']);
            
            if (!$user || !Security::verifyPassword($password, $user['password'])) {
                $this->setFlash('error', '密码错误');
                $this->redirect(Helper::url('admin/verify'));
            }
            
            $_SESSION[$authKey] = time();
            $this->redirect(Helper::url('admin'));
        }
        
        $this->view->setLayout(null);
        $this->render('admin/verify');
    }

    public function circles($action = 'index')
    {
        $this->checkAdmin();
        
        $circleController = new CircleController();
        
        switch ($action) {
            case 'add':
                $circleController->adminAdd();
                break;
            case 'edit':
                $circleController->adminEdit();
                break;
            case 'delete':
                $circleController->adminDelete();
                break;
            case 'members':
                $circleController->adminMembers();
                break;
            case 'updateRole':
                $circleController->adminUpdateRole();
                break;
            case 'removeMember':
                $circleController->adminRemoveMember();
                break;
            case 'verify':
                $circleController->adminVerify();
                break;
            default:
                $circleController->adminIndex();
        }
    }
    
    public function users()
    {
        $this->checkAdmin();
        
        $page = (int)Helper::get('page', 1);
        $keyword = Helper::get('keyword', '');
        
        $where = '1';
        $params = [];
        
        if ($keyword) {
            $where = '(username LIKE ? OR email LIKE ?)';
            $params = ["%{$keyword}%", "%{$keyword}%"];
        }

        $users = $this->userModel->paginate($page, 20, $where, $params, 'id DESC');

        $this->render('admin/users', [
            'users' => $users,
            'keyword' => $keyword
        ]);
    }

    public function userStatus()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $id = (int)Helper::post('id');
        $status = (int)Helper::post('status');
        
        if (!in_array($status, [0, 1])) {
            $this->jsonError('状态值错误');
        }

        $user = $this->userModel->find($id);
        if (!$user) {
            $this->jsonError('用户不存在');
        }

        if ($user['is_admin'] && $status == 0) {
            $this->jsonError('不能封禁管理员');
        }

        $this->userModel->update($id, ['status' => $status, 'updated_at' => time()]);
        $this->jsonSuccess(null, $status ? '用户已解封' : '用户已封禁');
    }

    public function userEdit()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $id = (int)Helper::post('id');
        $username = trim(Helper::post('username'));
        $email = trim(Helper::post('email'));
        $bio = trim(Helper::post('bio'));
        $password = trim(Helper::post('password'));
        
        $user = $this->userModel->find($id);
        if (!$user) {
            $this->jsonError('用户不存在');
        }
        
        if (empty($username)) {
            $this->jsonError('用户名不能为空');
        }
        
        if (empty($email)) {
            $this->jsonError('邮箱不能为空');
        }
        
        $existing = $this->db->fetch(
            "SELECT id FROM __PREFIX__users WHERE (username = ? OR email = ?) AND id != ?",
            [$username, $email, $id]
        );
        if ($existing) {
            $this->jsonError('用户名或邮箱已被使用');
        }
        
        $data = [
            'username' => $username,
            'email' => $email,
            'bio' => $bio,
            'updated_at' => time()
        ];
        
        if (!empty($password)) {
            if (strlen($password) < 6) {
                $this->jsonError('密码长度不能少于6位');
            }
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }
        
        $this->userModel->update($id, $data);
        $this->jsonSuccess(null, '用户信息已更新');
    }

    public function userBan()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $id = (int)Helper::post('id');
        $banDays = (int)Helper::post('ban_days');
        $banReason = trim(Helper::post('ban_reason'));
        
        $user = $this->userModel->find($id);
        if (!$user) {
            $this->jsonError('用户不存在');
        }
        
        if ($user['is_admin']) {
            $this->jsonError('不能对管理员进行禁言操作');
        }
        
        $notificationModel = new NotificationModel();
        
        if ($banDays === -1) {
            $data = [
                'ban_type' => 0,
                'ban_until' => 0,
                'ban_reason' => '',
                'updated_at' => time()
            ];
            $this->userModel->update($id, $data);
            
            $notificationModel->send(
                $id,
                NotificationModel::TYPE_SYSTEM,
                '您已被解除禁言',
                '管理员已解除了您的禁言状态，您现在可以正常发布内容、评论和点赞了。',
                [
                    'sender_id' => 0,
                    'target_type' => NotificationModel::TARGET_USER,
                    'target_id' => $id,
                    'data' => ['action' => 'unban']
                ]
            );
            
            $this->jsonSuccess(null, '已解除禁言');
        }
        
        $banUntil = $banDays === 0 ? 0 : time() + ($banDays * 86400);
        
        $data = [
            'ban_type' => 1,
            'ban_until' => $banUntil,
            'ban_reason' => $banReason,
            'updated_at' => time()
        ];
        
        $this->userModel->update($id, $data);
        
        $untilText = $banDays === 0 ? '永久' : date('Y-m-d H:i', $banUntil);
        $reasonText = $banReason ? "\n原因：" . $banReason : '';
        
        $notificationModel->send(
            $id,
            NotificationModel::TYPE_SYSTEM,
            '您已被禁言',
            '您已被管理员禁言，禁言期间无法发布内容、评论和点赞。' . "\n禁言至：" . $untilText . $reasonText,
            [
                'sender_id' => 0,
                'target_type' => NotificationModel::TARGET_USER,
                'target_id' => $id,
                'data' => ['action' => 'ban', 'ban_until' => $banUntil, 'ban_reason' => $banReason]
            ]
        );
        
        $untilTextShort = $banDays === 0 ? '永久' : $banDays . '天';
        $this->jsonSuccess(null, '已禁言用户' . $untilTextShort);
    }

    public function posts()
    {
        $this->checkAdmin();
        
        $page = (int)Helper::get('page', 1);
        $keyword = Helper::get('keyword', '');
        
        $where = 'p.status = 1';
        $params = [];
        
        if ($keyword) {
            $where .= ' AND (p.content LIKE ? OR u.username LIKE ?)';
            $params = ["%{$keyword}%", "%{$keyword}%"];
        }

        $offset = ($page - 1) * 20;
        $sql = "SELECT p.*, u.username, p.ip 
                FROM __PREFIX__posts p 
                INNER JOIN __PREFIX__users u ON p.user_id = u.id 
                WHERE {$where} 
                ORDER BY p.is_pinned DESC, p.is_featured DESC, p.id DESC 
                LIMIT {$offset}, 20";
        
        $posts = $this->db->fetchAll($sql, $params);
        
        foreach ($posts as &$post) {
            $post['time_ago'] = Helper::formatTime($post['created_at']);
            $post['location'] = IpLocation::getLocation($post['ip'] ?? '');
        }

        $total = $this->db->count('posts', 'status = 1');
        $totalPages = ceil($total / 20);

        $this->render('admin/posts', [
            'posts' => $posts,
            'page' => $page,
            'totalPages' => $totalPages,
            'keyword' => $keyword
        ]);
    }

    public function postDelete()
    {
        $this->checkAdmin();
        
        $id = (int)Helper::post('id');
        
        $result = $this->db->update('posts', ['status' => 0, 'updated_at' => time()], 'id = ?', [$id]);
        
        if ($result) {
            $this->jsonSuccess(null, '删除成功');
        }
        $this->jsonError('删除失败');
    }

    public function comments()
    {
        $this->checkAdmin();
        
        $page = (int)Helper::get('page', 1);
        $keyword = Helper::get('keyword', '');
        
        $where = 'c.status = 1';
        $params = [];
        
        if ($keyword) {
            $where .= ' AND (c.content LIKE ? OR u.username LIKE ?)';
            $params = ["%{$keyword}%", "%{$keyword}%"];
        }

        $offset = ($page - 1) * 20;
        $sql = "SELECT c.*, u.username 
                FROM __PREFIX__comments c 
                INNER JOIN __PREFIX__users u ON c.user_id = u.id 
                WHERE {$where} 
                ORDER BY c.id DESC 
                LIMIT {$offset}, 20";
        
        $comments = $this->db->fetchAll($sql, $params);
        
        foreach ($comments as &$comment) {
            $comment['time_ago'] = Helper::formatTime($comment['created_at']);
            $comment['location'] = IpLocation::getLocation($comment['ip'] ?? '');
        }

        $total = $this->db->count('comments', 'status = 1');
        $totalPages = ceil($total / 20);

        $this->render('admin/comments', [
            'comments' => $comments,
            'page' => $page,
            'totalPages' => $totalPages,
            'keyword' => $keyword
        ]);
    }

    public function commentDelete()
    {
        $this->checkAdmin();
        
        $id = (int)Helper::post('id');
        
        $comment = $this->db->fetch("SELECT * FROM __PREFIX__comments WHERE id = ?", [$id]);
        if (!$comment) {
            $this->setFlash('error', '评论不存在');
            $this->redirect(Helper::url('admin/comments'));
            return;
        }
        
        $result = $this->db->update('comments', ['status' => 0], 'id = ?', [$id]);
        
        if ($result) {
            $this->db->query("UPDATE __PREFIX__posts SET comments = comments - 1 WHERE id = ?", [$comment['post_id']]);
            $this->setFlash('success', '删除成功');
        } else {
            $this->setFlash('error', '删除失败');
        }
        
        $this->redirect(Helper::url('admin/comments'));
    }

    public function togglePin()
    {
        $this->checkAdmin();
        
        $id = (int)Helper::post('id');
        
        $post = $this->postModel->find($id);
        if (!$post) {
            $this->jsonError('动态不存在');
        }
        
        if (!isset($post['is_pinned'])) {
            $this->jsonError('数据库尚未升级，请刷新页面后重试');
        }
        
        $currentStatus = (int)$post['is_pinned'];
        $newStatus = $currentStatus ? 0 : 1;
        
        $result = $this->postModel->update($id, ['is_pinned' => $newStatus]);
        
        $message = $newStatus ? '置顶成功' : '取消置顶成功';
        $this->jsonSuccess(['is_pinned' => $newStatus], $message);
    }

    public function toggleFeature()
    {
        $this->checkAdmin();
        
        $id = (int)Helper::post('id');
        
        $post = $this->postModel->find($id);
        if (!$post) {
            $this->jsonError('动态不存在');
        }
        
        if (!isset($post['is_featured'])) {
            $this->jsonError('数据库尚未升级，请刷新页面后重试');
        }
        
        $currentStatus = (int)$post['is_featured'];
        $newStatus = $currentStatus ? 0 : 1;
        
        $result = $this->postModel->update($id, ['is_featured' => $newStatus]);
        
        $message = $newStatus ? '加精成功' : '取消加精成功';
        $this->jsonSuccess(['is_featured' => $newStatus], $message);
    }

    public function settings()
    {
        $this->checkAdmin();
        
        if ($this->isPost()) {
            $siteName = trim(Helper::post('site_name'));
            $siteSubtitle = trim(Helper::post('site_subtitle'));
            $siteKeywords = trim(Helper::post('site_keywords'));
            $siteDescription = trim(Helper::post('site_description'));
            $postsPerPage = (int)Helper::post('posts_per_page', 10);
            $maxPostLength = (int)Helper::post('max_post_length', 500);
            $maxCommentLength = (int)Helper::post('max_comment_length', 500);
            $registrationOpen = (int)Helper::post('registration_open', 1);
            $allowedEmailSuffixes = trim(Helper::post('allowed_email_suffixes', ''));
            $maxAttachmentSize = (int)Helper::post('max_attachment_size', 10);
            $allowedAttachmentExtensions = trim(Helper::post('allowed_attachment_extensions', 'pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar'));
            $maxAttachmentCount = (int)Helper::post('max_attachment_count', 5);
            
            if ($postsPerPage < 5 || $postsPerPage > 50) {
                $postsPerPage = 10;
            }
            
            if ($maxPostLength < 50 || $maxPostLength > 5000) {
                $maxPostLength = 500;
            }
            
            if ($maxCommentLength < 50 || $maxCommentLength > 2000) {
                $maxCommentLength = 500;
            }
            
            if ($maxAttachmentSize < 1 || $maxAttachmentSize > 100) {
                $maxAttachmentSize = 10;
            }
            
            if ($maxAttachmentCount < 1 || $maxAttachmentCount > 10) {
                $maxAttachmentCount = 5;
            }
            
            $this->saveSettingValue('site_name', $siteName);
            $this->saveSettingValue('site_subtitle', $siteSubtitle);
            $this->saveSettingValue('site_keywords', $siteKeywords);
            $this->saveSettingValue('site_description', $siteDescription);
            $this->saveSettingValue('posts_per_page', $postsPerPage);
            $this->saveSettingValue('max_post_length', $maxPostLength);
            $this->saveSettingValue('publish_placeholder', trim(Helper::post('publish_placeholder', '')));
            $this->saveSettingValue('max_comment_length', $maxCommentLength);
            $this->saveSettingValue('hide_tag_admin_only', (int)Helper::post('hide_tag_admin_only', 0));
            $this->saveSettingValue('hot_topics_enabled', (int)Helper::post('hot_topics_enabled', 1));
            $this->saveSettingValue('hot_threshold', min(10000, max(1, (int)Helper::post('hot_threshold', 20))));
            $this->saveSettingValue('circles_enabled', (int)Helper::post('circles_enabled', 1));
            $this->saveSettingValue('registration_open', $registrationOpen);
            $this->saveSettingValue('allowed_email_suffixes', $allowedEmailSuffixes);
            $this->saveSettingValue('max_attachment_size', min(100, max(1, $maxAttachmentSize)));
            $this->saveSettingValue('allowed_attachment_extensions', $allowedAttachmentExtensions);
            $this->saveSettingValue('max_attachment_count', $maxAttachmentCount);
            $this->saveSettingValue('max_image_size', min(20, max(1, (int)Helper::post('max_image_size', 5))));
            $this->saveSettingValue('max_avatar_size', min(20, max(1, (int)Helper::post('max_avatar_size', 5))));
            $this->saveSettingValue('max_image_count', min(18, max(1, (int)Helper::post('max_image_count', 9))));
            $this->saveSettingValue('guest_download_allowed', (int)Helper::post('guest_download_allowed', 1));
            $this->saveSettingValue('mention_suggest_scope', Helper::post('mention_suggest_scope', 'all'));
            $this->saveSettingValue('max_video_size', min(500, max(1, (int)Helper::post('max_video_size', 100))));
            $this->saveSettingValue('max_video_count', min(5, max(1, (int)Helper::post('max_video_count', 1))));
            $this->saveSettingValue('point_name', trim(Helper::post('point_name', '积分')));
            $this->saveSettingValue('banned_usernames', trim(Helper::post('banned_usernames', '')));
            $this->saveSettingValue('action_interval', min(60, max(0, (int)Helper::post('action_interval', 0))));
            $this->saveSettingValue('default_all_posts_threshold', min(10000, max(0, (int)Helper::post('default_all_posts_threshold', 100))));
            $this->saveSettingValue('icp_number', trim(Helper::post('icp_number', '')));
            $this->saveSettingValue('icp_url', trim(Helper::post('icp_url', 'https://beian.miit.gov.cn/')));
            $this->saveSettingValue('guest_access_allowed', (int)Helper::post('guest_access_allowed', 1));
            $this->saveSettingValue('registration_email_verify', (int)Helper::post('registration_email_verify', 0));
            $this->saveSettingValue('require_invite_code', (int)Helper::post('require_invite_code', 0));
            $this->saveSettingValue('mail_enabled', (int)Helper::post('mail_enabled', 0));
            $this->saveSettingValue('mail_host', trim(Helper::post('mail_host', '')));
            $this->saveSettingValue('mail_port', (int)Helper::post('mail_port', 465));
            $this->saveSettingValue('mail_encryption', Helper::post('mail_encryption', 'ssl'));
            $this->saveSettingValue('mail_username', trim(Helper::post('mail_username', '')));
            $this->saveSettingValue('mail_password', trim(Helper::post('mail_password', '')));
            $this->saveSettingValue('mail_from_name', trim(Helper::post('mail_from_name', '')));
            $this->saveSettingValue('mail_from_address', trim(Helper::post('mail_from_address', '')));
            
            $usernameMinLength = min(20, max(1, (int)Helper::post('username_min_length', 2)));
            $usernameMaxLength = min(50, max(1, (int)Helper::post('username_max_length', 20)));
            if ($usernameMaxLength < $usernameMinLength) {
                $usernameMaxLength = $usernameMinLength;
            }
            $this->saveSettingValue('username_min_length', $usernameMinLength);
            $this->saveSettingValue('username_max_length', $usernameMaxLength);
            
            $this->saveSettingValue('language_mode', Helper::post('language_mode', 'manual'));
            $this->saveSettingValue('default_language', Helper::post('default_language', 'zh-cn'));
            
            // 移动端功能开关设置
            $this->saveSettingValue('mobile_location_enabled', (int)Helper::post('mobile_location_enabled', 1));
            $this->saveSettingValue('mobile_at_enabled', (int)Helper::post('mobile_at_enabled', 1));
            $this->saveSettingValue('mobile_privacy_enabled', (int)Helper::post('mobile_privacy_enabled', 1));
            $this->saveSettingValue('mobile_emoji_enabled', (int)Helper::post('mobile_emoji_enabled', 1));
            $this->saveSettingValue('mobile_topic_enabled', (int)Helper::post('mobile_topic_enabled', 1));
            $this->saveSettingValue('mobile_hot_enabled', (int)Helper::post('mobile_hot_enabled', 1));
            $this->saveSettingValue('mobile_discover_enabled', (int)Helper::post('mobile_discover_enabled', 1));
            $this->saveSettingValue('mobile_hot_topics_enabled', (int)Helper::post('mobile_hot_topics_enabled', 1));
            $this->saveSettingValue('mobile_favorite_enabled', (int)Helper::post('mobile_favorite_enabled', 1));
            $this->saveSettingValue('mobile_message_enabled', (int)Helper::post('mobile_message_enabled', 1));
            
            // 清除设置缓存，使新设置立即生效
            Setting::clearCache();
            
            // 处理可用语言数组
            $availableLanguages = Helper::post('available_languages', ['zh-cn']);
            if (is_array($availableLanguages)) {
                $this->saveSettingValue('available_languages', implode(',', $availableLanguages));
            } else {
                $this->saveSettingValue('available_languages', 'zh-cn,zh-tw,en');
            }
            
            $this->setFlash('success', '设置保存成功');
            
            $currentTab = Helper::post('current_tab', 'basic');
            $this->redirect(Helper::url('admin/settings?tab=' . $currentTab));
        }

        $settings = $this->getSettings();
        $this->render('admin/settings', ['settings' => $settings]);
    }
    
    public function statistics()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'service/StatisticsService.php';
        $statsService = new StatisticsService();
        
        $overview = $statsService->getOverview();
        $userGrowth = $statsService->getUserGrowth(7);
        $contentTrend = $statsService->getContentTrend(7);
        $activeUsers = $statsService->getActiveUsers(10);
        $hotTopics = $statsService->getHotTopics(10);
        $reportStats = $statsService->getReportStats();
        $activityDistribution = $statsService->getUserActivityDistribution();
        $postSourceDistribution = $statsService->getPostSourceDistribution();
        
        $this->view->setLayout('admin');
        $this->render('admin/statistics', [
            'overview' => $overview,
            'userGrowth' => $userGrowth,
            'contentTrend' => $contentTrend,
            'activeUsers' => $activeUsers,
            'hotTopics' => $hotTopics,
            'reportStats' => $reportStats,
            'activityDistribution' => $activityDistribution,
            'postSourceDistribution' => $postSourceDistribution
        ]);
    }

    private function saveSettingValue($key, $value)
    {
        $exists = $this->db->fetch("SELECT * FROM __PREFIX__settings WHERE `key` = ?", [$key]);
        
        if ($exists) {
            $this->db->update('settings', ['value' => $value, 'updated_at' => time()], '`key` = ?', [$key]);
        } else {
            $this->db->insert('settings', [
                'key' => $key,
                'value' => $value,
                'created_at' => time(),
                'updated_at' => time()
            ]);
        }
    }

    private function getSettings()
    {
        $rows = $this->db->fetchAll("SELECT * FROM __PREFIX__settings");
        $settings = [];
        
        foreach ($rows as $row) {
            $settings[$row['key']] = $row['value'];
        }
        
        return $settings;
    }
    
    public function saveSetting()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            Helper::jsonError('安全验证失败');
        }
        
        $key = Helper::post('key');
        $value = Helper::post('value');
        
        if (empty($key)) {
            Helper::jsonError('参数错误');
        }
        
        $this->saveSettingValue($key, $value);
        Helper::jsonSuccess(null, '保存成功');
    }
    
    public function testMail()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            Helper::jsonError('安全验证失败');
        }
        
        $email = Helper::post('email');
        if (empty($email)) {
            Helper::jsonError('请输入测试邮箱地址');
        }
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            Helper::jsonError('邮箱格式不正确');
        }
        
        $result = Mailer::send($email, '【' . Setting::getSiteName() . '】测试邮件', '
            <div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; padding: 20px; background: #f5f5f5;">
                <div style="max-width: 500px; margin: 0 auto; background: #fff; border-radius: 8px; padding: 30px; text-align: center;">
                    <h2 style="color: #1e293b; margin-bottom: 20px;">邮件测试成功</h2>
                    <p style="color: #64748b;">恭喜！您的邮件服务配置正确，可以正常发送邮件。</p>
                    <p style="color: #94a3b8; font-size: 12px; margin-top: 30px;">发送时间：' . date('Y-m-d H:i:s') . '</p>
                </div>
            </div>
        ');
        
        if ($result['success']) {
            Helper::jsonSuccess(null, '测试邮件已发送至 ' . $email);
        } else {
            Helper::jsonError($result['message']);
        }
    }

    public function userDelete()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            Helper::jsonError('安全验证失败');
        }
        
        $id = (int)Helper::post('id');
        
        if ($id <= 0) {
            Helper::jsonError('用户ID无效');
        }
        
        $user = $this->db->fetch("SELECT * FROM __PREFIX__users WHERE id = ?", [$id]);
        
        if (!$user) {
            Helper::jsonError('用户不存在');
        }
        
        if ($user['is_admin']) {
            Helper::jsonError('不能删除管理员用户');
        }
        
        if ($id == $_SESSION['user_id']) {
            Helper::jsonError('不能删除自己');
        }
        
        try {
            $posts = $this->db->fetchAll("SELECT images, attachments, videos FROM __PREFIX__posts WHERE user_id = ?", [$id]);
            
            foreach ($posts as $post) {
                $this->deleteMediaFiles($post['images']);
                $this->deleteMediaFiles($post['attachments']);
                $this->deleteMediaFiles($post['videos']);
            }
            
            if (!empty($user['avatar'])) {
                $this->deleteFile($user['avatar']);
            }
            
            $this->db->delete('posts', 'user_id = ?', [$id]);
            $this->db->delete('comments', 'user_id = ?', [$id]);
            $this->db->delete('likes', 'user_id = ?', [$id]);
            $this->db->delete('follows', 'user_id = ? OR follow_id = ?', [$id, $id]);
            $this->db->delete('notifications', 'user_id = ? OR sender_id = ?', [$id, $id]);
            $this->db->delete('point_logs', 'user_id = ?', [$id]);
            $this->db->delete('users', 'id = ?', [$id]);
            
            Helper::jsonSuccess(null, '用户已删除');
        } catch (Exception $e) {
            Helper::jsonError('删除失败：' . $e->getMessage());
        }
    }
    
    private function deleteMediaFiles($jsonStr)
    {
        if (empty($jsonStr)) {
            return;
        }
        
        $items = json_decode($jsonStr, true);
        
        if (!is_array($items)) {
            return;
        }
        
        foreach ($items as $item) {
            if (is_string($item)) {
                $this->deleteFile($item);
            } elseif (is_array($item) && isset($item['path'])) {
                $this->deleteFile($item['path']);
            } elseif (is_array($item) && isset($item['url'])) {
                $this->deleteFile($item['url']);
            }
        }
    }
    
    private function deleteFile($path)
    {
        if (empty($path)) {
            return;
        }
        
        if (preg_match('/^https?:\/\//i', $path)) {
            return;
        }
        
        $fullPath = ROOT_PATH . 'uploads' . DIRECTORY_SEPARATOR . ltrim(str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR);
        
        if (strpos($fullPath, ROOT_PATH . 'uploads') !== 0) {
            return;
        }
        
        if (file_exists($fullPath) && is_file($fullPath)) {
            @unlink($fullPath);
        }
    }
    
    /**
     * 举报管理列表
     */
    public function reports()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'content/report/ReportModel.php';
        $reportModel = new ReportModel();
        
        $page = (int)Helper::get('page', 1);
        $status = (int)Helper::get('status', -1);
        
        $result = $reportModel->getReports($page, 20, $status);
        
        $stats = [
            'total' => $reportModel->countReports(),
            'pending' => $reportModel->countReports(0),
            'handled' => $reportModel->countReports(1),
            'rejected' => $reportModel->countReports(2),
        ];
        
        foreach ($result['items'] as &$report) {
            $report['status_label'] = $reportModel->getStatusLabel($report['status']);
        }
        
        $this->view->setLayout('admin');
        $this->render('admin/reports', [
            'reports' => $result['items'],
            'page' => $result['page'],
            'totalPages' => $result['totalPages'],
            'status' => $status,
            'stats' => $stats,
            'reasonOptions' => $reportModel->getReasonOptions()
        ]);
    }
    
    /**
     * 处理举报
     */
    public function reportHandle()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'content/report/ReportModel.php';
        $reportModel = new ReportModel();
        
        $id = (int)Helper::post('id');
        $status = (int)Helper::post('status');
        $result = trim(Helper::post('result', ''));
        
        if (!in_array($status, [1, 2])) {
            $this->jsonError('状态值错误');
        }
        
        $report = $reportModel->getReport($id);
        if (!$report) {
            $this->jsonError('举报不存在');
        }
        
        $handlerId = $_SESSION['user_id'];
        $success = $reportModel->handleReport($id, $status, $handlerId, $result);
        
        if ($success) {
            $message = $status == 1 ? '处理成功' : '已驳回';
            $this->jsonSuccess(null, $message);
        } else {
            $this->jsonError('处理失败');
        }
    }
    
    /**
     * 举报详情
     */
    public function reportDetail()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'content/report/ReportModel.php';
        $reportModel = new ReportModel();
        
        $id = (int)Helper::get('id');
        $report = $reportModel->getReport($id);
        
        if (!$report) {
            $this->setFlash('error', '举报不存在');
            $this->redirect(Helper::url('admin/reports'));
            return;
        }
        
        $report['status_label'] = $reportModel->getStatusLabel($report['status']);
        
        $this->view->setLayout('admin');
        $this->render('admin/report_detail', [
            'report' => $report,
            'reasonOptions' => $reportModel->getReasonOptions()
        ]);
    }
    
    /**
     * 敏感词管理列表
     */
    public function filter()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'content/filter/FilterModel.php';
        $filterModel = new FilterModel();
        
        $page = (int)Helper::get('page', 1);
        $keyword = trim(Helper::get('keyword', ''));
        
        $result = $filterModel->getWords($page, 20, $keyword);
        
        $this->view->setLayout('admin');
        $this->render('admin/filter', [
            'words' => $result['items'],
            'page' => $result['page'],
            'totalPages' => $result['totalPages'],
            'keyword' => $keyword
        ]);
    }
    
    /**
     * 保存敏感词
     */
    public function filterSave()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'content/filter/FilterModel.php';
        $filterModel = new FilterModel();
        
        $id = (int)Helper::post('id');
        $word = trim(Helper::post('word'));
        $replacement = trim(Helper::post('replacement', ''));
        
        if (empty($word)) {
            $this->jsonError('请输入敏感词');
        }
        
        if (mb_strlen($word) > 100) {
            $this->jsonError('敏感词长度不能超过100字符');
        }
        
        if ($id > 0) {
            $success = $filterModel->updateWord($id, $word, $replacement);
        } else {
            $success = $filterModel->addWord($word, $replacement);
        }
        
        if ($success) {
            $message = $id > 0 ? '修改成功' : '添加成功';
            $this->jsonSuccess(null, $message);
        } else {
            $this->jsonError($id > 0 ? '修改失败' : '添加失败，敏感词已存在');
        }
    }
    
    /**
     * 删除敏感词
     */
    public function filterDelete()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'content/filter/FilterModel.php';
        $filterModel = new FilterModel();
        
        $id = (int)Helper::post('id');
        
        if ($id <= 0) {
            $this->jsonError('参数错误');
        }
        
        $success = $filterModel->deleteWord($id);
        
        if ($success) {
            $this->jsonSuccess(null, '删除成功');
        } else {
            $this->jsonError('删除失败');
        }
    }
    
    /**
     * 获取敏感词详情
     */
    public function filterGet()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'content/filter/FilterModel.php';
        $filterModel = new FilterModel();
        
        $id = (int)Helper::get('id');
        
        if ($id <= 0) {
            $this->jsonError('参数错误');
        }
        
        $word = $filterModel->getWord($id);
        
        if ($word) {
            $this->jsonSuccess($word);
        } else {
            $this->jsonError('敏感词不存在');
        }
    }
    
    /**
     * 导入敏感词
     */
    public function filterImport()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'content/filter/FilterModel.php';
        $filterModel = new FilterModel();
        
        if (!isset($_FILES['file']) || $_FILES['file']['error'] != UPLOAD_ERR_OK) {
            $this->jsonError('请选择要上传的文件');
        }
        
        $file = $_FILES['file'];
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        
        if ($ext != 'txt') {
            $this->jsonError('只支持 .txt 文件');
        }
        
        $count = $filterModel->importFromFile($file['tmp_name']);
        
        $this->jsonSuccess(null, "成功导入 {$count} 个敏感词");
    }
    
    /**
     * 备份管理页面
     */
    public function backup($action = null)
    {
        $this->checkAdmin();
        
        // 处理子操作
        if ($action !== null) {
            $actionMap = [
                'create' => 'backupCreate',
                'code' => 'backupCode',
                'uploads' => 'backupUploads',
                'full' => 'backupFull',
                'delete' => 'backupDelete',
                'restore' => 'backupRestore',
                'upload' => 'backupUpload',
                'download' => 'backupDownload',
                'cleanup' => 'backupCleanup',
            ];
            
            $method = $actionMap[$action] ?? null;
            if ($method && method_exists($this, $method)) {
                return $this->$method();
            }
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $backups = $backupService->getBackupFiles('all');
        $stats = $backupService->getBackupStats();
        
        $this->view->setLayout('admin');
        $this->render('admin/backup', [
            'backups' => $backups,
            'stats' => $stats
        ]);
    }
    
    /**
     * 创建备份
     */
    public function backupCreate()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $result = $backupService->backupDatabase();
        
        if ($result) {
            $this->jsonSuccess(null, '备份创建成功');
        } else {
            $this->jsonError('备份创建失败');
        }
    }
    
    /**
     * 备份项目代码
     */
    public function backupCode()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $result = $backupService->backupFiles('code');
        
        if ($result) {
            $this->jsonSuccess(['file' => basename($result)], '代码备份创建成功');
        } else {
            $this->jsonError('代码备份创建失败，请检查服务器配置（需启用 ZipArchive）');
        }
    }
    
    /**
     * 备份上传文件
     */
    public function backupUploads()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $result = $backupService->backupFiles('uploads');
        
        if ($result) {
            $this->jsonSuccess(['file' => basename($result)], '上传文件备份创建成功');
        } else {
            $this->jsonError('上传文件备份创建失败，请检查服务器配置（需启用 ZipArchive）');
        }
    }
    
    /**
     * 完整备份（代码+上传+数据库）
     */
    public function backupFull()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $result = $backupService->backupFiles('full');
        
        if ($result) {
            $this->jsonSuccess(['file' => basename($result)], '完整备份创建成功');
        } else {
            $this->jsonError('完整备份创建失败，请检查服务器配置（需启用 ZipArchive）');
        }
    }
    
    /**
     * 下载备份文件
     */
    public function backupDownload()
    {
        $this->checkAdmin();
        
        $filename = Helper::get('file');
        
        // 安全检查
        if (strpos($filename, '..') !== false || empty($filename)) {
            die('无效的文件名');
        }
        
        $path = ROOT_PATH . 'backups' . DIRECTORY_SEPARATOR . $filename;
        
        if (!file_exists($path)) {
            die('文件不存在');
        }
        
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($path));
        
        readfile($path);
        exit;
    }
    
    /**
     * 恢复备份
     */
    public function backupRestore()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $filename = Helper::post('filename');
        
        // 安全检查
        if (strpos($filename, '..') !== false || empty($filename)) {
            $this->jsonError('无效的文件名');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $path = ROOT_PATH . 'backups' . DIRECTORY_SEPARATOR . $filename;
        
        if (!file_exists($path)) {
            $this->jsonError('备份文件不存在');
        }
        
        $result = $backupService->restoreDatabase($path);
        
        if ($result) {
            $this->jsonSuccess(null, '恢复成功');
        } else {
            $this->jsonError('恢复失败');
        }
    }
    
    /**
     * 上传并恢复备份
     */
    public function backupUpload()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        if (!isset($_FILES['file']) || $_FILES['file']['error'] != UPLOAD_ERR_OK) {
            $this->jsonError('请选择要上传的文件');
        }
        
        $file = $_FILES['file'];
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        
        if ($ext != 'sql') {
            $this->jsonError('只支持 .sql 文件');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $result = $backupService->restoreDatabase($file['tmp_name']);
        
        if ($result) {
            $this->jsonSuccess(null, '恢复成功');
        } else {
            $this->jsonError('恢复失败');
        }
    }
    
    /**
     * 删除备份文件
     */
    public function backupDelete()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $filename = Helper::post('filename');
        
        // 安全检查
        if (strpos($filename, '..') !== false || empty($filename)) {
            $this->jsonError('无效的文件名');
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $result = $backupService->deleteBackup($filename);
        
        if ($result) {
            $this->jsonSuccess(null, '删除成功');
        } else {
            $this->jsonError('删除失败');
        }
    }
    
    /**
     * 批量清理备份文件
     */
    public function backupCleanup()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $keepCount = intval(Helper::post('keep_count', 5));
        if ($keepCount < 1) {
            $keepCount = 1;
        }
        
        require_once ROOT_PATH . 'service/BackupService.php';
        $backupService = new BackupService();
        
        $backups = $backupService->getBackupFiles();
        $deletedCount = 0;
        
        if (count($backups) > $keepCount) {
            $oldFiles = array_slice($backups, $keepCount);
            
            foreach ($oldFiles as $file) {
                if ($backupService->deleteBackup($file['name'])) {
                    $deletedCount++;
                }
            }
        }
        
        $this->jsonSuccess(['deleted_count' => $deletedCount], "清理完成，已删除 {$deletedCount} 个备份文件");
    }
    
    /**
     * 角色管理列表
     */
    public function roles()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $roles = $roleModel->getAllRoles();
        
        foreach ($roles as &$role) {
            $role['permissions'] = !empty($role['permissions']) ? json_decode($role['permissions'], true) : [];
        }
        
        $this->view->setLayout('admin');
        $this->render('admin/roles', [
            'roles' => $roles,
            'permissions' => $roleModel->getAvailablePermissions()
        ]);
    }
    
    /**
     * 保存角色
     */
    public function rolesSave()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $id = (int)Helper::post('id');
        $name = trim(Helper::post('name'));
        $description = trim(Helper::post('description', ''));
        $permissions = Helper::post('permissions', []);
        
        if (empty($name)) {
            $this->jsonError('请输入角色名称');
        }
        
        if (!is_array($permissions)) {
            $permissions = [];
        }
        
        if ($id > 0) {
            $success = $roleModel->updateRole($id, [
                'name' => $name,
                'description' => $description,
                'permissions' => $permissions
            ]);
        } else {
            $success = $roleModel->createRole([
                'name' => $name,
                'description' => $description,
                'permissions' => $permissions
            ]);
        }
        
        if ($success) {
            $message = $id > 0 ? '修改成功' : '添加成功';
            $this->jsonSuccess(null, $message);
        } else {
            $this->jsonError($id > 0 ? '修改失败' : '添加失败，角色名称已存在');
        }
    }
    
    /**
     * 删除角色
     */
    public function rolesDelete()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $id = (int)Helper::post('id');
        
        if ($id <= 0) {
            $this->jsonError('参数错误');
        }
        
        if ($id == 1) {
            $this->jsonError('不能删除超级管理员角色');
        }
        
        $success = $roleModel->deleteRole($id);
        
        if ($success) {
            $this->jsonSuccess(null, '删除成功');
        } else {
            $this->jsonError('删除失败');
        }
    }
    
    /**
     * 获取角色详情
     */
    public function rolesGet()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $id = (int)Helper::get('id');
        
        if ($id <= 0) {
            $this->jsonError('参数错误');
        }
        
        $role = $roleModel->getRole($id);
        
        if ($role) {
            $this->jsonSuccess($role);
        } else {
            $this->jsonError('角色不存在');
        }
    }
    
    /**
     * 管理员用户列表路由
     */
    public function admin_users($action = 'index')
    {
        $this->checkAdmin();
        
        switch ($action) {
            case 'assignRole':
                $this->adminUsersAssignRole();
                break;
            case 'revokeRole':
                $this->adminUsersRevokeRole();
                break;
            case 'getRoles':
                $this->adminUsersGetRoles();
                break;
            default:
                $this->_adminUsers();
        }
    }
    
    /**
     * 管理员用户列表
     */
    public function _adminUsers()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'content/user/UserModel.php';
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        
        $userModel = new UserModel();
        $roleModel = new AdminRoleModel();
        
        $users = $userModel->getAdminUsers();
        
        foreach ($users as &$user) {
            $user['roles'] = $roleModel->getUserRoles($user['id']);
        }
        
        $roles = $roleModel->getAllRoles();
        
        $this->view->setLayout('admin');
        $this->render('admin/admin_users', [
            'users' => $users,
            'roles' => $roles
        ]);
    }
    
    /**
     * 为管理员分配角色
     */
    public function adminUsersAssignRole()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $userId = (int)Helper::post('user_id');
        $roleId = (int)Helper::post('role_id');
        
        if ($userId <= 0 || $roleId <= 0) {
            $this->jsonError('参数错误');
        }
        
        $success = $roleModel->assignRole($userId, $roleId);
        
        if ($success) {
            $this->jsonSuccess(null, '分配成功');
        } else {
            $this->jsonError('分配失败，可能已存在');
        }
    }
    
    /**
     * 取消管理员角色
     */
    public function adminUsersRevokeRole()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $userId = (int)Helper::post('user_id');
        $roleId = (int)Helper::post('role_id');
        
        if ($userId <= 0 || $roleId <= 0) {
            $this->jsonError('参数错误');
        }
        
        $success = $roleModel->revokeRole($userId, $roleId);
        
        if ($success) {
            $this->jsonSuccess(null, '取消成功');
        } else {
            $this->jsonError('取消失败');
        }
    }
    
    /**
     * 获取用户的角色列表
     */
    public function adminUsersGetRoles()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'admin/AdminRoleModel.php';
        $roleModel = new AdminRoleModel();
        
        $userId = (int)Helper::get('user_id');
        
        if ($userId <= 0) {
            $this->jsonError('参数错误');
        }
        
        $roles = $roleModel->getUserRoles($userId);
        $roleIds = array_column($roles, 'id');
        
        $this->jsonSuccess($roleIds);
    }

    /**
     * 附件管理页面
     */
    public function attachments()
    {
        $this->checkAdmin();

        require_once ROOT_PATH . 'service/AttachmentService.php';
        $attachmentService = new AttachmentService();

        $type = Helper::get('type', '');
        $type = $type !== '' ? trim($type) : null;
        $page = (int)Helper::get('page', 1);
        $page = max(1, $page);

        $usedStatusParam = Helper::get('used_status', '');
        $usedStatus = null;
        if ($usedStatusParam !== '') {
            $usedStatus = (int)$usedStatusParam;
            if (!in_array($usedStatus, [0, 1])) {
                $usedStatus = null;
            }
        }

        $keyword = trim(Helper::get('keyword', ''));

        $result = $attachmentService->getAttachments($type, $page, 20, $usedStatus, $keyword);
        $stats = $attachmentService->getStats();

        $this->view->setLayout('admin');
        $this->render('admin/attachments', [
            'attachments' => $result['items'],
            'page' => $result['page'],
            'totalPages' => $result['totalPages'],
            'total' => $result['total'],
            'type' => $type,
            'usedStatus' => $usedStatus,
            'keyword' => $keyword,
            'stats' => $stats,
            'baseUrl' => defined('SITE_URL') && SITE_URL ? SITE_URL : '/'
        ]);
    }
    
    /**
     * 获取附件统计信息
     */
    public function attachmentStats()
    {
        $this->checkAdmin();
        
        require_once ROOT_PATH . 'service/AttachmentService.php';
        $attachmentService = new AttachmentService();
        
        $stats = $attachmentService->getStats();
        
        $this->jsonSuccess($stats);
    }
    
    /**
     * 删除单个附件
     */
    public function doAttachmentDelete()
    {
        $this->checkAdmin();

        if (!Helper::verifyCsrf()) {
            $this->setFlash('error', '安全验证失败');
            $this->redirect(Helper::url('admin/attachments'));
            return;
        }

        $path = Helper::post('path');

        if (empty($path)) {
            $this->setFlash('error', '文件路径不能为空');
            $this->redirect(Helper::url('admin/attachments'));
            return;
        }

        require_once ROOT_PATH . 'service/AttachmentService.php';
        $attachmentService = new AttachmentService();

        if ($attachmentService->deleteFile($path)) {
            $this->setFlash('success', '删除成功');
        } else {
            $this->setFlash('error', '删除失败，文件可能不存在或无权删除');
        }

        $this->redirect(Helper::url('admin/attachments'));
    }

    /**
     * 批量删除未使用附件
     */
    public function doAttachmentDeleteUnused()
    {
        $this->checkAdmin();

        if (!Helper::verifyCsrf()) {
            $this->setFlash('error', '安全验证失败');
            $this->redirect(Helper::url('admin/attachments'));
            return;
        }

        $type = Helper::post('type', null);
        $olderThanDays = (int)Helper::post('older_than_days', 0);

        require_once ROOT_PATH . 'service/AttachmentService.php';
        $attachmentService = new AttachmentService();

        $count = $attachmentService->deleteUnused($type, $olderThanDays);

        $this->setFlash('success', '已删除 ' . $count . ' 个未使用的附件');
        $this->redirect(Helper::url('admin/attachments'));
    }

    /**
     * 批量删除附件
     */
    public function doAttachmentDeleteBatch()
    {
        $this->checkAdmin();

        if (!Helper::verifyCsrf()) {
            $this->setFlash('error', '安全验证失败');
            $this->redirect(Helper::url('admin/attachments'));
            return;
        }

        $pathsJson = Helper::post('paths');
        if (empty($pathsJson)) {
            $this->setFlash('error', '请选择要删除的文件');
            $this->redirect(Helper::url('admin/attachments'));
            return;
        }

        $paths = json_decode($pathsJson, true);
        if (!is_array($paths) || empty($paths)) {
            $this->setFlash('error', '文件列表无效');
            $this->redirect(Helper::url('admin/attachments'));
            return;
        }

        require_once ROOT_PATH . 'service/AttachmentService.php';
        $attachmentService = new AttachmentService();

        $count = 0;
        $failed = [];
        foreach ($paths as $path) {
            $path = trim($path);
            if (empty($path)) continue;

            if ($attachmentService->deleteFile($path)) {
                $count++;
            } else {
                $failed[] = $path;
            }
        }

        if ($count > 0) {
            $msg = '成功删除 ' . $count . ' 个文件';
            if (!empty($failed)) {
                $msg .= '，' . count($failed) . ' 个文件删除失败';
            }
            $this->setFlash('success', $msg);
        } else {
            $this->setFlash('error', '删除失败');
        }

        $this->redirect(Helper::url('admin/attachments'));
    }
    
    /**
     * 清理缓存页面
     */
    public function clearCache()
    {
        $this->checkAdmin();
        
        // 确保 CSRF token 已生成
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = Helper::generateToken();
        }
        
        require_once ROOT_PATH . 'service/CacheService.php';
        $cacheService = new CacheService();
        
        $cacheSize = $cacheService->getCacheSize();
        $cacheSizeFormatted = CacheService::formatSize($cacheSize);
        
        $this->view->setLayout('admin');
        $this->render('admin/clear_cache', [
            'cacheSize' => $cacheSizeFormatted,
            'cacheSizeRaw' => $cacheSize
        ]);
    }
    
    /**
     * 执行清理缓存
     */
    public function clearCacheDo()
    {
        error_log("clearCacheDo called");
        $this->checkAdmin();
        error_log("after checkAdmin");
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        require_once ROOT_PATH . 'service/CacheService.php';
        $cacheService = new CacheService();
        
        try {
            $results = $cacheService->clearAll();
            error_log("clearAll results: " . json_encode($results));
            
            $totalCount = 0;
            $details = [];
            
            foreach ($results as $key => $count) {
                if (is_numeric($count)) {
                    $totalCount += $count;
                    $labels = [
                        'temp' => '临时文件',
                        'cache' => '缓存文件',
                        'thumbnails' => '缩略图',
                        'setting' => '设置缓存',
                        'template' => '模板缓存'
                    ];
                    $details[] = ($labels[$key] ?? $key) . '：' . $count . ' 个';
                }
            }
            
            if ($totalCount > 0) {
                $this->jsonSuccess([
                    'count' => $totalCount,
                    'details' => $details
                ], '清理成功，共清理 ' . $totalCount . ' 个文件');
            } else {
                $this->jsonSuccess(null, '没有需要清理的缓存');
            }
        } catch (Exception $e) {
            $this->jsonError('清理失败：' . $e->getMessage());
        }
    }
}
