<?php
/**
 * HuSNS - 圈子模型
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 */
class CircleModel extends Model
{
    protected $table = 'circles';
    
    /**
     * 创建圈子
     * @param array $data 圈子数据
     * @return int|bool 圈子ID或false
     */
    public function createCircle($data)
    {
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $data['member_count'] = 0;
        $data['post_count'] = 0;
        
        $circleId = $this->insert($data);
        
        if ($circleId && isset($data['user_id'])) {
            // 添加创建者为管理员
            $this->addMember($circleId, $data['user_id'], 2);
        }
        
        return $circleId;
    }
    
    /**
     * 更新圈子信息
     * @param int $id 圈子ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateCircle($id, $data)
    {
        $data['updated_at'] = time();
        return $this->update($id, $data);
    }
    
    /**
     * 删除圈子（软删除）
     * @param int $id 圈子ID
     * @return bool
     */
    public function deleteCircle($id)
    {
        return $this->update($id, ['status' => 0, 'updated_at' => time()]);
    }
    
    /**
     * 获取圈子详情
     * @param int $id 圈子ID
     * @return array|null
     */
    public function getCircle($id)
    {
        return $this->db->fetch(
            "SELECT * FROM __PREFIX__circles WHERE id = ? AND status = 1",
            [$id]
        );
    }

    /**
     * 根据ID获取圈子详情（getCircle的别名）
     * @param int $id 圈子ID
     * @return array|null
     */
    public function getCircleById($id)
    {
        return $this->getCircle($id);
    }
    
    /**
     * 获取圈子列表
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @param string $keyword 关键词
     * @param int $status 状态筛选
     * @return array
     */
    public function getCircles($page = 1, $pageSize = 20, $keyword = '', $status = -1)
    {
        $offset = ($page - 1) * $pageSize;
        
        $where = [];
        $params = [];
        
        if ($status >= 0) {
            $where[] = 'c.status = ?';
            $params[] = $status;
        }
        
        if (!empty($keyword)) {
            $where[] = '(c.name LIKE ? OR c.description LIKE ?)';
            $params[] = "%{$keyword}%";
            $params[] = "%{$keyword}%";
        }
        
        $whereStr = $where ? 'WHERE ' . implode(' AND ', $where) : '';
        
        $sql = "SELECT c.*, 0 as member_count, 0 as post_count, IFNULL(c.is_verified, 0) as is_verified
                FROM __PREFIX__circles c
                {$whereStr}
                ORDER BY IFNULL(c.is_verified, 0) DESC, c.created_at DESC
                LIMIT ?, ?";
        
        $params[] = $offset;
        $params[] = $pageSize;
        
        $circles = $this->db->fetchAll($sql, $params);
        
        $total = $this->countCircles($keyword, $status);
        $totalPages = ceil($total / $pageSize);
        
        return [
            'items' => $circles,
            'total' => $total,
            'page' => $page,
            'pageSize' => $pageSize,
            'totalPages' => $totalPages
        ];
    }
    
    /**
     * 统计圈子数量
     * @param string $keyword 关键词
     * @param int $status 状态
     * @return int
     */
    public function countCircles($keyword = '', $status = -1)
    {
        $where = [];
        $params = [];
        
        if ($status >= 0) {
            $where[] = 'status = ?';
            $params[] = $status;
        }
        
        if (!empty($keyword)) {
            $where[] = '(name LIKE ? OR description LIKE ?)';
            $params[] = "%{$keyword}%";
            $params[] = "%{$keyword}%";
        }
        
        $whereStr = $where ? 'WHERE ' . implode(' AND ', $where) : '';
        
        $sql = "SELECT COUNT(*) as count FROM __PREFIX__circles c {$whereStr}";
        $result = $this->db->fetch($sql, $params);
        
        return (int)($result['count'] ?? 0);
    }
    
    /**
     * 添加成员
     * @param int $circleId 圈子ID
     * @param int $userId 用户ID
     * @param int $role 角色
     * @return bool
     */
    public function addMember($circleId, $userId, $role = 0)
    {
        // 检查是否已加入
        $exists = $this->db->count(
            'circle_members',
            'circle_id = ? AND user_id = ?',
            [$circleId, $userId]
        );
        
        if ($exists > 0) {
            return true;
        }
        
        $result = $this->db->insert('circle_members', [
            'circle_id' => $circleId,
            'user_id' => $userId,
            'role' => $role,
            'created_at' => time()
        ]);
        
        if ($result) {
            // 更新成员数
            $this->db->query(
                "UPDATE __PREFIX__circles SET member_count = member_count + 1 WHERE id = ?",
                [$circleId]
            );
        }
        
        return $result;
    }
    
    /**
     * 移除成员
     * @param int $circleId 圈子ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function removeMember($circleId, $userId)
    {
        $result = $this->db->delete(
            'circle_members',
            'circle_id = ? AND user_id = ?',
            [$circleId, $userId]
        );
        
        if ($result) {
            $this->db->query(
                "UPDATE __PREFIX__circles SET member_count = GREATEST(0, member_count - 1) WHERE id = ?",
                [$circleId]
            );
        }
        
        return $result;
    }
    
    /**
     * 获取圈子成员列表
     * @param int $circleId 圈子ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getMembers($circleId, $page = 1, $pageSize = 20)
    {
        $offset = ($page - 1) * $pageSize;
        
        $sql = "SELECT cm.*, u.username, u.avatar
                FROM __PREFIX__circle_members cm
                INNER JOIN __PREFIX__users u ON cm.user_id = u.id
                WHERE cm.circle_id = ?
                ORDER BY cm.role DESC, cm.created_at DESC
                LIMIT ?, ?";
        
        $members = $this->db->fetchAll($sql, [$circleId, $offset, $pageSize]);
        
        $total = $this->db->count('circle_members', 'circle_id = ?', [$circleId]);
        $totalPages = ceil($total / $pageSize);
        
        return [
            'items' => $members,
            'total' => $total,
            'page' => $page,
            'pageSize' => $pageSize,
            'totalPages' => $totalPages
        ];
    }
    
    /**
     * 检查用户是否是圈子成员
     * @param int $circleId 圈子ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function isMember($circleId, $userId)
    {
        return $this->db->count(
            'circle_members',
            'circle_id = ? AND user_id = ?',
            [$circleId, $userId]
        ) > 0;
    }
    
    /**
     * 用户加入圈子
     * @param int $circleId 圈子ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function joinCircle($circleId, $userId)
    {
        $exists = $this->db->count(
            'circle_members',
            'circle_id = ? AND user_id = ?',
            [$circleId, $userId]
        );
        
        if ($exists > 0) {
            return true;
        }
        
        $result = $this->db->insert('circle_members', [
            'circle_id' => $circleId,
            'user_id' => $userId,
            'role' => 0,
            'created_at' => time()
        ]);
        
        if ($result) {
            $this->db->query(
                "UPDATE __PREFIX__circles SET member_count = member_count + 1 WHERE id = ?",
                [$circleId]
            );
        }
        
        return $result;
    }
    
    /**
     * 获取用户的角色
     * @param int $circleId 圈子ID
     * @param int $userId 用户ID
     * @return int
     */
    public function getMemberRole($circleId, $userId)
    {
        $result = $this->db->fetch(
            "SELECT role FROM __PREFIX__circle_members WHERE circle_id = ? AND user_id = ?",
            [$circleId, $userId]
        );
        
        return (int)($result['role'] ?? 0);
    }
    
    /**
     * 更新成员角色
     * @param int $circleId 圈子ID
     * @param int $userId 用户ID
     * @param int $role 角色
     * @return bool
     */
    public function updateMemberRole($circleId, $userId, $role)
    {
        return $this->db->update(
            'circle_members',
            ['role' => $role],
            'circle_id = ? AND user_id = ?',
            [$circleId, $userId]
        );
    }
    
    /**
     * 添加帖子到圈子
     * @param int $circleId 圈子ID
     * @param int $postId 帖子ID
     * @return bool
     */
    public function addPost($circleId, $postId)
    {
        $exists = $this->db->count(
            'circle_posts',
            'circle_id = ? AND post_id = ?',
            [$circleId, $postId]
        );
        
        if ($exists > 0) {
            return true;
        }
        
        $result = $this->db->insert('circle_posts', [
            'circle_id' => $circleId,
            'post_id' => $postId,
            'created_at' => time()
        ]);
        
        if ($result) {
            $this->db->query(
                "UPDATE __PREFIX__circles SET post_count = post_count + 1 WHERE id = ?",
                [$circleId]
            );
        }
        
        return $result;
    }
    
    /**
     * 移除帖子
     * @param int $circleId 圈子ID
     * @param int $postId 帖子ID
     * @return bool
     */
    public function removePost($circleId, $postId)
    {
        $result = $this->db->delete(
            'circle_posts',
            'circle_id = ? AND post_id = ?',
            [$circleId, $postId]
        );
        
        if ($result) {
            $this->db->query(
                "UPDATE __PREFIX__circles SET post_count = GREATEST(0, post_count - 1) WHERE id = ?",
                [$circleId]
            );
        }
        
        return $result;
    }
    
    /**
     * 获取圈子帖子列表
     * @param int $circleId 圈子ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getCirclePosts($circleId, $page = 1, $pageSize = 20)
    {
        $offset = ($page - 1) * $pageSize;
        
        $sql = "SELECT p.*, p.user_id, u.username, u.avatar
                FROM __PREFIX__circle_posts cp
                INNER JOIN __PREFIX__posts p ON cp.post_id = p.id
                INNER JOIN __PREFIX__users u ON p.user_id = u.id
                WHERE cp.circle_id = ? AND p.status = 1
                ORDER BY p.created_at DESC
                LIMIT ?, ?";
        
        $posts = $this->db->fetchAll($sql, [$circleId, $offset, $pageSize]);
        
        $total = $this->db->fetch(
            "SELECT COUNT(*) as count FROM __PREFIX__circle_posts cp 
             INNER JOIN __PREFIX__posts p ON cp.post_id = p.id 
             WHERE cp.circle_id = ? AND p.status = 1",
            [$circleId]
        );
        
        $totalPages = ceil(($total['count'] ?? 0) / $pageSize);
        
        return [
            'items' => $posts,
            'total' => $total['count'] ?? 0,
            'page' => $page,
            'pageSize' => $pageSize,
            'totalPages' => $totalPages
        ];
    }
    
    /**
     * 增加浏览量
     * @param int $circleId 圈子ID
     * @return bool
     */
    public function incrementViewCount($circleId)
    {
        // 浏览量功能暂时注释，数据库表没有 view_count 字段
        return true;
    }
    
    /**
     * 获取热门圈子
     * @param int $limit 数量
     * @return array
     */
    public function getHotCircles($limit = 10)
    {
        $sql = "SELECT c.*, 
                       (SELECT COUNT(*) FROM __PREFIX__circle_members cm WHERE cm.circle_id = c.id) as member_count,
                       (SELECT COUNT(*) FROM __PREFIX__circle_posts cp WHERE cp.circle_id = c.id) as post_count
                FROM __PREFIX__circles c
                WHERE c.status = 1 AND c.is_private = 0
                ORDER BY member_count DESC, post_count DESC
                LIMIT ?";
        
        return $this->db->fetchAll($sql, [$limit]);
    }
    
    /**
     * 获取用户加入的圈子
     * @param int $userId 用户ID
     * @param int $limit 数量
     * @return array
     */
    public function getUserCircles($userId, $limit = 20)
    {
        $sql = "SELECT c.*, cm.role, cm.created_at
                FROM __PREFIX__circle_members cm
                INNER JOIN __PREFIX__circles c ON cm.circle_id = c.id
                WHERE cm.user_id = ? AND c.status = 1
                ORDER BY cm.created_at DESC
                LIMIT ?";
        
        return $this->db->fetchAll($sql, [$userId, $limit]);
    }
}
?>