<?php
require_once __DIR__ . '/../includes/functions.php';

$postId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($postId <= 0) {
    header('Location: ' . SITE_URL . '/mobile/index.php');
    exit;
}

$db = Database::getInstance();

// 获取帖子详情
$post = $db->queryOne(
    "SELECT p.*, u.username, u.avatar, u.signature, c.name as category_name 
     FROM posts p 
     LEFT JOIN users u ON p.user_id = u.id 
     LEFT JOIN categories c ON p.category_id = c.id 
     WHERE p.id = ? AND p.status = 1",
    [$postId]
);

if (!$post) {
    header('Location: ' . SITE_URL . '/mobile/index.php');
    exit;
}

// 增加浏览次数
$db->query("UPDATE posts SET view_count = view_count + 1 WHERE id = ?", [$postId]);

// 获取回复列表
$replies = $db->query(
    "SELECT r.*, u.username, u.avatar 
     FROM replies r 
     LEFT JOIN users u ON r.user_id = u.id 
     WHERE r.post_id = ? AND r.status = 1 
     ORDER BY r.created_at ASC",
    [$postId]
);

// 获取当前用户
$currentUser = getCurrentUser();

// 获取帖子的点赞和收藏状态
$isLiked = false;
$isFavorited = false;
$likeCount = getLikeCount('post', $postId);
$favoriteCount = getFavoriteCount('post', $postId);

if ($currentUser) {
    $isLiked = isLiked($currentUser['id'], 'post', $postId);
    $isFavorited = isFavorited($currentUser['id'], 'post', $postId);
}

$pageTitle = $post['title'];
include __DIR__ . '/includes/header.php';
?>

<!-- 返回按钮 -->
<div class="mobile-back-bar">
    <a href="javascript:history.back();" class="mobile-back-btn">
        <i class="fas fa-arrow-left"></i> 返回
    </a>
</div>

<!-- 帖子内容 -->
<div class="mobile-post-detail">
    <h1 class="mobile-post-detail-title"><?php echo e($post['title']); ?></h1>
    <div class="mobile-post-detail-meta">
        <a href="<?php echo SITE_URL; ?>/mobile/user.php?id=<?php echo $post['user_id']; ?>" class="mobile-post-author">
            <?php if (!empty($post['avatar']) && $post['avatar'] != 'NULL'): ?>
                <?php
                // 处理头像路径
                $avatarUrl = $post['avatar'];
                if (!preg_match('/^https?:\/\//', $avatarUrl) && !preg_match('/^\//', $avatarUrl)) {
                    $avatarUrl = SITE_URL . '/' . $avatarUrl;
                }
                ?>
                <img src="<?php echo e($avatarUrl); ?>" alt="" onerror="this.style.display='none'; this.parentElement.querySelector('.avatar-fallback').style.display='flex';">
                <i class="fas fa-user avatar-fallback" style="display: none;"></i>
            <?php else: ?>
                <i class="fas fa-user"></i>
            <?php endif; ?>
            <span><?php echo e($post['username']); ?></span>
        </a>
        <span class="mobile-post-time"><?php echo formatTime($post['created_at']); ?></span>
        <?php if ($post['category_name']): ?>
        <span class="mobile-post-category-tag"><?php echo e($post['category_name']); ?></span>
        <?php endif; ?>
    </div>
    <div class="mobile-post-detail-content">
        <?php echo $post['content']; ?>
    </div>
    
    <!-- 点赞和收藏按钮 -->
    <div class="mobile-post-actions">
        <?php if ($currentUser): ?>
            <button type="button" class="mobile-action-btn like-btn <?php echo $isLiked ? 'active' : ''; ?>" 
                    data-type="post" data-id="<?php echo $postId; ?>">
                <i class="<?php echo $isLiked ? 'fas' : 'far'; ?> fa-thumbs-up"></i>
                <span class="action-count"><?php echo $likeCount; ?></span>
                <span class="action-text"><?php echo $isLiked ? '已赞' : '点赞'; ?></span>
            </button>
            <button type="button" class="mobile-action-btn favorite-btn <?php echo $isFavorited ? 'active' : ''; ?>" 
                    data-type="post" data-id="<?php echo $postId; ?>">
                <i class="<?php echo $isFavorited ? 'fas' : 'far'; ?> fa-star"></i>
                <span class="action-count"><?php echo $favoriteCount; ?></span>
                <span class="action-text"><?php echo $isFavorited ? '已收藏' : '收藏'; ?></span>
            </button>
        <?php else: ?>
            <a href="<?php echo SITE_URL; ?>/mobile/login.php" class="mobile-action-btn">
                <i class="far fa-thumbs-up"></i>
                <span><?php echo $likeCount; ?></span>
                <span>点赞</span>
            </a>
            <a href="<?php echo SITE_URL; ?>/mobile/login.php" class="mobile-action-btn">
                <i class="far fa-star"></i>
                <span><?php echo $favoriteCount; ?></span>
                <span>收藏</span>
            </a>
        <?php endif; ?>
    </div>
    
    <div class="mobile-post-detail-stats">
        <span><i class="fas fa-eye"></i> <?php echo $post['view_count']; ?></span>
        <span><i class="fas fa-comment"></i> <?php echo count($replies); ?></span>
    </div>
</div>

<!-- 回复列表 -->
<div class="mobile-section">
    <div class="mobile-section-title">
        <i class="fas fa-comments" style="color: var(--primary-color);"></i>
        <span>回复 (<?php echo count($replies); ?>)</span>
    </div>
    
    <?php if (empty($replies)): ?>
    <div class="mobile-empty">
        <i class="fas fa-comment-slash"></i>
        <p>暂无回复，快来抢沙发吧！</p>
    </div>
    <?php else: ?>
    <?php
    // 获取高亮参数
    $highlightReplyId = isset($_GET['highlight']) ? intval($_GET['highlight']) : 0;
    ?>
    <div class="mobile-reply-list">
        <?php foreach ($replies as $index => $reply):
            $isHighlighted = ($highlightReplyId == $reply['id']);
            
            // 获取回复的点赞和收藏状态
            $replyIsLiked = false;
            $replyIsFavorited = false;
            $replyLikeCount = getLikeCount('reply', $reply['id']);
            $replyFavoriteCount = getFavoriteCount('reply', $reply['id']);
            if ($currentUser) {
                $replyIsLiked = isLiked($currentUser['id'], 'reply', $reply['id']);
                $replyIsFavorited = isFavorited($currentUser['id'], 'reply', $reply['id']);
            }
        ?>
        <div class="mobile-reply-item <?php echo $isHighlighted ? 'highlight-reply' : ''; ?>" id="reply-<?php echo $reply['id']; ?>">
            <div class="mobile-reply-header">
                <a href="<?php echo SITE_URL; ?>/mobile/user.php?id=<?php echo $reply['user_id']; ?>" class="mobile-reply-author">
                    <?php if (!empty($reply['avatar']) && $reply['avatar'] != 'NULL'): ?>
                        <?php
                        // 处理头像路径
                        $replyAvatarUrl = $reply['avatar'];
                        if (!preg_match('/^https?:\/\//', $replyAvatarUrl) && !preg_match('/^\//', $replyAvatarUrl)) {
                            $replyAvatarUrl = SITE_URL . '/' . $replyAvatarUrl;
                        }
                        ?>
                        <img src="<?php echo e($replyAvatarUrl); ?>" alt="" onerror="this.style.display='none'; this.parentElement.querySelector('.avatar-fallback').style.display='flex';">
                        <i class="fas fa-user avatar-fallback" style="display: none;"></i>
                    <?php else: ?>
                        <i class="fas fa-user"></i>
                    <?php endif; ?>
                    <span><?php echo e($reply['username']); ?></span>
                </a>
                <span class="mobile-reply-floor">#<?php echo $index + 1; ?></span>
            </div>
            <div class="mobile-reply-content">
                <?php echo $reply['content']; ?>
            </div>
            <div class="mobile-reply-footer">
                <span class="mobile-reply-time"><?php echo formatTime($reply['created_at']); ?></span>
                
                <!-- 回复点赞和收藏按钮 -->
                <div class="mobile-reply-actions">
                    <?php if ($currentUser): ?>
                        <button type="button" class="mobile-reply-action-btn like-btn <?php echo $replyIsLiked ? 'active' : ''; ?>" 
                                data-type="reply" data-id="<?php echo $reply['id']; ?>">
                            <i class="<?php echo $replyIsLiked ? 'fas' : 'far'; ?> fa-thumbs-up"></i>
                            <span class="action-count"><?php echo $replyLikeCount; ?></span>
                        </button>
                        <button type="button" class="mobile-reply-action-btn favorite-btn <?php echo $replyIsFavorited ? 'active' : ''; ?>" 
                                data-type="reply" data-id="<?php echo $reply['id']; ?>">
                            <i class="<?php echo $replyIsFavorited ? 'fas' : 'far'; ?> fa-star"></i>
                            <span class="action-count"><?php echo $replyFavoriteCount; ?></span>
                        </button>
                    <?php else: ?>
                        <a href="<?php echo SITE_URL; ?>/mobile/login.php" class="mobile-reply-action-btn">
                            <i class="far fa-thumbs-up"></i>
                            <span><?php echo $replyLikeCount; ?></span>
                        </a>
                        <a href="<?php echo SITE_URL; ?>/mobile/login.php" class="mobile-reply-action-btn">
                            <i class="far fa-star"></i>
                            <span><?php echo $replyFavoriteCount; ?></span>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- 回复表单 -->
<?php if ($currentUser): ?>
<div class="mobile-section">
    <div class="mobile-section-title">
        <i class="fas fa-reply" style="color: var(--primary-color);"></i>
        <span>发表回复</span>
    </div>
    <form method="POST" action="<?php echo SITE_URL; ?>/mobile/reply-action.php" class="mobile-reply-form">
        <input type="hidden" name="post_id" value="<?php echo $postId; ?>">
        <div class="mobile-form-group">
            <textarea name="content" class="mobile-reply-textarea" rows="4" placeholder="请输入回复内容..." required></textarea>
        </div>
        <button type="submit" class="mobile-reply-submit">
            <i class="fas fa-paper-plane"></i> 发表回复
        </button>
    </form>
</div>
<?php else: ?>
<div class="mobile-section">
    <div class="mobile-login-tip">
        <p>请先 <a href="<?php echo SITE_URL; ?>/mobile/login.php">登录</a> 后回复</p>
    </div>
</div>
<?php endif; ?>

<style>
.mobile-back-bar {
    background: #fff;
    padding: 10px 15px;
    border-bottom: 1px solid #f0f0f0;
}
.mobile-back-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    color: #666;
    font-size: 14px;
    text-decoration: none;
}
.mobile-back-btn i {
    font-size: 12px;
}
.mobile-post-detail {
    background: #fff;
    padding: 15px;
    margin-bottom: 10px;
}
.mobile-post-detail-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    line-height: 1.4;
}
.mobile-post-detail-meta {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}
.mobile-post-author {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #333;
}
.mobile-post-author img {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    object-fit: cover;
}
.mobile-post-author i {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
}
.mobile-post-time {
    font-size: 12px;
    color: #999;
}
.mobile-post-category-tag {
    background: var(--primary-color);
    color: #fff;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 11px;
}
.mobile-post-detail-content {
    font-size: 15px;
    line-height: 1.8;
    color: #333;
    margin-bottom: 15px;
    word-break: break-word;
}
.mobile-post-detail-content img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    margin: 10px 0;
}
.mobile-reply-content img {
    max-width: 64px;
    max-height: 64px;
    border-radius: 4px;
    margin: 5px 0;
}

/* 点赞收藏按钮样式 */
.mobile-post-actions {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}
.mobile-action-btn {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 8px 16px;
    border-radius: 20px;
    border: 1px solid #e0e0e0;
    background: #fff;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.3s;
}
.mobile-action-btn.active {
    background: var(--primary-color);
    color: #fff;
    border-color: var(--primary-color);
}
.mobile-action-btn.like-btn.active {
    background: #ff6b6b;
    border-color: #ff6b6b;
}
.mobile-action-btn.favorite-btn.active {
    background: #ffd700;
    border-color: #ffd700;
    color: #333;
}
.mobile-action-btn:active {
    transform: scale(0.95);
}

.mobile-post-detail-stats {
    display: flex;
    gap: 15px;
    font-size: 13px;
    color: #999;
}
.mobile-reply-item {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
}
.mobile-reply-item:last-child {
    border-bottom: none;
}
.mobile-reply-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}
.mobile-reply-author {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #333;
}
.mobile-reply-author img {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    object-fit: cover;
}
.mobile-reply-author i {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 12px;
}
.mobile-reply-floor {
    font-size: 12px;
    color: #999;
    background: #f5f5f5;
    padding: 2px 8px;
    border-radius: 10px;
}
.mobile-reply-content {
    font-size: 14px;
    line-height: 1.6;
    color: #333;
    margin-bottom: 8px;
    word-break: break-word;
}
.mobile-reply-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.mobile-reply-time {
    font-size: 12px;
    color: #999;
}
.mobile-reply-actions {
    display: flex;
    gap: 8px;
}
.mobile-reply-action-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border-radius: 12px;
    border: 1px solid #e0e0e0;
    background: #fff;
    color: #666;
    font-size: 12px;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.3s;
}
.mobile-reply-action-btn.like-btn.active {
    background: #ff6b6b;
    color: #fff;
    border-color: #ff6b6b;
}
.mobile-reply-action-btn.favorite-btn.active {
    background: #ffd700;
    color: #333;
    border-color: #ffd700;
}
.mobile-reply-action-btn:active {
    transform: scale(0.95);
}
.mobile-login-tip {
    text-align: center;
    padding: 30px 15px;
    color: #999;
}
.mobile-login-tip a {
    color: var(--primary-color);
}
.mobile-reply-form {
    padding: 15px;
    background: #fff;
}
.mobile-reply-textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
    line-height: 1.6;
    resize: vertical;
    min-height: 100px;
    font-family: inherit;
    box-sizing: border-box;
}
.mobile-reply-textarea:focus {
    outline: none;
    border-color: var(--primary-color);
}
.mobile-reply-submit {
    width: 100%;
    padding: 12px;
    margin-top: 12px;
    background: var(--primary-color);
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}
.mobile-reply-submit:active {
    opacity: 0.9;
}

/* 高亮回复样式 */
.highlight-reply {
    animation: highlight-pulse 2s ease-in-out 3;
    border: 2px solid var(--primary-color) !important;
    border-radius: 8px;
}

@keyframes highlight-pulse {
    0%, 100% {
        background-color: rgba(76, 175, 80, 0.1);
        box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.4);
    }
    50% {
        background-color: rgba(76, 175, 80, 0.2);
        box-shadow: 0 0 0 10px rgba(76, 175, 80, 0);
    }
}
</style>

<script>
// 高亮回复自动滚动
(function() {
    const urlParams = new URLSearchParams(window.location.search);
    const highlightId = urlParams.get('highlight');
    
    if (highlightId) {
        const targetElement = document.getElementById('reply-' + highlightId);
        if (targetElement) {
            // 延迟滚动，确保页面已完全加载
            setTimeout(function() {
                targetElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
            }, 500);
        }
    }
})();

// 点赞和收藏功能
(function() {
    // 更新点赞按钮UI
    function updateLikeButton(btn, data) {
        const icon = btn.querySelector('i');
        const countSpan = btn.querySelector('.action-count, .like-count');
        const textSpan = btn.querySelector('.action-text');
        
        if (data.liked) {
            btn.classList.add('active');
            icon.classList.remove('far');
            icon.classList.add('fas');
            if (textSpan) textSpan.textContent = '已赞';
        } else {
            btn.classList.remove('active');
            icon.classList.remove('fas');
            icon.classList.add('far');
            if (textSpan) textSpan.textContent = '点赞';
        }
        if (countSpan) countSpan.textContent = data.count;
    }
    
    // 更新收藏按钮UI
    function updateFavoriteButton(btn, data) {
        const icon = btn.querySelector('i');
        const countSpan = btn.querySelector('.action-count');
        const textSpan = btn.querySelector('.action-text');
        
        if (data.favorited) {
            btn.classList.add('active');
            icon.classList.remove('far');
            icon.classList.add('fas');
            if (textSpan) textSpan.textContent = '已收藏';
        } else {
            btn.classList.remove('active');
            icon.classList.remove('fas');
            icon.classList.add('far');
            if (textSpan) textSpan.textContent = '收藏';
        }
        if (countSpan) countSpan.textContent = data.count;
    }
    
    // 点赞按钮点击事件
    document.querySelectorAll('.like-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetType = this.dataset.type;
            const targetId = this.dataset.id;
            const isLiked = this.classList.contains('active');
            const action = isLiked ? 'unlike' : 'like';
            
            fetch('<?php echo SITE_URL; ?>/api/like.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=' + action + '&target_type=' + targetType + '&target_id=' + targetId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateLikeButton(this, data);
                } else {
                    alert(data.message || '操作失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，请重试');
            });
        });
    });
    
    // 收藏按钮点击事件
    document.querySelectorAll('.favorite-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetType = this.dataset.type;
            const targetId = this.dataset.id;
            const isFavorited = this.classList.contains('active');
            const action = isFavorited ? 'unfavorite' : 'favorite';
            
            fetch('<?php echo SITE_URL; ?>/api/favorite.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=' + action + '&target_type=' + targetType + '&target_id=' + targetId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateFavoriteButton(this, data);
                } else {
                    alert(data.message || '操作失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，请重试');
            });
        });
    });
})();
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
