<?php
/**
 * HuSNS - 圈子控制器
 * 
 * @author  HYR
 * @QQ      281900864
 * @website https://huyourui.com
 * @license MIT
 */
class CircleController extends Controller
{
    private $circleModel;
    private $userModel;
    
    public function __construct()
    {
        parent::__construct();
        $this->circleModel = new CircleModel();
        $this->userModel = new UserModel();
    }
    
    /**
     * 后台圈子列表
     */
    public function adminIndex()
    {
        $this->checkAdmin();
        
        $page = (int)Helper::get('page', 1);
        $keyword = Helper::get('keyword', '');
        $status = (int)Helper::get('status', -1);
        
        $result = $this->circleModel->getCircles($page, 20, $keyword, $status);
        
        $this->view->setLayout('admin');
        $this->render('admin/circles', [
            'circles' => $result['items'],
            'page' => $result['page'],
            'totalPages' => $result['totalPages'],
            'total' => $result['total'],
            'keyword' => $keyword,
            'status' => $status
        ]);
    }
    
    /**
     * 后台添加圈子页面
     */
    public function adminAdd()
    {
        $this->checkAdmin();
        
        if ($this->isPost()) {
            if (!Helper::verifyCsrf()) {
                $this->setFlash('error', '安全验证失败');
                $this->redirect(Helper::url('admin/circles/add'));
                return;
            }
            
            $name = trim(Helper::post('name'));
            $description = trim(Helper::post('description'));
            $isPrivate = (int)Helper::post('is_private', 0);
            
            if (empty($name)) {
                $this->setFlash('error', '圈子名称不能为空');
                $this->redirect(Helper::url('admin/circles/add'));
                return;
            }
            
            $data = [
                'name' => $name,
                'description' => $description,
                'is_private' => $isPrivate,
                'status' => 1
            ];
            
            // 处理头像上传
            if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->uploadFile('avatar', 'circle');
                if ($uploadResult['success']) {
                    $data['avatar'] = $uploadResult['path'];
                }
            }
            
            // 处理封面横幅上传（使用数据库的cover字段）
            if (isset($_FILES['banner']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->uploadFile('banner', 'circle');
                if ($uploadResult['success']) {
                    $data['cover'] = $uploadResult['path'];
                }
            }
            
            $circleId = $this->circleModel->createCircle($data);
            
            if ($circleId) {
                $this->setFlash('success', '圈子创建成功');
                $this->redirect(Helper::url('admin/circles'));
            } else {
                $this->setFlash('error', '圈子创建失败');
                $this->redirect(Helper::url('admin/circles/add'));
            }
        }
        
        $this->view->setLayout('admin');
        $this->render('admin/circle_add');
    }
    
    /**
     * 后台编辑圈子页面
     */
    public function adminEdit()
    {
        $this->checkAdmin();
        
        $id = (int)Helper::get('id');
        $circle = $this->circleModel->getCircle($id);
        
        if (!$circle) {
            $this->setFlash('error', '圈子不存在');
            $this->redirect(Helper::url('admin/circles'));
            return;
        }
        
        if ($this->isPost()) {
            if (!Helper::verifyCsrf()) {
                $this->setFlash('error', '安全验证失败');
                $this->redirect(Helper::url('admin/circles/edit?id=' . $id));
                return;
            }
            
            $name = trim(Helper::post('name'));
            $description = trim(Helper::post('description'));
            $isPrivate = (int)Helper::post('is_private', 0);
            $isVerified = (int)Helper::post('is_verified', 0);
            
            if (empty($name)) {
                $this->setFlash('error', '圈子名称不能为空');
                $this->redirect(Helper::url('admin/circles/edit?id=' . $id));
                return;
            }
            
            $data = [
                'name' => $name,
                'description' => $description,
                'is_private' => $isPrivate,
                'is_verified' => $isVerified
            ];
            
            // 处理头像上传
            if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->uploadFile('avatar', 'circle');
                if ($uploadResult['success']) {
                    $data['avatar'] = $uploadResult['path'];
                }
            }
            
            // 处理封面横幅上传（使用数据库的cover字段）
            if (isset($_FILES['banner']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->uploadFile('banner', 'circle');
                if ($uploadResult['success']) {
                    $data['cover'] = $uploadResult['path'];
                }
            }
            
            $result = $this->circleModel->updateCircle($id, $data);
            
            if ($result) {
                $this->setFlash('success', '圈子更新成功');
            } else {
                $this->setFlash('error', '圈子更新失败');
            }
            
            $this->redirect(Helper::url('admin/circles/edit?id=' . $id));
        }
        
        $this->view->setLayout('admin');
        $this->render('admin/circle_edit', ['circle' => $circle]);
    }
    
    /**
     * 后台删除圈子
     */
    public function adminDelete()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $id = (int)Helper::post('id');
        $circle = $this->circleModel->getCircle($id);
        
        if (!$circle) {
            $this->jsonError('圈子不存在');
        }
        
        $result = $this->circleModel->deleteCircle($id);
        
        if ($result) {
            $this->jsonSuccess(null, '圈子已删除');
        } else {
            $this->jsonError('删除失败');
        }
    }
    
    /**
     * 后台圈子成员管理
     */
    public function adminMembers()
    {
        $this->checkAdmin();
        
        $circleId = (int)Helper::get('circle_id');
        $page = (int)Helper::get('page', 1);
        
        $circle = $this->circleModel->getCircle($circleId);
        
        if (!$circle) {
            $this->setFlash('error', '圈子不存在');
            $this->redirect(Helper::url('admin/circles'));
            return;
        }
        
        $result = $this->circleModel->getMembers($circleId, $page, 20);
        
        $this->view->setLayout('admin');
        $this->render('admin/circle_members', [
            'circle' => $circle,
            'members' => $result['items'],
            'page' => $result['page'],
            'totalPages' => $result['totalPages'],
            'total' => $result['total']
        ]);
    }
    
    /**
     * 后台更新成员角色
     */
    public function adminUpdateRole()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $circleId = (int)Helper::post('circle_id');
        $userId = (int)Helper::post('user_id');
        $role = (int)Helper::post('role');
        
        if (!in_array($role, [0, 1, 2])) {
            $this->jsonError('角色值错误');
        }
        
        $result = $this->circleModel->updateMemberRole($circleId, $userId, $role);
        
        if ($result) {
            $roleName = $role == 2 ? '创始人' : ($role == 1 ? '管理员' : '成员');
            $this->jsonSuccess(null, '角色已更新为' . $roleName);
        } else {
            $this->jsonError('更新失败');
        }
    }
    
    /**
     * 后台移除成员
     */
    public function adminRemoveMember()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $circleId = (int)Helper::post('circle_id');
        $userId = (int)Helper::post('user_id');
        
        $result = $this->circleModel->removeMember($circleId, $userId);
        
        if ($result) {
            $this->jsonSuccess(null, '成员已移除');
        } else {
            $this->jsonError('移除失败');
        }
    }
    
    /**
     * 后台圈子认证/取消认证
     */
    public function adminVerify()
    {
        $this->checkAdmin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $id = (int)Helper::post('id');
        $verified = (int)Helper::post('verified');
        $verifyType = (int)Helper::post('verify_type', 0);
        $verifyInfo = trim(Helper::post('verify_info', ''));
        
        $circle = $this->circleModel->getCircle($id);
        
        if (!$circle) {
            $this->jsonError('圈子不存在');
        }
        
        $data = ['is_verified' => $verified];
        
        if ($verified) {
            $data['verify_type'] = $verifyType;
            $data['verify_info'] = $verifyInfo;
            $data['verify_time'] = time();
            $data['verify_admin'] = $_SESSION['user_id'] ?? 0;
        } else {
            $data['verify_type'] = 0;
            $data['verify_info'] = '';
            $data['verify_time'] = 0;
            $data['verify_admin'] = 0;
        }
        
        $result = $this->circleModel->updateCircle($id, $data);
        
        if ($result) {
            $action = $verified ? '认证成功' : '取消认证成功';
            $this->jsonSuccess(null, $action);
        } else {
            $this->jsonError('操作失败');
        }
    }
    
    /**
     * 前台圈子列表页面
     */
    public function index()
    {
        $page = (int)Helper::get('page', 1);
        $keyword = Helper::get('keyword', '');
        
        $result = $this->circleModel->getCircles($page, 20, $keyword, 1);
        
        $hotCircles = $this->circleModel->getHotCircles(6);
        
        $this->render('circle/index', [
            'circles' => $result['items'],
            'page' => $result['page'],
            'totalPages' => $result['totalPages'],
            'total' => $result['total'],
            'keyword' => $keyword,
            'hotCircles' => $hotCircles
        ]);
    }
    
    /**
     * 前台圈子详情页面
     */
    public function detail()
    {
        $id = (int)Helper::get('id');
        $page = (int)Helper::get('page', 1);
        
        $circle = $this->circleModel->getCircle($id);
        
        if (!$circle) {
            $this->error('圈子不存在');
            return;
        }
        
        // 增加浏览量
        $this->circleModel->incrementViewCount($id);
        
        // 获取圈子帖子
        $postsResult = $this->circleModel->getCirclePosts($id, $page, 20);
        
        // 获取成员列表
        $membersResult = $this->circleModel->getMembers($id, 1, 8);
        
        // 检查当前用户是否是成员
        $isMember = false;
        $memberRole = 0;
        if (isset($_SESSION['user_id'])) {
            $isMember = $this->circleModel->isMember($id, $_SESSION['user_id']);
            $memberRole = $this->circleModel->getMemberRole($id, $_SESSION['user_id']);
        }
        
        $this->render('circle/detail', [
            'circle' => $circle,
            'posts' => $postsResult['items'],
            'page' => $postsResult['page'],
            'totalPages' => $postsResult['totalPages'],
            'members' => $membersResult['items'],
            'memberCount' => $membersResult['total'],
            'isMember' => $isMember,
            'memberRole' => $memberRole
        ]);
    }
    
    /**
     * 加入圈子
     */
    public function join()
    {
        $this->checkLogin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $circleId = (int)Helper::post('circle_id');
        $circle = $this->circleModel->getCircle($circleId);
        
        if (!$circle) {
            $this->jsonError('圈子不存在');
        }
        
        // 检查是否私密圈子（is_private = 1 表示私密）
        if ($circle['is_private']) {
            $this->jsonError('这是一个私密圈子，无法直接加入');
        }
        
        $result = $this->circleModel->addMember($circleId, $_SESSION['user_id'], 0);
        
        if ($result) {
            $this->jsonSuccess(null, '加入成功');
        } else {
            $this->jsonError('加入失败');
        }
    }
    
    /**
     * 退出圈子
     */
    public function leave()
    {
        $this->checkLogin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $circleId = (int)Helper::post('circle_id');
        
        $role = $this->circleModel->getMemberRole($circleId, $_SESSION['user_id']);
        
        if ($role == 2) {
            $this->jsonError('创始人不能退出圈子');
        }
        
        $result = $this->circleModel->removeMember($circleId, $_SESSION['user_id']);
        
        if ($result) {
            $this->jsonSuccess(null, '已退出圈子');
        } else {
            $this->jsonError('退出失败');
        }
    }
    
    /**
     * 发布圈子帖子
     */
    public function publish()
    {
        $this->checkLogin();
        
        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }
        
        $circleId = (int)Helper::post('circle_id');
        $content = trim(Helper::post('content'));
        
        // 检查是否是圈子成员
        if (!$this->circleModel->isMember($circleId, $_SESSION['user_id'])) {
            $this->jsonError('请先加入圈子');
        }
        
        if (empty($content)) {
            $this->jsonError('内容不能为空');
        }
        
        // 创建帖子
        $postModel = new PostModel();
        $postId = $postModel->create([
            'user_id' => $_SESSION['user_id'],
            'content' => $content,
            'created_at' => time(),
            'updated_at' => time(),
            'status' => 1
        ]);
        
        if ($postId) {
            // 添加到圈子
            $this->circleModel->addPost($circleId, $postId);
            $this->jsonSuccess(['post_id' => $postId], '发布成功');
        } else {
            $this->jsonError('发布失败');
        }
    }
    
    /**
     * 上传文件辅助方法
     */
    private function uploadFile($fieldName, $folder)
    {
        $uploadDir = ROOT_PATH . 'uploads/' . $folder . '/';
        
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $file = $_FILES[$fieldName];
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $fileName = time() . '_' . mt_rand(1000, 9999) . '.' . $extension;
        $filePath = $uploadDir . $fileName;
        
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            return [
                'success' => true,
                'path' => $folder . '/' . $fileName
            ];
        }
        
        return ['success' => false];
    }
}
?>