<?php
/**
 * HuSNS - 一款免费开源的社交平台
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 * @声明    严禁用于违法违规用途
 */
class UserModel extends Model
{
    protected $table = 'users';

    public function findByUsername($username)
    {
        return $this->db->fetch("SELECT * FROM __PREFIX__users WHERE username = ?", [$username]);
    }

    public function findByEmail($email)
    {
        return $this->db->fetch("SELECT * FROM __PREFIX__users WHERE email = ?", [$email]);
    }

    public function register($data)
    {
        $data['password'] = Security::hashPassword($data['password']);
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $data['status'] = 1;
        $data['is_admin'] = 0;
        // 设置默认头像（使用静态资源目录）
        $data['avatar'] = 'static/images/avatar_default.png';
        
        return $this->insert($data);
    }

    public function login($username, $password)
    {
        $user = $this->findByUsername($username);
        
        if (!$user) {
            return false;
        }

        if ($user['status'] != 1) {
            return false;
        }

        if (!Security::verifyPassword($password, $user['password'])) {
            return false;
        }

        return $user;
    }

    public function updateProfile($id, $data)
    {
        $data['updated_at'] = time();
        return $this->update($id, $data);
    }

    public function updatePassword($id, $oldPassword, $newPassword)
    {
        $user = $this->find($id);
        
        if (!$user) {
            return false;
        }

        if (!Security::verifyPassword($oldPassword, $user['password'])) {
            return false;
        }

        return $this->update($id, [
            'password' => Security::hashPassword($newPassword),
            'updated_at' => time()
        ]);
    }

    public function getFollowers($userId)
    {
        $sql = "SELECT u.* FROM __PREFIX__users u 
                INNER JOIN __PREFIX__follows f ON u.id = f.user_id 
                WHERE f.follow_id = ?";
        return $this->db->fetchAll($sql, [$userId]);
    }

    public function getFollowing($userId)
    {
        $sql = "SELECT u.* FROM __PREFIX__users u 
                INNER JOIN __PREFIX__follows f ON u.id = f.follow_id 
                WHERE f.user_id = ?";
        return $this->db->fetchAll($sql, [$userId]);
    }

    public function getFollowCount($userId)
    {
        $following = $this->db->count('follows', 'user_id = ?', [$userId]);
        $followers = $this->db->count('follows', 'follow_id = ?', [$userId]);
        
        return [
            'following' => $following,
            'followers' => $followers
        ];
    }
    
    /**
     * 更新用户最后活跃时间
     */
    public function updateLastActivity($userId)
    {
        if (!$userId) return false;
        return $this->update($userId, ['last_activity' => time()]);
    }
    
    /**
     * 检查用户是否在线（最近5分钟内活跃）
     */
    public function isOnline($userId)
    {
        if (!$userId) return false;
        $user = $this->find($userId);
        if (!$user) return false;
        // 5分钟内活跃视为在线
        return isset($user['last_activity']) && (time() - $user['last_activity']) < 300;
    }

    public function isFollowing($userId, $targetId)
    {
        return $this->db->count('follows', 'user_id = ? AND follow_id = ?', [$userId, $targetId]) > 0;
    }

    public function follow($userId, $targetId)
    {
        if ($userId == $targetId) {
            return false;
        }

        if ($this->isFollowing($userId, $targetId)) {
            return false;
        }

        return $this->db->insert('follows', [
            'user_id' => $userId,
            'follow_id' => $targetId,
            'created_at' => time()
        ]);
    }

    public function unfollow($userId, $targetId)
    {
        return $this->db->delete('follows', 'user_id = ? AND follow_id = ?', [$userId, $targetId]);
    }

    public function isBanned($userId)
    {
        $user = $this->find($userId);
        
        if (!$user) {
            return false;
        }
        
        $banType = isset($user['ban_type']) ? (int)$user['ban_type'] : 0;
        $banUntil = isset($user['ban_until']) ? (int)$user['ban_until'] : 0;
        
        if ($banType === 0) {
            return false;
        }
        
        if ($banType === 1) {
            if ($banUntil === 0) {
                return true;
            }
            if ($banUntil > time()) {
                return true;
            }
            return false;
        }
        
        if ($banType === 2) {
            return true;
        }
        
        return false;
    }

    public function getBanInfo($userId)
    {
        $user = $this->find($userId);
        
        if (!$user) {
            return null;
        }
        
        $banType = isset($user['ban_type']) ? (int)$user['ban_type'] : 0;
        $banUntil = isset($user['ban_until']) ? (int)$user['ban_until'] : 0;
        $banReason = isset($user['ban_reason']) ? $user['ban_reason'] : '';
        
        if ($banType === 0) {
            return null;
        }
        
        if ($banType === 1 && $banUntil > 0 && $banUntil < time()) {
            return null;
        }
        
        return [
            'type' => $banType,
            'until' => $banUntil,
            'reason' => $banReason,
            'type_text' => $banType === 1 ? '禁言' : '封禁',
            'until_text' => $banUntil === 0 ? '永久' : date('Y-m-d H:i', $banUntil)
        ];
    }

    public function searchUsers($keyword, $limit = 10)
    {
        $keyword = '%' . $keyword . '%';
        $sql = "SELECT id, username, avatar FROM __PREFIX__users 
                WHERE status = 1 AND username LIKE ? 
                ORDER BY id DESC 
                LIMIT ?";
        return $this->db->fetchAll($sql, [$keyword, $limit]);
    }

    public function searchFollowing($userId, $keyword, $limit = 10)
    {
        $keyword = '%' . $keyword . '%';
        $sql = "SELECT u.id, u.username, u.avatar
                FROM __PREFIX__users u
                INNER JOIN __PREFIX__follows f ON u.id = f.follow_id
                WHERE f.user_id = ? AND u.status = 1 AND u.username LIKE ?
                ORDER BY u.id DESC
                LIMIT ?";
        return $this->db->fetchAll($sql, [$userId, $keyword, $limit]);
    }

    /**
     * 获取在线用户列表
     * @param int $limit 返回数量
     * @return array
     */
    public function getOnlineUsers($limit = 10)
    {
        $onlineTime = time() - 5 * 60; // 5分钟内活跃视为在线
        $sql = "SELECT id, username, avatar 
                FROM __PREFIX__users 
                WHERE status = 1 
                  AND last_activity >= ?
                ORDER BY last_activity DESC
                LIMIT ?";
        return $this->db->fetchAll($sql, [$onlineTime, $limit]);
    }
    
    /**
     * 获取在线用户数量
     * @return int
     */
    public function getOnlineCount()
    {
        $onlineTime = time() - 5 * 60; // 5分钟内活跃视为在线
        $sql = "SELECT COUNT(*) as count 
                FROM __PREFIX__users 
                WHERE status = 1 
                  AND last_activity >= ?";
        $result = $this->db->fetch($sql, [$onlineTime]);
        return (int)($result['count'] ?? 0);
    }
    
    /**
     * 获取活跃用户列表（按积分排序）
     * @param int $limit 返回数量
     * @return array
     */
    public function getActiveUsers($limit = 10)
    {
        $sql = "SELECT id, username, avatar, points 
                FROM __PREFIX__users 
                WHERE status = 1 
                  AND is_admin = 0
                ORDER BY points DESC
                LIMIT ?";
        return $this->db->fetchAll($sql, [$limit]);
    }
    
    /**
     * 获取管理员用户列表
     * @return array
     */
    public function getAdminUsers()
    {
        $sql = "SELECT id, username, avatar, email, created_at 
                FROM __PREFIX__users 
                WHERE status = 1 
                  AND is_admin = 1
                ORDER BY created_at DESC";
        return $this->db->fetchAll($sql);
    }
    
    /**
     * 获取推荐用户
     * @param int $userId 当前用户ID
     * @param int $limit 返回数量
     * @return array
     */
    public function getRecommendedUsers($userId, $limit = 10)
    {
        // 获取用户已经关注的用户ID
        $followingIds = [];
        $following = $this->getFollowing($userId);
        foreach ($following as $user) {
            $followingIds[] = $user['id'];
        }
        $followingIds[] = $userId;
        
        $followingIdsStr = implode(',', $followingIds);
        
        // 7天内活跃的时间戳
        $activeDays = 7;
        $activeTime = time() - ($activeDays * 24 * 60 * 60);
        
        // 推荐用户条件：
        // 1. 排除已关注的用户和本人
        // 2. 用户状态正常
        // 3. 排除管理员
        // 4. 头像完整（必须设置头像）
        // 5. 发布过至少1条帖子
        // 6. 积分达到100分以上
        // 7. 7天内有活跃记录
        $sql = "SELECT u.id, u.username, u.avatar, 
                       (SELECT COUNT(*) FROM __PREFIX__follows f WHERE f.follow_id = u.id) as followers_count,
                       (SELECT COUNT(*) FROM __PREFIX__posts p WHERE p.user_id = u.id AND p.status = 1) as post_count,
                       u.points
                FROM __PREFIX__users u
                INNER JOIN __PREFIX__posts p ON p.user_id = u.id AND p.status = 1
                WHERE u.id NOT IN ({$followingIdsStr})
                  AND u.status = 1
                  AND u.is_admin = 0
                  AND u.avatar IS NOT NULL 
                  AND u.avatar != ''
                  AND u.points >= 100
                  AND u.last_activity >= ?
                GROUP BY u.id
                HAVING post_count >= 1
                ORDER BY followers_count DESC, u.points DESC, u.last_activity DESC
                LIMIT ?";
        
        return $this->db->fetchAll($sql, [$activeTime, $limit]);
    }

    /**
     * 发送私信
     * @param int $senderId 发送者ID
     * @param int $receiverId 接收者ID
     * @param string $content 内容
     * @return bool
     */
    public function sendMessage($senderId, $receiverId, $content)
    {
        $db = Database::getInstance();

        $messageId = $db->insert('private_messages', [
            'sender_id' => $senderId,
            'receiver_id' => $receiverId,
            'content' => $content,
            'created_at' => time(),
            'is_read' => 0,
            'status' => 1
        ]);

        if ($messageId) {
            Point::change($senderId, 'send_message', 'message', $messageId);
            
            // 发送私信通知
            try {
                require_once __DIR__ . '/../notification/NotificationModel.php';
                $notificationModel = new NotificationModel();
                $sender = $this->find($senderId);
                if ($sender) {
                    $notificationModel->sendMessageNotification($receiverId, $senderId, $sender['username'], $content);
                }
            } catch (\Exception $e) {
                // 忽略通知发送失败的错误
            }
            
            return true;
        }

        return false;
    }
}
