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

/**
 * 移动端控制器（基于API的新版本）
 * 
 * 提供移动端页面渲染，数据通过前端JavaScript调用API获取
 */
class MobileController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->view->setTheme('mobile');
        $this->view->setLayout('app');
    }

    public function index()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $tab = Helper::get('tab', 'all');
        $page = (int)Helper::get('page', 1);
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

        // 获取移动端主题配置
        $themeConfig = $this->getMobileThemeConfig();

        $this->render('app/index', [
            'tab' => $tab,
            'page' => $page,
            'currentPage' => 'home',
            'pageType' => 'home',
            'bodyClass' => 'home-page',
            'headerTitle' => Setting::getSiteName(),
            'circlesEnabled' => Setting::get('circles_enabled', '1') === '1',
            'userId' => $userId,
            'posts' => [],
            'pageData' => [],
            'themeConfig' => $themeConfig
        ]);
    }

    private function getMobileThemeConfig()
    {
        $themeConfig = [
            'primary_color' => '#007AFF',
            'secondary_color' => '#5856D6',
            'accent_color' => '#FF9500',
            'background_color' => '#F2F2F7',
            'card_color' => '#FFFFFF',
            'text_color' => '#000000',
            'text_secondary_color' => '#8E8E93',
            'border_color' => '#C6C6C8',
            'success_color' => '#34C759',
            'danger_color' => '#FF3B30',
            'warning_color' => '#FF9500',
            'primary_light' => '#66b2ff'
        ];
        
        $themeJsonPath = ROOT_PATH . 'templates/mobile/theme.json';
        if (file_exists($themeJsonPath)) {
            $themeJsonContent = file_get_contents($themeJsonPath);
            if ($themeJsonContent) {
                $themeJsonData = json_decode($themeJsonContent, true);
                if ($themeJsonData && isset($themeJsonData['config'])) {
                    $themeConfig = array_merge($themeConfig, $themeJsonData['config']);
                }
            }
        }
        
        return $themeConfig;
    }

    public function hot()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $type = Helper::get('type', 'day');
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

        $this->render('app/hot', [
            'currentPage' => 'hot',
            'pageType' => 'hot',
            'bodyClass' => 'hot-page',
            'headerTitle' => '热门',
            'type' => $type,
            'userId' => $userId,
            'posts' => [],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function discover()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/discover', [
            'currentPage' => 'discover',
            'pageType' => 'discover',
            'bodyClass' => 'discover-page',
            'headerTitle' => '发现',
            'userId' => $userId,
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function circles()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/circles', [
            'currentPage' => 'circles',
            'pageType' => 'circles',
            'bodyClass' => 'circles-page',
            'headerTitle' => '圈子',
            'userId' => $userId,
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function circlePosts()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $circleId = (int)Helper::get('circle_id', 0);
        
        // 获取圈子信息
        $circle = null;
        $circleName = '';
        $posts = [];
        if ($circleId) {
            require_once ROOT_PATH . 'content/circle/CircleModel.php';
            $circleModel = new CircleModel();
            $circle = $circleModel->getCircleById($circleId);
            if ($circle) {
                $circleName = $circle['name'];
                // 预加载帖子数据
                $postsResult = $circleModel->getCirclePosts($circleId, 1, 10);
                $posts = $postsResult['items'] ?? [];
            }
        }

        $this->render('app/circle-posts', [
            'currentPage' => 'circlePosts',
            'pageType' => 'circlePosts',
            'bodyClass' => 'circle-posts-page',
            'headerTitle' => $circleName ?: '圈子动态',
            'circleId' => $circleId,
            'circleName' => $circleName,
            'circle' => $circle,
            'posts' => $posts,
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function login()
    {
        if (isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $this->render('app/login', [
            'hideTabBar' => true,
            'headerTitle' => '登录',
            'pageType' => 'login',
            'bodyClass' => 'login-page',
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function register()
    {
        if (isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        if (!Setting::isRegistrationOpen()) {
            Helper::setFlash('error', '注册功能已关闭');
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $emailVerifyEnabled = Setting::isRegistrationEmailVerifyEnabled();
        $requireInviteCode = (int)Setting::get('require_invite_code', 0) === 1;

        $this->render('app/register', [
            'hideTabBar' => true,
            'headerTitle' => '注册',
            'emailVerifyEnabled' => $emailVerifyEnabled,
            'requireInviteCode' => $requireInviteCode,
            'pageType' => 'register',
            'bodyClass' => 'register-page',
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function logout()
    {
        // 触发退出登录钩子
        Hook::trigger('user_logout', ['user_id' => $_SESSION['user_id'] ?? null]);
        
        // 清除记住登录状态的cookie
        setcookie('remember_token', '', time() - 3600, '/');
        
        // 销毁session
        session_destroy();
        
        // 跳转到移动端首页
        $this->redirect(Helper::url('mobile'));
    }

    public function publish()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/publish', [
            'currentPage' => 'publish',
            'pageType' => 'publish',
            'bodyClass' => 'publish-page',
            'headerTitle' => '发布动态',
            'showBack' => true,
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function detail()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $id = (int)Helper::get('id');
        if (!$id) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $postModel = new PostModel();
        $post = $postModel->getPost($id, $userId);
        
        $comments = [];
        if ($post && $post['status'] == 1) {
            $comments = $postModel->getComments($id, 1, 20);
            $post['images'] = is_array($post['images']) ? $post['images'] : ($post['images'] ? json_decode($post['images'], true) : []);
            $post['videos'] = is_array($post['videos']) ? $post['videos'] : ($post['videos'] ? json_decode($post['videos'], true) : []);
            $post['time_ago'] = Helper::formatTime($post['created_at']);
            $post['content'] = Helper::parseContent($post['content']);
            $post['is_liked'] = $userId ? $postModel->isLiked($id, $userId) : false;
            $favoriteModel = new FavoriteModel();
            $post['is_favorited'] = $userId ? $favoriteModel->isFavorited($id, $userId) : false;
        }

        $this->render('app/detail', [
            'id' => $id,
            'post' => $post,
            'comments' => $comments,
            'showBack' => true,
            'headerTitle' => '动态详情',
            'pageType' => 'detail',
            'bodyClass' => 'detail-page',
            'userId' => $userId,
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function notification()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $userId = $_SESSION['user_id'];
        $type = isset($_GET['type']) ? $_GET['type'] : 'all';

        // 获取各类未读消息数量
        $notificationModel = new NotificationModel();
        $unreadCount = $notificationModel->getUnreadCount($userId);
        $mentionCount = $notificationModel->getUnreadCount($userId, 'mention');
        $likeCount = $notificationModel->getUnreadCount($userId, 'like');
        $commentCount = $notificationModel->getUnreadCount($userId, 'comment');
        
        // 获取私信未读数量
        require_once ROOT_PATH . 'templates/mobile/MessageModel.php';
        $messageModel = new MessageModel();
        $messageCount = $messageModel->getUnreadCount($userId);

        $this->render('app/notification', [
            'currentPage' => 'notification',
            'pageType' => 'notification',
            'bodyClass' => 'notification-page',
            'headerTitle' => '消息',
            'type' => $type,
            'unreadCount' => $unreadCount,
            'mentionCount' => $mentionCount,
            'likeCount' => $likeCount,
            'commentCount' => $commentCount,
            'messageCount' => $messageCount,
            'userId' => $userId,
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function profile()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $themeConfig = $this->getMobileThemeConfig();
        $userId = $_SESSION['user_id'];

        $this->render('app/profile', [
            'currentPage' => 'profile',
            'pageType' => 'profile',
            'bodyClass' => 'profile-page',
            'headerTitle' => '我的',
            'userId' => $userId,
            'mobileSettings' => [
                'mobile_favorite_enabled' => (int)Setting::get('mobile_favorite_enabled', 1),
                'mobile_message_enabled' => (int)Setting::get('mobile_message_enabled', 1),
            ],
            'themeConfig' => $themeConfig
        ]);
    }

    public function user()
    {
        $loginUserId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$loginUserId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $username = Helper::get('username');
        $targetId = (int)Helper::get('id');
        $tab = Helper::get('tab', 'posts'); // 获取tab参数，默认为posts

        if (!$username && !$targetId) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $this->render('app/user', [
            'userId' => $loginUserId, // 传递登录用户ID用于 checkLogin() 判断
            'targetUserId' => $targetId, // 传递目标用户ID用于显示谁的主页
            'username' => $username,
            'tab' => $tab, // 传递tab参数用于确定当前显示哪个标签
            'showBack' => true,
            'headerTitle' => $username ?: '用户主页',
            'pageType' => 'user',
            'bodyClass' => 'user-page',
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function topic()
    {
        $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
        
        if (!$userId && !Setting::isGuestAccessAllowed()) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $keyword = trim(Helper::get('keyword'));
        if (empty($keyword)) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $keyword = Security::xssClean($keyword);
        
        // 获取话题相关的帖子数据
        $postModel = new PostModel();
        $page = (int)Helper::get('page', 1);
        $pageSize = Setting::getPostsPerPage();
        $tab = Helper::get('tab', 'latest');
        
        $posts = $postModel->getPostsByTopic($keyword, $page, $pageSize, $tab);
        foreach ($posts as &$post) {
            $post['images'] = is_array($post['images']) ? $post['images'] : 
                ($post['images'] ? json_decode($post['images'], true) : []);
            $post['videos'] = is_array($post['videos']) ? $post['videos'] : 
                ($post['videos'] ? json_decode($post['videos'], true) : []);
            $post['time_ago'] = Helper::formatTime($post['created_at']);
            // 保存原始内容用于分享
            $post['raw_content'] = $post['content'];
            // 使用移动端的话题和用户链接格式
            $topicUrl = Helper::url('mobile/topic?keyword=$1');
            $userUrl = Helper::url('mobile/user?username=$1');
            $post['content'] = Helper::parseContent($post['content'], $topicUrl, $userUrl);
        }
        unset($post);
        
        $total = $postModel->countPostsByTopic($keyword);

        $this->render('app/topic', [
            'keyword' => $keyword,
            'posts' => $posts,
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $total,
            'tab' => $tab,
            'showBack' => true,
            'headerTitle' => '#' . $keyword . '#',
            'pageType' => 'topic',
            'bodyClass' => 'topic-page',
            'userId' => $userId,
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function repost()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $id = (int)Helper::get('id');
        if (!$id) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $this->render('app/repost', [
            'id' => $id,
            'showBack' => true,
            'headerTitle' => '转发动态',
            'pageType' => 'repost',
            'bodyClass' => 'repost-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function favorites()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/favorites', [
            'showBack' => true,
            'headerTitle' => '我的收藏',
            'pageType' => 'favorites',
            'bodyClass' => 'favorites-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function follows()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/follows', [
            'showBack' => true,
            'headerTitle' => '我的关注',
            'pageType' => 'follows',
            'bodyClass' => 'follows-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function fans()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/fans', [
            'showBack' => true,
            'headerTitle' => '我的粉丝',
            'pageType' => 'fans',
            'bodyClass' => 'fans-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function settings()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/settings', [
            'currentPage' => 'settings',
            'headerTitle' => '设置',
            'pageType' => 'settings',
            'bodyClass' => 'settings-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function privacy()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/privacy', [
            'currentPage' => 'privacy',
            'headerTitle' => '隐私设置',
            'pageType' => 'privacy',
            'bodyClass' => 'privacy-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function privacyBlacklist()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/privacy-blacklist', [
            'currentPage' => 'privacy-blacklist',
            'headerTitle' => '黑名单管理',
            'pageType' => 'privacy',
            'bodyClass' => 'privacy-page blacklist-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function privacySecurity()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/privacy-security', [
            'currentPage' => 'privacy-security',
            'headerTitle' => '账号安全',
            'pageType' => 'privacy',
            'bodyClass' => 'privacy-page security-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function privacyData()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/privacy-data', [
            'currentPage' => 'privacy-data',
            'headerTitle' => '数据管理',
            'pageType' => 'privacy',
            'bodyClass' => 'privacy-page data-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function password()
    {
        $this->render('app/password', [
            'currentPage' => 'password',
            'hideTabBar' => true,
            'headerTitle' => '忘记密码',
            'pageType' => 'password',
            'bodyClass' => 'password-page',
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function editProfile()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/edit_profile', [
            'currentPage' => 'edit_profile',
            'headerTitle' => '编辑资料',
            'pageType' => 'edit_profile',
            'bodyClass' => 'edit-profile-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function messages()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/messages', [
            'currentPage' => 'messages',
            'headerTitle' => '私信',
            'pageType' => 'messages',
            'bodyClass' => 'messages-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function chat()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $userId = (int)Helper::get('user_id');
        $username = Helper::get('username');

        if (!$userId || !$username) {
            $this->redirect(Helper::url('mobile/messages'));
            return;
        }

        $this->render('app/chat', [
            'showBack' => true,
            'headerTitle' => $username,
            'hideTabBar' => true,
            'pageType' => 'chat',
            'bodyClass' => 'chat-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function recommend()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/recommend', [
            'showBack' => true,
            'headerTitle' => '推荐关注',
            'pageType' => 'recommend',
            'bodyClass' => 'recommend-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function topics()
    {
        $this->render('app/topics', [
            'showBack' => true,
            'headerTitle' => '热门话题',
            'pageType' => 'topics',
            'bodyClass' => 'topics-page',
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function points()
    {
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile/login'));
            return;
        }

        $this->render('app/points', [
            'showBack' => true,
            'headerTitle' => '积分中心',
            'pageType' => 'points',
            'bodyClass' => 'points-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    public function reportManage()
    {
        // 只有管理员ID=1可以访问
        if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] !== 1) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $this->render('app/report_manage', [
            'showBack' => true,
            'headerTitle' => '举报管理',
            'pageType' => 'report_manage',
            'bodyClass' => 'report-manage-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    /**
     * 我的举报页面
     */
    public function myReports()
    {
        // 需要登录
        if (!isset($_SESSION['user_id'])) {
            $this->redirect(Helper::url('mobile'));
            return;
        }

        $this->render('app/my_reports', [
            'showBack' => true,
            'headerTitle' => '我的举报',
            'pageType' => 'my_reports',
            'bodyClass' => 'my-reports-page',
            'userId' => $_SESSION['user_id'],
            'pageData' => [],
            'themeConfig' => $this->getMobileThemeConfig()
        ]);
    }

    protected function render($template, $data = [])
    {
        echo $this->view->render($template, $data);
    }
}
