<?php
// Connect to the database using the existing config
require_once 'admin/config/db.php';

// Fetch categorized blog counts for sidebar
$cat_count_stmt = $pdo->query("
    SELECT c.*, COUNT(p.id) as post_count 
    FROM blog_categories c 
    LEFT JOIN blog_posts p ON c.id = p.category_id AND p.status = 'published'
    WHERE c.status = 'active'
    GROUP BY c.id 
    ORDER BY c.name ASC
");
$categories_with_count = $cat_count_stmt->fetchAll();

// Fetch "Recent Posts" (Top 4 latest)
$recent_stmt = $pdo->query("
    SELECT * FROM blog_posts 
    WHERE status = 'published' 
    ORDER BY created_at DESC 
    LIMIT 4
");
$recent_posts = $recent_stmt->fetchAll();

// Pagination and Filtering logic
$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? (int)$_GET['page'] : 1;
$per_page = 4;
$offset = ($page - 1) * $per_page;

$category_filter = isset($_GET['category']) ? trim($_GET['category']) : '';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

$where_clause = "WHERE p.status = 'published'";
$params = [];

if ($category_filter) {
    $where_clause .= " AND c.slug = ?";
    $params[] = $category_filter;
}
if ($search_query) {
    $where_clause .= " AND (p.title LIKE ? OR p.content LIKE ?)";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
}

// Count total for pagination
$count_sql = "
    SELECT COUNT(p.id) 
    FROM blog_posts p
    LEFT JOIN blog_categories c ON p.category_id = c.id
    $where_clause
";
$total_stmt = $pdo->prepare($count_sql);
$total_stmt->execute($params);
$total_posts = $total_stmt->fetchColumn();
$total_pages = ceil($total_posts / $per_page);

// Fetch items
$sql = "
    SELECT p.*, c.name as category_name, c.slug as category_slug
    FROM blog_posts p
    LEFT JOIN blog_categories c ON p.category_id = c.id
    $where_clause
    ORDER BY p.created_at DESC
    LIMIT $per_page OFFSET $offset
";
$post_stmt = $pdo->prepare($sql);
$post_stmt->execute($params);
$blog_posts = $post_stmt->fetchAll();

$pageTitle = "Blog | Construction & Design Insights | MK Construction & Builder";
$pageDesc = "Stay updated with the latest trends in construction, architecture, and interior design in Krishnagiri. Professional tips from MK Construction.";
$pageKeywords = "construction blog, architecture tips, interior design ideas, builder news krishnagiri";
include 'includes/header.php';
?>

    <!-- Page Header -->
    <div class="page-header" style="background-image: linear-gradient(rgba(17, 24, 39, 0.8), rgba(17, 24, 39, 0.9)), url('assets/img/hero-blog.jpg'); text-align: left; padding: 120px 0;">
        <div class="container">
            <h1 class="page-title" style="font-size: 3rem; margin-bottom: 10px;">Our Blog</h1>
            <div class="breadcrumb" style="justify-content: flex-start; gap: 8px;">
                <a href="index.php" style="color: rgba(255,255,255,0.8);">Home</a>
                <i class="fa-solid fa-chevron-right" style="font-size: 0.8rem; color: rgba(255,255,255,0.6);"></i>
                <span style="color: var(--primary-color); font-weight: 500;">Blog</span>
            </div>
        </div>
    </div>

    <!-- Blog Layout Section -->
    <section class="section-padding bg-light" style="padding: 80px 0;">
        <div class="container">
            <div class="blog-layout" style="display: grid; grid-template-columns: 1fr 350px; gap: 40px; align-items: start;">
                
                <!-- Left Side: Main Content -->
                <div class="blog-main-content">
                    <?php if(count($blog_posts) > 0): ?>
                        <?php foreach($blog_posts as $post): 
                            $date = new DateTime($post['created_at']);
                            $formatted_date = $date->format('d M, Y');
                        ?>
                            <div class="blog-card" style="background: var(--white); border-radius: 12px; overflow: hidden; box-shadow: var(--shadow-sm); margin-bottom: 40px; border: 1px solid rgba(0,0,0,0.05);">
                                <div class="blog-image">
                                    <a href="blog-details.php?slug=<?= htmlspecialchars($post['slug']) ?>">
                                        <img src="<?= htmlspecialchars($post['image_path']) ?>" alt="<?= htmlspecialchars($post['title']) ?>" style="width: 100%; height: auto; max-height: 450px; object-fit: cover; display: block;">
                                    </a>
                                </div>
                                <div class="blog-content" style="padding: 35px;">
                                    <div class="blog-meta" style="display: flex; gap: 20px; font-size: 0.9rem; color: var(--text-muted); margin-bottom: 15px; font-weight: 500;">
                                        <span><i class="fa-regular fa-user" style="color: var(--primary-color); margin-right: 6px;"></i> By <?= htmlspecialchars($post['author'] ?? 'Admin') ?></span>
                                        <span><i class="fa-regular fa-calendar" style="color: var(--primary-color); margin-right: 6px;"></i> <?= $formatted_date ?></span>
                                    </div>
                                    <h2 class="blog-title" style="font-family: var(--font-serif); font-size: 1.8rem; margin-bottom: 18px; line-height: 1.3;">
                                        <a href="blog-details.php?slug=<?= htmlspecialchars($post['slug']) ?>" style="color: var(--dark-nav); text-decoration: none; transition: var(--transition);">
                                            <?= htmlspecialchars($post['title']) ?>
                                        </a>
                                    </h2>
                                    <p class="blog-excerpt" style="color: var(--text-muted); line-height: 1.7; margin-bottom: 25px; font-size: 1rem;">
                                        <?= (strlen(strip_tags($post['content'])) > 160) ? substr(strip_tags($post['content']), 0, 160) . '...' : strip_tags($post['content']) ?>
                                    </p>
                                    <a href="blog-details.php?slug=<?= htmlspecialchars($post['slug']) ?>" class="btn-read-more" style="display: inline-flex; align-items: center; gap: 8px; font-weight: 700; color: var(--dark-nav); text-decoration: none; border: 1px solid #e2e8f0; padding: 10px 24px; border-radius: 6px; font-size: 0.9rem; transition: var(--transition); text-transform: uppercase;">
                                        READ MORE <i class="fa-solid fa-arrow-right" style="color: var(--text-muted); font-size: 0.8rem; transition: var(--transition);"></i>
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>

                        <!-- Pagination -->
                        <?php if($total_pages > 1): ?>
                            <div class="pagination" style="display: flex; justify-content: center; gap: 10px; margin-top: 50px;">
                                <?php if($page > 1): ?>
                                    <a href="?page=<?= $page - 1 ?><?= $category_filter ? '&category=' . $category_filter : '' ?><?= $search_query ? '&search=' . urlencode($search_query) : '' ?>" class="page-link"><i class="fa-solid fa-chevron-left"></i></a>
                                <?php endif; ?>
                                <?php for($i = 1; $i <= $total_pages; $i++): ?>
                                    <a href="?page=<?= $i ?><?= $category_filter ? '&category=' . $category_filter : '' ?><?= $search_query ? '&search=' . urlencode($search_query) : '' ?>" class="page-link <?= ($i == $page) ? 'active' : '' ?>"><?= $i ?></a>
                                <?php endfor; ?>
                                <?php if($page < $total_pages): ?>
                                    <a href="?page=<?= $page + 1 ?><?= $category_filter ? '&category=' . $category_filter : '' ?><?= $search_query ? '&search=' . urlencode($search_query) : '' ?>" class="page-link"><i class="fa-solid fa-chevron-right"></i></a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="no-results text-center" style="padding: 100px 20px; background: var(--white); border-radius: 12px; border: 1px dashed #e2e8f0;">
                            <i class="fa-solid fa-newspaper" style="font-size: 4rem; color: #e2e8f0; margin-bottom: 20px;"></i>
                            <h3>No Articles Found</h3>
                            <a href="blog.php" class="btn btn-primary mt-4">View All Posts</a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Sidebar -->
                <aside class="blog-sidebar">
                    <div class="sidebar-widget">
                        <h3 class="widget-title">Search Blog</h3>
                        <form action="blog.php" method="GET" style="position: relative;">
                            <input type="text" name="search" placeholder="Search articles..." value="<?= htmlspecialchars($search_query) ?>" class="form-control" style="padding-right: 45px;">
                            <button type="submit" style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); background: var(--primary-color); border: none; color: white; width: 35px; height: 35px; border-radius: 5px;"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </form>
                    </div>
                    
                    <div class="sidebar-widget">
                        <h3 class="widget-title">Categories</h3>
                        <div class="category-list">
                            <?php foreach($categories_with_count as $cat): ?>
                                <a href="?category=<?= htmlspecialchars($cat['slug']) ?>" class="<?= ($category_filter == $cat['slug']) ? 'active' : '' ?>">
                                    <span><?= htmlspecialchars($cat['name']) ?></span>
                                    <span class="count"><?= $cat['post_count'] ?></span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="sidebar-widget">
                        <h3 class="widget-title">Recent Posts</h3>
                        <div class="recent-posts">
                            <?php foreach($recent_posts as $post): ?>
                                <div class="recent-post-item">
                                    <div class="recent-post-thumb">
                                        <a href="blog-details.php?slug=<?= htmlspecialchars($post['slug']) ?>"><img src="<?= htmlspecialchars($post['image_path']) ?>" alt=""></a>
                                    </div>
                                    <div class="recent-post-content">
                                        <h4><a href="blog-details.php?slug=<?= htmlspecialchars($post['slug']) ?>"><?= htmlspecialchars($post['title']) ?></a></h4>
                                        <span><?= date('M d, Y', strtotime($post['created_at'])) ?></span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </aside>
            </div>
        </div>
    </section>

    <style>
        .pagination .page-link { width: 40px; height: 40px; border-radius: 50%; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; color: var(--dark-nav); text-decoration: none; transition: 0.3s; }
        .pagination .page-link.active { background: var(--primary-color); color: white; border-color: var(--primary-color); }
        .sidebar-widget { background: white; padding: 25px; border-radius: 10px; margin-bottom: 30px; box-shadow: var(--shadow-sm); }
        .widget-title { font-size: 1.25rem; margin-bottom: 20px; padding-left: 10px; border-left: 4px solid var(--primary-color); }
        .category-list a { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f1f5f9; color: var(--text-muted); text-decoration: none; transition: 0.3s; }
        .category-list a:hover, .category-list a.active { color: var(--primary-color); }
        .recent-post-item { display: flex; gap: 15px; margin-bottom: 15px; align-items: center; }
        .recent-post-thumb { width: 70px; height: 70px; border-radius: 8px; overflow: hidden; flex-shrink: 0; }
        .recent-post-thumb img { width: 100%; height: 100%; object-fit: cover; }
        .recent-post-content h4 { font-size: 0.95rem; margin-bottom: 5px; line-height: 1.4; }
        .recent-post-content h4 a { color: var(--dark-nav); text-decoration: none; }
        .recent-post-content span { font-size: 0.8rem; color: var(--text-muted); }
    </style>

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