<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

$category_slug = $_GET['cat'] ?? '';
$page_title = 'Category';

if (!$category_slug) {
    header('HTTP/1.0 404 Not Found');
    $page_title = 'Category Not Found';
    include 'includes/header.php';
    echo '<div class="container"><div class="error-message"><h1>Category Not Found</h1><p>The category you are looking for does not exist.</p><a href="' . BASE_URL . 'home" class="btn btn-primary">Back to Home</a></div></div>';
    include 'includes/footer.php';
    exit;
}

$posts = getPostsByCategory($category_slug);
$category = getCategoryBySlug($category_slug); // Assuming this function exists, or we can get from posts

if ($category) {
    $page_title = $category['name'];
} else {
    $page_title = ucfirst($category_slug);
}

include 'includes/header.php';
?>

<section class="category-posts">
    <div class="container">
        <h1 class="section-title"><?php echo htmlspecialchars($page_title); ?></h1>

        <?php if ($posts): ?>
            <div class="posts-grid">
                <?php foreach ($posts as $post): ?>
                    <article class="post-card">
                        <div class="post-header">
                            <span class="post-category"><?php echo htmlspecialchars($post['category_name']); ?></span>
                            <time class="post-date"><?php echo formatDate($post['created_at']); ?></time>
                        </div>
                        <h3 class="post-title">
                            <a href="<?php echo BASE_URL; ?>post.php?slug=<?php echo urlencode($post['slug']); ?>">
                                <?php echo htmlspecialchars($post['title']); ?>
                            </a>
                        </h3>
                        <p class="post-excerpt">
                            <?php echo htmlspecialchars(truncateText(strip_tags($post['content']))); ?>
                        </p>
                        <div class="post-footer">
                            <span class="post-author">By <?php echo htmlspecialchars($post['author_name']); ?></span>
                            <a href="<?php echo BASE_URL; ?>post.php?slug=<?php echo urlencode($post['slug']); ?>" class="read-more">
                                Read More <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="no-posts">
                <i class="fas fa-newspaper"></i>
                <p>No posts found in this category. Check back soon!</p>
            </div>
        <?php endif; ?>
    </div>
</section>

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