<?php
/**
 * HuSNS - 统计服务类
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 */
class StatisticsService
{
    private $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    /**
     * 获取概览统计数据
     */
    public function getOverview()
    {
        $prefix = $this->db->getPrefix();
        
        $stats = [
            'users' => $this->db->count('users', 'status = 1'),
            'posts' => $this->db->count('posts', 'status = 1'),
            'comments' => $this->db->count('comments', 'status = 1'),
            'today_users' => $this->db->count('users', 'status = 1 AND created_at > ?', [strtotime('today')]),
            'today_posts' => $this->db->count('posts', 'status = 1 AND created_at > ?', [strtotime('today')]),
            'today_comments' => $this->db->count('comments', 'status = 1 AND created_at > ?', [strtotime('today')]),
            'online_users' => $this->getOnlineCount(),
        ];
        
        return $stats;
    }
    
    /**
     * 获取在线用户数量
     */
    public function getOnlineCount()
    {
        $onlineTime = time() - 5 * 60; // 5分钟内活跃视为在线
        return $this->db->count('users', 'status = 1 AND last_activity >= ?', [$onlineTime]);
    }
    
    /**
     * 获取用户增长趋势（按天）
     * @param int $days 天数
     */
    public function getUserGrowth($days = 7)
    {
        $result = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i day"));
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            
            $count = $this->db->count('users', 'created_at >= ? AND created_at <= ?', [$startTime, $endTime]);
            $result[] = [
                'date' => $date,
                'count' => $count
            ];
        }
        return $result;
    }
    
    /**
     * 获取内容发布趋势（按天）
     * @param int $days 天数
     */
    public function getContentTrend($days = 7)
    {
        $result = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i day"));
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            
            $posts = $this->db->count('posts', 'status = 1 AND created_at >= ? AND created_at <= ?', [$startTime, $endTime]);
            $comments = $this->db->count('comments', 'status = 1 AND created_at >= ? AND created_at <= ?', [$startTime, $endTime]);
            
            $result[] = [
                'date' => $date,
                'posts' => $posts,
                'comments' => $comments
            ];
        }
        return $result;
    }
    
    /**
     * 获取活跃用户排行
     * @param int $limit 数量
     */
    public function getActiveUsers($limit = 10)
    {
        $sql = "SELECT u.id, u.username, u.avatar, u.points,
                       (SELECT COUNT(*) FROM {$this->db->getPrefix()}posts p WHERE p.user_id = u.id AND p.status = 1) as post_count,
                       (SELECT COUNT(*) FROM {$this->db->getPrefix()}comments c WHERE c.user_id = u.id AND c.status = 1) as comment_count
                FROM {$this->db->getPrefix()}users u
                WHERE u.status = 1
                ORDER BY (post_count + comment_count) DESC
                LIMIT ?";
        
        return $this->db->fetchAll($sql, [$limit]);
    }
    
    /**
     * 获取热门话题排行
     * @param int $limit 数量
     */
    public function getHotTopics($limit = 10)
    {
        $sql = "SELECT t.name, t.is_pinned,
                       COUNT(DISTINCT p.id) as post_count
                FROM {$this->db->getPrefix()}topics t
                LEFT JOIN {$this->db->getPrefix()}posts p ON p.content LIKE CONCAT('%#', t.name, '#%') AND p.status = 1
                WHERE t.is_blocked = 0
                GROUP BY t.id, t.name, t.is_pinned
                ORDER BY t.is_pinned DESC, post_count DESC
                LIMIT ?";
        
        return $this->db->fetchAll($sql, [$limit]);
    }
    
    /**
     * 获取热门帖子
     * @param int $limit 数量
     */
    public function getHotPosts($limit = 10)
    {
        $sql = "SELECT p.id, p.content, p.likes, p.comments, p.reposts, p.created_at,
                       u.username, u.avatar
                FROM {$this->db->getPrefix()}posts p
                INNER JOIN {$this->db->getPrefix()}users u ON p.user_id = u.id
                WHERE p.status = 1
                ORDER BY (p.likes + p.comments + p.reposts) DESC
                LIMIT ?";
        
        $posts = $this->db->fetchAll($sql, [$limit]);
        
        foreach ($posts as &$post) {
            $post['content'] = mb_substr(strip_tags($post['content']), 0, 50);
        }
        
        return $posts;
    }
    
    /**
     * 获取举报统计
     */
    public function getReportStats()
    {
        $prefix = $this->db->getPrefix();
        
        return [
            'total' => $this->db->count('reports'),
            'pending' => $this->db->count('reports', 'status = 0'),
            'handled' => $this->db->count('reports', 'status = 1'),
            'rejected' => $this->db->count('reports', 'status = 2'),
        ];
    }
    
    /**
     * 获取用户活跃度分布
     */
    public function getUserActivityDistribution()
    {
        $prefix = $this->db->getPrefix();
        
        $sql = "SELECT 
                    CASE 
                        WHEN last_activity >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) THEN '1小时内'
                        WHEN last_activity >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN '1天内'
                        WHEN last_activity >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY)) THEN '1周内'
                        WHEN last_activity >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) THEN '1月内'
                        ELSE '1月以上'
                    END as period,
                    COUNT(*) as count
                FROM {$prefix}users
                WHERE status = 1
                GROUP BY period
                ORDER BY 
                    CASE period 
                        WHEN '1小时内' THEN 1
                        WHEN '1天内' THEN 2
                        WHEN '1周内' THEN 3
                        WHEN '1月内' THEN 4
                        ELSE 5
                    END";
        
        return $this->db->fetchAll($sql);
    }
    
    /**
     * 获取帖子来源分布
     */
    public function getPostSourceDistribution()
    {
        $prefix = $this->db->getPrefix();
        
        $sql = "SELECT 
                    CASE 
                        WHEN is_anonymous = 1 THEN '匿名发布'
                        WHEN repost_id > 0 THEN '转发'
                        ELSE '原创'
                    END as type,
                    COUNT(*) as count,
                    ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM {$prefix}posts WHERE status = 1), 1) as percentage
                FROM {$prefix}posts
                WHERE status = 1
                GROUP BY type";
        
        return $this->db->fetchAll($sql);
    }
    
    /**
     * 获取每日活跃时段分布
     */
    public function getHourlyActivity()
    {
        $prefix = $this->db->getPrefix();
        
        $sql = "SELECT 
                    HOUR(FROM_UNIXTIME(created_at)) as hour,
                    COUNT(*) as count
                FROM {$prefix}posts
                WHERE status = 1 AND created_at >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))
                GROUP BY hour
                ORDER BY hour";
        
        $result = $this->db->fetchAll($sql);
        
        // 确保24小时都有数据
        $hourly = array_fill(0, 24, 0);
        foreach ($result as $row) {
            $hourly[$row['hour']] = $row['count'];
        }
        
        return $hourly;
    }
}
?>