<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_ajaxTabPosts() {
    $tab = isset($_GET['tab']) ? trim($_GET['tab']) : 'latest';
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $pageSize = isset($_GET['size']) ? max(1, min(50, (int)$_GET['size'])) : 8;

    $allowedTabs = ['latest', 'views', 'likes', 'comments'];
    if (!in_array($tab, $allowedTabs)) {
        return ['code' => 0, 'success' => true, 'html' => ''];
    }

    try {
        $db = \Typecho\Db::get();
        $options = Mirai_opt();

        $select = $db->select(
            'table.contents.cid', 'table.contents.title', 'table.contents.slug',
            'table.contents.created', 'table.contents.authorId',
            'table.contents.views', 'table.contents.likes', 'table.contents.commentsNum',
            'table.contents.text', 'table.contents.cover',
            'table.users.screenName', 'table.users.mail as authorMail'
        )->from('table.contents')
            ->join('table.users', 'table.contents.authorId = table.users.uid', \Typecho\Db::LEFT_JOIN)
            ->where('table.contents.status = ?', 'publish')
            ->where('table.contents.type = ?', 'post')
            ->where('table.contents.created <= ?', time())
            ->where('table.contents.password IS NULL OR table.contents.password = ?', '');

        switch ($tab) {
            case 'views':
                $select->order('table.contents.views', \Typecho\Db::SORT_DESC);
                break;
            case 'likes':
                $select->order('table.contents.likes', \Typecho\Db::SORT_DESC);
                break;
            case 'comments':
                $select->order('table.contents.commentsNum', \Typecho\Db::SORT_DESC);
                break;
            default:
                $select->order('table.contents.created', \Typecho\Db::SORT_DESC);
                break;
        }

        $offset = ($page - 1) * $pageSize;
        $select->offset($offset)->limit($pageSize);

        $posts = $db->fetchAll($select);

        if (empty($posts)) {
            return ['code' => 0, 'success' => true, 'html' => ''];
        }

        $cids = array_column($posts, 'cid');
        $metaMap = Mirai_buildPostMetaMap($cids, ['category', 'tag'], true);
        $categoryMap = $metaMap['categoryMap'];
        $tagMap = $metaMap['tagMap'];

        ob_start();
        $articleIndex = 0;
        foreach ($posts as $post) {
            $articleIndex++;
            $cid = $post['cid'];
            $post['author'] = $post['screenName'] ?? 'Unknown';
            $post['categories'] = !empty($categoryMap[$cid]) ? $categoryMap[$cid] : [];
            $post['tags'] = !empty($tagMap[$cid]) ? $tagMap[$cid] : [];

            Mirai_renderPostItem($post, [
                'isWidget' => false,
                'isFirst' => ($articleIndex === 1 && $page === 1),
                'isIndex' => true,
            ]);
        }
        $html = ob_get_clean();

        return ['code' => 0, 'success' => true, 'html' => $html];
    } catch (\Exception $e) {
        return ['code' => -1, 'success' => false, 'msg' => '获取失败'];
    }
}
