<?php
/**
 * 空状态推荐文章模块
 * 
 * 在404、暂无文章等空状态页面中显示推荐阅读文章
 */

if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_getEmptyStateRecommendPosts($limit = 6, $sortBy = 'random') {
    $db = \Typecho\Db::get();
    $options = Mirai_opt();
    
    $select = $db->select('cid', 'title', 'slug', 'text', 'created', 'cover', 'authorId', 'views', 'likes', 'commentsNum')
        ->from('table.contents')
        ->where('status = ?', 'publish')
        ->where('type = ?', 'post')
        ->where('created <= ?', time())
        ->where('password IS NULL OR password = ?', '');
    
    switch ($sortBy) {
        case 'hot':
            $select->order('views', \Typecho\Db::SORT_DESC);
            break;
        case 'latest':
            $select->order('created', \Typecho\Db::SORT_DESC);
            break;
        case 'random':
        default:
            // 使用伪随机：基于当前时间的小时数来偏移
            $totalRows = $db->fetchObject($db->select('COUNT(*) AS cnt')
                ->from('table.contents')
                ->where('status = ?', 'publish')
                ->where('type = ?', 'post')
                ->where('created <= ?', time())
            )->cnt;
            
            if ($totalRows > $limit) {
                $offset = (int)(time() / 3600 * 7) % max(1, $totalRows - $limit);
                $select->offset((int)$offset);
            }
            $select->order('created', \Typecho\Db::SORT_DESC);
            break;
    }
    
    $select->limit($limit);
    $posts = $db->fetchAll($select);
    
    if (empty($posts)) return [];
    
    $cids = array_column($posts, 'cid');
    
    $metaResult = Mirai_buildPostMetaMap($cids);
    $categoryMap = $metaResult['categoryMap'];
    $tagMap = $metaResult['tagMap'];
    
    $authorIds = array_filter(array_unique(array_column($posts, 'authorId')));
    $authorMap = [];
    if (!empty($authorIds)) {
        $authorData = $db->fetchAll(
            $db->select('uid', 'screenName', 'mail')
                ->from('table.users')
                ->where('uid IN ?', $authorIds)
        );
        foreach ($authorData as $author) {
            $authorMap[$author['uid']] = [
                'name' => $author['screenName'],
                'mail' => $author['mail']
            ];
        }
    }
    
    $result = [];
    foreach ($posts as $row) {
        $row['categories'] = $categoryMap[$row['cid']] ?? [];
        $row['tags'] = $tagMap[$row['cid']] ?? [];
        $row['permalink'] = \Typecho\Router::url('post', $row, $options->index);
        
        $authorInfo = $authorMap[$row['authorId']] ?? null;
        $row['author'] = $authorInfo ? $authorInfo['name'] : 'Unknown';
        $row['authorMail'] = $authorInfo ? $authorInfo['mail'] : '';
        
        $result[] = $row;
    }
    
    return $result;
}

function Mirai_renderEmptyStateWithRecommend($emptyImg, $emptyTitle, $emptyDesc, $widget = null) {
    $options = Mirai_opt();
    
    $emptyRecommendEnable = !isset($options->emptyRecommendEnable) || $options->emptyRecommendEnable !== '0';
    $sortBy = isset($options->emptyRecommendSort) ? $options->emptyRecommendSort : 'random';
    $limit = intval($options->emptyRecommendNum ?? 6);
    if ($limit < 1) $limit = 6;
    
    $posts = [];
    if ($emptyRecommendEnable) {
        $posts = Mirai_getEmptyStateRecommendPosts($limit, $sortBy);
    }
    
    echo '<div class="gt-empty">' . "\n";
    echo '    <img src="' . htmlspecialchars($emptyImg, ENT_QUOTES, 'UTF-8') . '" alt="' . htmlspecialchars($emptyTitle, ENT_QUOTES, 'UTF-8') . '" class="gt-empty-img" width="120" height="120">' . "\n";
    if ($emptyTitle) {
        echo '    <h1 class="gt-empty-title">' . htmlspecialchars($emptyTitle, ENT_QUOTES, 'UTF-8') . '</h1>' . "\n";
    }
    if (!empty($posts)) {
        echo '    <p class="gt-empty-desc">' . htmlspecialchars($emptyDesc, ENT_QUOTES, 'UTF-8') . '，为您推荐以下文章</p>' . "\n";
    } else {
        echo '    <p class="gt-empty-desc">' . htmlspecialchars($emptyDesc, ENT_QUOTES, 'UTF-8') . '</p>' . "\n";
    }
    echo '</div>' . "\n";
    
    if (!empty($posts)) {
        echo '<h2 class="gt-cms-title-h3" style="grid-column: 1 / -1; width: 100%;">推荐阅读</h2>' . "\n";
        
        foreach ($posts as $post) {
            Mirai_renderPostItem($post, ['isWidget' => false, 'isFirst' => false, 'isIndex' => true]);
        }
    }
}
