<?php
/**
 * Public Blog Listing Page
 * Display all published blog posts
 */

require_once '../config/config.php';

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);

$pageTitle = 'Blog - ' . getSiteName();

$db = getDB();

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

// Get total count
$stmt = $db->prepare("SELECT COUNT(*) FROM cms_posts WHERE status = 'published'");
$stmt->execute();
$totalPosts = $stmt->fetchColumn();
$totalPages = ceil($totalPosts / $perPage);

// Get posts
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name
    FROM cms_posts p
    LEFT JOIN users u ON p.author_id = u.id
    WHERE p.status = 'published'
    ORDER BY p.published_at DESC
    LIMIT ? OFFSET ?
");
$stmt->execute([$perPage, $offset]);
$posts = $stmt->fetchAll();

// Get featured post (fallback: latest post)
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name
    FROM cms_posts p
    LEFT JOIN users u ON p.author_id = u.id
    WHERE p.status = 'published'
    ORDER BY p.published_at DESC
    LIMIT 1
");
$stmt->execute();
$featuredPost = $stmt->fetch();

// Include appropriate header based on device
if ($isMobile) {
    include '../templates/mobile-header.php';
} else {
    include '../templates/header.php';
}
?>

<!-- Hero Section -->
<section class="bg-primary text-white py-5">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <h1 class="display-4 fw-bold mb-3">Our Blog</h1>
                <p class="lead mb-0">
                    Stay updated with the latest research insights, medical breakthroughs, 
                    and healthcare innovations in OBGYN.
                </p>
            </div>
            <div class="col-lg-4 text-lg-end">
                <i class="fas fa-newspaper fa-5x opacity-50"></i>
            </div>
        </div>
    </div>
</section>

<!-- Featured Post -->
<?php if ($featuredPost): ?>
<section class="py-5 bg-light">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <div class="badge bg-warning text-dark mb-3">
                    <i class="fas fa-star"></i> Featured Post
                </div>
            </div>
        </div>
        <div class="row g-4">
            <div class="col-lg-6">
                <?php if ($featuredPost['featured_image']): ?>
                    <img src="<?php echo e($featuredPost['featured_image']); ?>" 
                         alt="<?php echo e($featuredPost['title']); ?>"
                         class="img-fluid rounded shadow">
                <?php else: ?>
                    <div class="bg-secondary rounded d-flex align-items-center justify-content-center" 
                         style="height: 400px;">
                        <i class="fas fa-image fa-5x text-white opacity-25"></i>
                    </div>
                <?php endif; ?>
            </div>
            <div class="col-lg-6">
                <h2 class="h1 mb-3">
                    <a href="post.php?slug=<?php echo e($featuredPost['slug']); ?>" 
                       class="text-decoration-none text-dark">
                        <?php echo e($featuredPost['title']); ?>
                    </a>
                </h2>
                <div class="text-muted mb-3">
                    <i class="fas fa-user"></i> <?php echo e($featuredPost['first_name'] . ' ' . $featuredPost['last_name']); ?>
                    <span class="mx-2">•</span>
                    <i class="fas fa-calendar"></i> <?php echo date('F j, Y', strtotime($featuredPost['published_at'])); ?>
                    <span class="mx-2">•</span>
                    <i class="fas fa-eye"></i> <?php echo number_format(isset($featuredPost['views']) ? $featuredPost['views'] : (isset($featuredPost['views_count']) ? $featuredPost['views_count'] : 0)); ?> views
                </div>
                <p class="lead mb-4">
                    <?php echo e($featuredPost['excerpt'] ?: substr(strip_tags($featuredPost['content']), 0, 200) . '...'); ?>
                </p>
                <a href="post.php?slug=<?php echo e($featuredPost['slug']); ?>" 
                   class="btn btn-primary btn-lg">
                    Read More <i class="fas fa-arrow-right ms-2"></i>
                </a>
            </div>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Blog Posts Grid -->
<section class="py-5">
    <div class="container">
        <div class="row mb-4">
            <div class="col-12">
                <h2 class="h3 mb-0">Latest Posts</h2>
            </div>
        </div>

        <?php if (empty($posts)): ?>
            <div class="row">
                <div class="col-12">
                    <div class="alert alert-info text-center py-5">
                        <i class="fas fa-info-circle fa-3x mb-3"></i>
                        <h4>No blog posts yet</h4>
                        <p class="mb-0">Check back soon for new content!</p>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($posts as $post): ?>
                    <?php if ($featuredPost && $post['id'] === $featuredPost['id']) continue; ?>
                    
                    <div class="col-lg-4 col-md-6">
                        <div class="card h-100 shadow-sm hover-shadow">
                            <?php if ($post['featured_image']): ?>
                                <img src="<?php echo e($post['featured_image']); ?>" 
                                     class="card-img-top" 
                                     alt="<?php echo e($post['title']); ?>"
                                     style="height: 200px; object-fit: cover;">
                            <?php else: ?>
                                <div class="bg-secondary d-flex align-items-center justify-content-center" 
                                     style="height: 200px;">
                                    <i class="fas fa-image fa-3x text-white opacity-25"></i>
                                </div>
                            <?php endif; ?>
                            
                            <div class="card-body d-flex flex-column">
                                <h5 class="card-title">
                                    <a href="post.php?slug=<?php echo e($post['slug']); ?>" 
                                       class="text-decoration-none text-dark">
                                        <?php echo e($post['title']); ?>
                                    </a>
                                </h5>
                                
                                <div class="text-muted small mb-3">
                                    <i class="fas fa-user"></i> <?php echo e($post['first_name'] . ' ' . $post['last_name']); ?>
                                    <span class="mx-1">•</span>
                                    <i class="fas fa-calendar"></i> <?php echo date('M j, Y', strtotime($post['published_at'])); ?>
                                </div>
                                
                                <p class="card-text flex-grow-1">
                                    <?php echo e($post['excerpt'] ?: substr(strip_tags($post['content']), 0, 120) . '...'); ?>
                                </p>
                                
                                <div class="d-flex justify-content-between align-items-center">
                                    <a href="post.php?slug=<?php echo e($post['slug']); ?>" 
                                       class="btn btn-outline-primary btn-sm">
                                        Read More <i class="fas fa-arrow-right ms-1"></i>
                                    </a>
                                    <small class="text-muted">
                                        <i class="fas fa-eye"></i> <?php echo number_format(isset($post['views']) ? $post['views'] : (isset($post['views_count']) ? $post['views_count'] : 0)); ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="row mt-5">
                    <div class="col-12">
                        <nav aria-label="Blog pagination">
                            <ul class="pagination justify-content-center">
                                <!-- Previous -->
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>">
                                        <i class="fas fa-chevron-left"></i> Previous
                                    </a>
                                </li>
                                
                                <!-- Page Numbers -->
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                    <?php if ($i == 1 || $i == $totalPages || abs($i - $page) <= 2): ?>
                                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                        </li>
                                    <?php elseif (abs($i - $page) == 3): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <!-- Next -->
                                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>">
                                        Next <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</section>

<style>
.hover-shadow {
    transition: all 0.3s ease;
}

.hover-shadow:hover {
    transform: translateY(-5px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

.card-img-top {
    transition: transform 0.3s ease;
}

.card:hover .card-img-top {
    transform: scale(1.05);
}

.card {
    overflow: hidden;
}
</style>

<?php // Include appropriate footer based on device
if ($isMobile) {
    include '../templates/mobile-footer.php';
} else {
    include '../templates/footer.php';
} ?>
