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

function Mirai_apiArchiveList() {
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $pageSize = isset($_GET['size']) ? max(1, min(50, (int)$_GET['size'])) : 5;
    $scope = isset($_GET['scope']) ? trim($_GET['scope']) : 'index';

    $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.contents.type',
        '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 = ?', '');

    $baseUrl = null;
    $totalPosts = 0;
    $isIndex = ($scope === 'index');

    switch ($scope) {
        case 'category':
            $mid = isset($_GET['mid']) ? (int)$_GET['mid'] : 0;
            if ($mid <= 0) return ['code' => -1, 'success' => false, 'msg' => '缺少分类ID'];
            $select->join('table.relationships', 'table.contents.cid = table.relationships.cid')
                   ->where('table.relationships.mid = ?', $mid);
            $meta = $db->fetchRow($db->select('name', 'slug', 'mid')->from('table.metas')->where('mid = ? AND type = ?', $mid, 'category'));
            if ($meta) $baseUrl = \Typecho\Router::url('category', $meta, $options->index);
            $countSelect = $db->select('COUNT(*)')->from('table.contents')
                ->join('table.relationships', 'table.contents.cid = table.relationships.cid')
                ->where('table.contents.status = ?', 'publish')
                ->where('table.contents.type = ?', 'post')
                ->where('table.contents.created <= ?', time())
                ->where('table.relationships.mid = ?', $mid);
            $totalPosts = (int)$db->fetchObject($countSelect)->{'COUNT(*)'};
            break;

        case 'tag':
            $mid = isset($_GET['mid']) ? (int)$_GET['mid'] : 0;
            if ($mid <= 0) return ['code' => -1, 'success' => false, 'msg' => '缺少标签ID'];
            $select->join('table.relationships', 'table.contents.cid = table.relationships.cid')
                   ->where('table.relationships.mid = ?', $mid);
            $meta = $db->fetchRow($db->select('name', 'slug', 'mid')->from('table.metas')->where('mid = ? AND type = ?', $mid, 'tag'));
            if ($meta) $baseUrl = \Typecho\Router::url('tag', $meta, $options->index);
            $countSelect = $db->select('COUNT(*)')->from('table.contents')
                ->join('table.relationships', 'table.contents.cid = table.relationships.cid')
                ->where('table.contents.status = ?', 'publish')
                ->where('table.contents.type = ?', 'post')
                ->where('table.contents.created <= ?', time())
                ->where('table.relationships.mid = ?', $mid);
            $totalPosts = (int)$db->fetchObject($countSelect)->{'COUNT(*)'};
            break;

        case 'search':
            $keywords = isset($_GET['keywords']) ? trim($_GET['keywords']) : '';
            if ($keywords === '') return ['code' => -1, 'success' => false, 'msg' => '缺少搜索关键词'];
            $select->where('table.contents.title LIKE ?', '%' . $keywords . '%');
            $baseUrl = $options->index . '/search/' . urlencode($keywords);
            $countSelect = $db->select('COUNT(*)')->from('table.contents')
                ->where('table.contents.status = ?', 'publish')
                ->where('table.contents.type = ?', 'post')
                ->where('table.contents.created <= ?', time())
                ->where('table.contents.title LIKE ?', '%' . $keywords . '%');
            $totalPosts = (int)$db->fetchObject($countSelect)->{'COUNT(*)'};
            break;

        case 'author':
            $uid = isset($_GET['uid']) ? (int)$_GET['uid'] : 0;
            if ($uid <= 0) return ['code' => -1, 'success' => false, 'msg' => '缺少作者ID'];
            $select->where('table.contents.authorId = ?', $uid);
            $author = $db->fetchRow($db->select('uid', 'name', 'screenName')->from('table.users')->where('uid = ?', $uid));
            if ($author) $baseUrl = \Typecho\Router::url('author', $author, $options->index);
            $countSelect = $db->select('COUNT(*)')->from('table.contents')
                ->where('table.contents.status = ?', 'publish')
                ->where('table.contents.type = ?', 'post')
                ->where('table.contents.created <= ?', time())
                ->where('table.contents.authorId = ?', $uid);
            $totalPosts = (int)$db->fetchObject($countSelect)->{'COUNT(*)'};
            break;

        case 'index':
        default:
            $scope = 'index';
            $excludedIds = Mirai_getRecommendExcludedIds();
            if (!empty($excludedIds)) {
                $select->where('table.contents.cid NOT IN ?', $excludedIds);
            }
            $stickyIds = [];
            if (!empty($options->listTopEnable) && $options->listTopEnable === '1' && !empty($options->listTopIds)) {
                $lines = explode("\n", $options->listTopIds);
                foreach ($lines as $line) {
                    $cid = intval(trim($line));
                    if ($cid > 0) $stickyIds[] = $cid;
                }
            }
            if (!empty($stickyIds)) {
                $select->where('table.contents.cid NOT IN ?', $stickyIds);
            }
            $baseUrl = $options->index;
            $countSelect = $db->select('COUNT(*)')->from('table.contents')
                ->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 = ?', '');
            if (!empty($excludedIds)) $countSelect->where('table.contents.cid NOT IN ?', $excludedIds);
            if (!empty($stickyIds)) $countSelect->where('table.contents.cid NOT IN ?', $stickyIds);
            $totalPosts = (int)$db->fetchObject($countSelect)->{'COUNT(*)'};
            break;
    }

    $select->order('table.contents.created', \Typecho\Db::SORT_DESC);
    $offset = ($page - 1) * $pageSize;
    $select->offset($offset)->limit($pageSize);

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

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

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

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

        Mirai_renderPostItem($post, [
            'isWidget' => false,
            'isFirst' => false,
            'isIndex' => $isIndex,
        ]);
    }
    $html = ob_get_clean();

    $totalPages = $pageSize > 0 ? ceil($totalPosts / $pageSize) : 1;
    $hasMore = $page < $totalPages;
    $nextPage = $hasMore ? $page + 1 : 0;

    $paginationHtml = '';
    if ($hasMore && $baseUrl) {
        $nextUrl = $baseUrl . ($nextPage > 1 ? '/page/' . $nextPage : '');
        $triggerMode = $options->archiveAjaxPaginationTrigger ?? 'button';
        $paginationHtml = Mirai_buildAjaxPaginationHtml([
            'scopeType' => 'archive',
            'current' => $page,
            'total' => $totalPages,
            'nextUrl' => $nextUrl,
            'triggerMode' => $triggerMode,
            'direction' => 'forward',
            'hasMore' => true,
        ]);
    } else {
        $paginationHtml = Mirai_buildAjaxPaginationHtml([
            'scopeType' => 'archive',
            'current' => $page,
            'total' => $totalPages,
            'hasMore' => false,
        ]);
    }

    return [
        'code' => 0,
        'success' => true,
        'html' => $html,
        'hasMore' => $hasMore,
        'nextPage' => $nextPage,
        'nextUrl' => $hasMore && $baseUrl ? $baseUrl . ($nextPage > 1 ? '/page/' . $nextPage : '') : '',
        'total' => $totalPosts,
        'paginationHtml' => $paginationHtml
    ];
}
