<?php
/**
 * Hostxolo - Blog Page
 */
require_once 'config.php';

// Get blog categories
$categories = [];
try {
    $stmt = db()->query("SELECT * FROM blog_categories WHERE status = 1 ORDER BY name");
    $categories = $stmt->fetchAll();
} catch (PDOException $e) {
    // Continue with empty categories
}

// Get search and filter parameters
$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 6;
$offset = ($page - 1) * $per_page;

// Build query
$sql = "SELECT bp.*, bc.name as category_name, bc.slug as category_slug 
        FROM blog_posts bp 
        LEFT JOIN blog_categories bc ON bp.category_id = bc.id 
        WHERE bp.status = 'published'";

$params = [];

if (!empty($search)) {
    $sql .= " AND (bp.title LIKE ? OR bp.content LIKE ? OR bp.excerpt LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param]);
}

if (!empty($category_filter)) {
    $sql .= " AND bc.slug = ?";
    $params[] = $category_filter;
}

// Get total count
$count_sql = str_replace("SELECT bp.*, bc.name as category_name, bc.slug as category_slug", "SELECT COUNT(*) as total", $sql);
try {
    $stmt = db()->prepare($count_sql);
    $stmt->execute($params);
    $total = $stmt->fetch()['total'] ?? 0;
} catch (PDOException $e) {
    $total = 0;
}

// Add ordering and limit
$sql .= " ORDER BY bp.published_at DESC LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;

// Get posts
try {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $posts = $stmt->fetchAll();
} catch (PDOException $e) {
    $posts = [];
}

$total_pages = ceil($total / $per_page);

include 'includes/header.php';
?>

<!-- Page Header -->
<section class="page-header">
    <div class="container">
        <h1>Our Blog</h1>
        <p>Insights, tips, and strategies for business growth</p>
    </div>
</section>

<!-- Blog Section -->
<section class="py-5">
    <div class="container">
        <!-- Search and Filter -->
        <div class="row mb-4">
            <div class="col-md-6">
                <form action="" method="GET" class="d-flex">
                    <?php if ($category_filter): ?>
                        <input type="hidden" name="category" value="<?php echo $category_filter; ?>">
                    <?php endif; ?>
                    <input type="text" name="search" class="form-control me-2" placeholder="Search articles..." 
                           value="<?php echo $search; ?>">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i></button>
                </form>
            </div>
            <div class="col-md-6 text-md-end mt-3 mt-md-0">
                <div class="dropdown d-inline-block">
                    <button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <?php echo $category_filter ? 'Category: ' . $category_filter : 'All Categories'; ?>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="<?php echo BASE_URL; ?>blog.php">All Categories</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <?php foreach ($categories as $cat): ?>
                            <li><a class="dropdown-item" href="<?php echo BASE_URL; ?>blog.php?category=<?php echo $cat['slug']; ?>">
                                <?php echo $cat['name']; ?>
                            </a></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- Posts Grid -->
        <?php if (empty($posts)): ?>
            <div class="text-center py-5">
                <i class="bi bi-journal-text text-muted" style="font-size: 4rem;"></i>
                <p class="text-muted mt-3">
                    <?php echo $search ? 'No articles found matching your search.' : 'No articles published yet.'; ?>
                </p>
                <?php if ($search): ?>
                    <a href="<?php echo BASE_URL; ?>blog.php" class="btn btn-primary">View All Articles</a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($posts as $post): ?>
                <div class="col-md-6 col-lg-4">
                    <article class="card h-100 blog-card border-0 shadow-sm">
                        <div class="blog-image bg-primary bg-opacity-10 d-flex align-items-center justify-content-center" style="height: 200px;">
                            <i class="bi bi-newspaper text-primary" style="font-size: 4rem;"></i>
                        </div>
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <?php if ($post['category_name']): ?>
                                    <span class="badge bg-primary bg-opacity-10 text-primary">
                                        <?php echo $post['category_name']; ?>
                                    </span>
                                <?php endif; ?>
                                <small class="text-muted">
                                    <i class="bi bi-calendar me-1"></i><?php echo format_date($post['published_at']); ?>
                                </small>
                            </div>
                            <h4 class="card-title">
                                <a href="<?php echo BASE_URL; ?>blog-post.php?slug=<?php echo $post['slug']; ?>" class="text-decoration-none">
                                    <?php echo $post['title']; ?>
                                </a>
                            </h4>
                            <p class="card-text text-muted">
                                <?php echo substr(strip_tags($post['excerpt'] ?? $post['content']), 0, 120) . '...'; ?>
                            </p>
                            <div class="d-flex justify-content-between align-items-center mt-3">
                                <small class="text-muted">
                                    <i class="bi bi-person me-1"></i><?php echo $post['author_name']; ?>
                                </small>
                                <a href="<?php echo BASE_URL; ?>blog-post.php?slug=<?php echo $post['slug']; ?>" class="btn btn-link p-0">
                                    Read More <i class="bi bi-arrow-right"></i>
                                </a>
                            </div>
                        </div>
                    </article>
                </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav class="mt-5">
                <ul class="pagination justify-content-center">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo $search; ?>&category=<?php echo $category_filter; ?>">
                                <i class="bi bi-chevron-left"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>&category=<?php echo $category_filter; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo $search; ?>&category=<?php echo $category_filter; ?>">
                                <i class="bi bi-chevron-right"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</section>

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