<?php
/**
 * 首页 - 时间流
 * 像一条缓缓流淌的河
 */
require_once __DIR__ . '/includes/init.php';

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * POSTS_PER_PAGE;

$db = getDB();

// 获取总数
$stmt = $db->query("SELECT COUNT(*) FROM posts WHERE status = 'published' AND is_public = 1 AND (published_at IS NULL OR published_at <= NOW())");
$totalPosts = (int) $stmt->fetchColumn();
$totalPages = ceil($totalPosts / POSTS_PER_PAGE);

// 获取文章列表（置顶优先，按时间倒序）
$stmt = $db->prepare("
    SELECT p.*, u.nickname, u.avatar
    FROM posts p
    LEFT JOIN users u ON p.user_id = u.id
    WHERE p.status = 'published' AND p.is_public = 1 AND (p.published_at IS NULL OR p.published_at <= NOW())
    ORDER BY p.is_pinned DESC, COALESCE(p.published_at, p.created_at) DESC
    LIMIT ? OFFSET ?
");
$stmt->execute([POSTS_PER_PAGE, $offset]);
$posts = $stmt->fetchAll();

// 获取每篇文章的标签
if (!empty($posts)) {
    $postIds = array_column($posts, 'id');
    $placeholders = implode(',', array_fill(0, count($postIds), '?'));
    $tagStmt = $db->prepare("
        SELECT pt.post_id, t.name, t.slug
        FROM post_tags pt
        JOIN tags t ON pt.tag_id = t.id
        WHERE pt.post_id IN ($placeholders)
    ");
    $tagStmt->execute($postIds);
    $tagMap = [];
    while ($row = $tagStmt->fetch()) {
        $tagMap[$row['post_id']][] = $row;
    }
}

$pageTitle = '时间流';
$pageDesc = getSetting('site_desc', '网络上的一个私人房间');
include ROOT_PATH . '/includes/header.php';
?>

<!-- 时间流头部 -->
<div class="timeline-header">
    <div class="current-time">
        <span class="live-time"></span>
    </div>
    <div class="greeting">
        <span class="greeting-text">你好</span>，这里是Gaoice的记事本。
    </div>
</div>

<!-- 卡片时间流 -->
<?php if (empty($posts)): ?>
<div class="empty-state">
    <i class="mdui-icon material-icons">nights_stay</i>
    <p>这里还什么都没有...</p>
    <p style="font-size:12px;color:#546e7a;margin-top:4px;">夜深了，写点什么吧</p>
</div>
<?php else: ?>
<div class="timeline-stream">
    <?php foreach ($posts as $post): ?>
    <div class="mdui-card diary-card diary-card-clickable" data-href="<?php echo SITE_URL; ?>/pages/post.php?slug=<?php echo h($post['slug']); ?>">
        <!-- 封面图片 -->
        <?php if (!empty($post['cover_image'])): ?>
        <div class="mdui-card-media">
            <img class="card-cover" src="<?php echo h($post['cover_image']); ?>" alt="<?php echo h($post['title']); ?>">
        </div>
        <?php endif; ?>

        <!-- 标题区 -->
        <div class="mdui-card-primary">
            <div class="mdui-card-primary-title">
                <?php if ($post['is_pinned']): ?>
                <span class="pin-badge"><i class="mdui-icon material-icons">push_pin</i> 置顶</span>
                <?php endif; ?>
                <?php echo h($post['title'] ?: '无标题'); ?>
            </div>
            <div class="mdui-card-primary-subtitle">
                <span><?php echo timeAgo($post['published_at'] ?? $post['created_at']); ?></span>

                <?php if (!empty($post['mood'])): ?>
                <span class="mood-tag">
                    <i class="mdui-icon material-icons"><?php echo moodIcon($post['mood']); ?></i>
                    <?php echo moodName($post['mood']); ?>
                </span>
                <?php endif; ?>

                <?php if (!empty($post['weather'])): ?>
                <span class="weather-tag">
                    <i class="mdui-icon material-icons"><?php echo weatherIcon($post['weather']); ?></i>
                    <?php echo weatherName($post['weather']); ?>
                </span>
                <?php endif; ?>
            </div>
        </div>

        <!-- 内容 -->
        <?php
        $contentText = $post['excerpt'] ?: truncate(strip_tags($post['content_html'] ?? $post['content']), 280);
        if (!empty($contentText)):
        ?>
        <div class="mdui-card-content">
            <?php echo h($contentText); ?>
        </div>
        <?php endif; ?>

        <!-- 音乐卡片 -->
        <?php if (!empty($post['music_url'])): ?>
        <div class="music-card-inner" style="margin:0 16px 8px;">
            <div class="music-icon">
                <i class="mdui-icon material-icons" style="color:#fff;font-size:22px;">music_note</i>
            </div>
            <div class="music-info">
                <div class="music-title"><?php echo h($post['music_title'] ?: '正在播放'); ?></div>
                <div class="music-artist"><?php echo h($post['music_artist'] ?: '未知艺术家'); ?></div>
            </div>
        </div>
        <?php endif; ?>

        <!-- 标签 & 操作 -->
        <div class="mdui-card-actions">
            <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;">
                <div class="post-tags">
                    <?php if (isset($tagMap[$post['id']])): ?>
                        <?php foreach ($tagMap[$post['id']] as $tag): ?>
                        <a href="<?php echo SITE_URL; ?>/pages/tag.php?slug=<?php echo h($tag['slug']); ?>" class="post-tag" onclick="event.stopPropagation();">#<?php echo h($tag['name']); ?></a>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <span style="font-size:11px;color:#546e7a;">
                    <?php echo $post['view_count']; ?> 次浏览
                    <?php if ($post['allow_comment']): ?>
                    · <i class="mdui-icon material-icons" style="font-size:13px;">chat_bubble_outline</i>
                    <?php endif; ?>
                </span>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- 分页 -->
<?php
$baseUrl = SITE_URL . '/?';
echo pagination($page, $totalPages, $baseUrl);
?>

<?php endif; ?>

<?php
include ROOT_PATH . '/includes/footer.php';
