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

$keyword = isset($_GET['q']) ? trim($_GET['q']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$perPage = 20;

$posts = [];
$totalResults = 0;
$totalPages = 0;

if ($keyword) {
    $db = Database::getInstance();
    $offset = ($page - 1) * $perPage;
    $searchTerm = '%' . $keyword . '%';
    
    // 调试信息
    $debug = isset($_GET['debug']) ? true : false;
    
    $countSql = "SELECT COUNT(*) as total FROM posts WHERE status = 1 AND (title LIKE ? OR content LIKE ?)";
    $countResult = $db->queryOne($countSql, [$searchTerm, $searchTerm]);
    $totalResults = $countResult ? $countResult['total'] : 0;
    $totalPages = ceil($totalResults / $perPage);
    
    // 简化查询，先不使用子查询
    $sql = "SELECT p.*, c.name as category_name, u.username, u.avatar 
            FROM posts p 
            LEFT JOIN categories c ON p.category_id = c.id 
            LEFT JOIN users u ON p.user_id = u.id 
            WHERE p.status = 1 AND (p.title LIKE ? OR p.content LIKE ?)
            ORDER BY p.is_top DESC, p.created_at DESC 
            LIMIT ? OFFSET ?";
    $result = $db->query($sql, [$searchTerm, $searchTerm, $perPage, $offset]);
    $posts = $result === false ? [] : $result;
}

$pageTitle = $keyword ? '搜索: ' . $keyword : '搜索';
include __DIR__ . '/templates/header.php';
?>

<div class="search-page">
    <div class="search-box-large">
        <form action="<?php echo SITE_URL; ?>/search.php" method="get" class="search-form-large">
            <input type="text" name="q" class="search-input-large" placeholder="搜索帖子标题或内容..." value="<?php echo e($keyword); ?>" required>
            <button type="submit" class="search-btn-large">
                <i class="fas fa-search"></i>
                <span>搜索</span>
            </button>
        </form>
    </div>
    
    <?php if ($keyword): ?>
        <div class="search-stats">
            找到 <strong><?php echo $totalResults; ?></strong> 条关于 "<strong><?php echo e($keyword); ?></strong>" 的结果
        </div>
        
        <?php if (empty($posts)): ?>
            <div class="empty-search">
                <i class="fas fa-search"></i>
                <h3>未找到相关结果</h3>
                <p>请尝试使用其他关键词搜索</p>
            </div>
        <?php else: ?>
            <div class="search-results">
                <?php foreach ($posts as $post): ?>
                    <div class="search-result-item">
                        <div class="search-result-title">
                            <?php if ($post['is_top']): ?>
                                <span class="pinned-icon"><i class="fas fa-thumbtack"></i></span>
                            <?php endif; ?>
                            <a href="<?php echo SITE_URL; ?>/post.php?id=<?php echo $post['id']; ?>">
                                <?php echo highlightKeyword(e($post['title']), $keyword); ?>
                            </a>
                        </div>
                        <div class="search-result-content">
                            <?php echo highlightKeyword(e(strip_tags($post['content'])), $keyword); ?>
                        </div>
                        <div class="search-result-meta">
                            <?php if ($post['category_name']): ?>
                                <span class="category-badge" style="background: var(--primary-color); color: #fff;">
                                    <?php echo e($post['category_name']); ?>
                                </span>
                            <?php endif; ?>
                            <a href="<?php echo SITE_URL; ?>/user.php?id=<?php echo $post['user_id']; ?>">
                                <i class="fas fa-user"></i> <?php echo e($post['username']); ?>
                            </a>
                            <span><i class="fas fa-clock"></i> <?php echo formatTime($post['created_at']); ?></span>
                            <span><i class="fas fa-comment"></i> <?php echo $post['reply_count'] ?? 0; ?></span>
                            <span><i class="fas fa-eye"></i> <?php echo $post['view_count']; ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?q=<?php echo urlencode($keyword); ?>&page=<?php echo $page - 1; ?>"><i class="fas fa-chevron-left"></i></a>
                    <?php else: ?>
                        <span class="disabled"><i class="fas fa-chevron-left"></i></span>
                    <?php endif; ?>
                    
                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    
                    if ($startPage > 1) {
                        echo '<a href="?q=' . urlencode($keyword) . '&page=1">1</a>';
                        if ($startPage > 2) echo '<span>...</span>';
                    }
                    
                    for ($i = $startPage; $i <= $endPage; $i++) {
                        if ($i == $page) {
                            echo '<span class="current">' . $i . '</span>';
                        } else {
                            echo '<a href="?q=' . urlencode($keyword) . '&page=' . $i . '">' . $i . '</a>';
                        }
                    }
                    
                    if ($endPage < $totalPages) {
                        if ($endPage < $totalPages - 1) echo '<span>...</span>';
                        echo '<a href="?q=' . urlencode($keyword) . '&page=' . $totalPages . '">' . $totalPages . '</a>';
                    }
                    ?>
                    
                    <?php if ($page < $totalPages): ?>
                        <a href="?q=<?php echo urlencode($keyword); ?>&page=<?php echo $page + 1; ?>"><i class="fas fa-chevron-right"></i></a>
                    <?php else: ?>
                        <span class="disabled"><i class="fas fa-chevron-right"></i></span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    <?php else: ?>
        <div class="empty-search">
            <i class="fas fa-search"></i>
            <h3>输入关键词开始搜索</h3>
            <p>搜索帖子标题和内容</p>
        </div>
    <?php endif; ?>
</div>

<?php
function highlightKeyword($text, $keyword) {
    if (empty($keyword)) return $text;
    $keyword = preg_quote($keyword, '/');
    return preg_replace('/(' . $keyword . ')/i', '<mark>$1</mark>', $text);
}

include __DIR__ . '/templates/footer.php';
?>
