<!DOCTYPE html>
<html lang="en">


<?php
include 'db.php'; // Ensure db conn is available

// Parameters
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 6; // Blogs per page
$offset = ($page - 1) * $limit;

$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$category_filters = isset($_GET['category']) && is_array($_GET['category']) ? array_map('intval', $_GET['category']) : [];
$tag_filter = isset($_GET['tag']) ? $conn->real_escape_string($_GET['tag']) : '';

// Build Where Clause for Active Blogs
$whereClauses = ["is_active = 1"];

if ($search) {
    $whereClauses[] = "(title LIKE '%$search%' OR content LIKE '%$search%')";
}
if ($tag_filter) {
    // tags are JSON array
    $whereClauses[] = "JSON_CONTAINS(tags, '\"$tag_filter\"')"; 
}
if (!empty($category_filters)) {
    $cat_clauses = [];
    foreach($category_filters as $cf) {
        $cat_clauses[] = "JSON_CONTAINS(categories, '\"$cf\"')";
    }
    // Match ANY of the checked categories (OR)
    $whereClauses[] = "(" . implode(" OR ", $cat_clauses) . ")";
}

$whereSQL = "WHERE " . implode(" AND ", $whereClauses);

// Fetch Total For Pagination
$total_query = $conn->query("SELECT COUNT(id) as total FROM blogs $whereSQL");
$total_blogs = $total_query->fetch_assoc()['total'];
$total_pages = ceil($total_blogs / $limit);

// Fetch Blogs
$blogs_sql = "SELECT id, title, slug, image, short_desc, categories, published_at FROM blogs $whereSQL ORDER BY published_at DESC LIMIT $offset, $limit";
$blogs_result = $conn->query($blogs_sql);

// Fetch All Categories for Sidebar (flat list)
$cats_q = $conn->query("SELECT id, name FROM blog_categories WHERE is_active = 1 ORDER BY name ASC");
$categories = [];
if ($cats_q && $cats_q->num_rows > 0) {
    while($cat = $cats_q->fetch_assoc()) {
        $categories[] = $cat;
    }
}

// Fetch Recent Posts for Sidebar
$recent_sql = "SELECT title, slug, image, categories FROM blogs WHERE is_active = 1 ORDER BY published_at DESC LIMIT 4";
$recent_result = $conn->query($recent_sql);

// Fetch All Unique Tags for Sidebar (parsing JSON tags column)
$tags_q = $conn->query("SELECT tags FROM blogs WHERE is_active = 1 AND tags != '[]' AND tags IS NOT NULL");
$all_tags_list = [];
while($t = $tags_q->fetch_assoc()) {
    $decoded = json_decode($t['tags'], true);
    if(is_array($decoded)){
        foreach($decoded as $tag){
            $tag = trim($tag);
            if(!empty($tag) && !in_array($tag, $all_tags_list)){
                $all_tags_list[] = $tag;
            }
        }
    }
}

// Helper block to fetch main category name for blog cards
function getCatName($cat_id, $conn) {
    $q = $conn->query("SELECT name FROM blog_categories WHERE id = ".intval($cat_id));
    if($q && $q->num_rows > 0){
        return $q->fetch_assoc()['name'];
    }
    return 'Blog';
}

// Generate base query string for pagination
$pagination_qs = [];
if($search) $pagination_qs[] = "search=".urlencode($search);
if($tag_filter) $pagination_qs[] = "tag=".urlencode($tag_filter);
if(!empty($category_filters)) {
    foreach($category_filters as $cf) {
        $pagination_qs[] = "category[]=".intval($cf);
    }
}
$base_qs = empty($pagination_qs) ? "all-blogs?" : "all-blogs?" . implode("&", $pagination_qs) . "&";



?>

<?php 

$title = "Blogs | James Thompson Textiles";
$description = "Read the latest fabric insights, updates, and stories from James Thompson Textiles.";
$keywords = "fabric blog, textile blog USA, cotton fabric blog, textile industry insights, fabric manufacturing blog, James Thompson Textiles blog, textile insights, fabric trends USA, textile knowledge center, cotton fabric guides, sustainable textile insights, industrial fabric information, fabric selection guide, home textile trends, eco-friendly fabric blog, cotton fabric buying guide USA, textile manufacturing insights and trends, how to choose the right cotton fabric, fabric supplier knowledge blog, sustainable fabric industry updates, industrial fabric applications guide, wholesale fabric industry news USA";
$image = "https://jthompsontextiles.com/assets/images/others/share-img.png";
$current_url = "https://jthompsontextiles.com/all-blogs";

include 'layouts/header.php'; ?>

<body>
    <?php include 'layouts/navbar.php'; ?>
<main id="content" class="wrapper layout-page">
    <section class="page-title z-index-2 position-relative" data-animated-id="1">
        <div class="bg-body-secondary">
            <div class="container">
                <nav class="py-4 lh-30px" aria-label="breadcrumb">
                    <ol class="breadcrumb justify-content-center py-1">
                        <li class="breadcrumb-item"><a href="index.html">Home</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Blogs</li>
                    </ol>
                </nav>
            </div>
        </div>
        <div class="text-center py-13" style="padding: 4rem 0;">
            <div class="container">
                <h2 class="mb-5">Blogs</h2>
                <?php if($search): ?> <p>Search Results for: "<b><?= htmlspecialchars($search) ?></b>"</p> <?php endif; ?>
                <?php if($tag_filter): ?> <p>Filtering by Tag: "<b><?= htmlspecialchars($tag_filter) ?></b>"</p> <?php endif; ?>
            </div>
        </div>
    </section>

    <div class="container mb-lg-18 mb-16 pb-3" data-animated-id="2">
        <div class="row">

            <!-- Blogs List Column -->
            <div class="col-lg-8">
                <div class="row gy-30px">
                    
                    <?php if($blogs_result && $blogs_result->num_rows > 0): ?>
                        <?php while($blog = $blogs_result->fetch_assoc()): 
                            $image_path = "uploads/blogs/" . $blog['image'];
                            if(!file_exists($image_path) || empty($blog['image'])) $image_path = "assets/images/placeholder.jpg";
                            
                            // Get first Category Name
                            $b_cats = json_decode($blog['categories'], true);
                            $first_cat = 'Blog';
                            $first_cat_id = 0;
                            if(is_array($b_cats) && count($b_cats) > 0){
                                $first_cat_id = $b_cats[0];
                                $first_cat = getCatName($first_cat_id, $conn);
                            }
                        ?>
                        <div class="col-sm-6 mb-4">
                            <article class="card card-post-grid-2 bg-transparent border-0 animate__fadeInUp animate__animated" data-animate="fadeInUp">
                                <figure class="card-img-top mb-4 position-relative overflow-hidden" style="border-radius: 8px;">
                                    <a href="blog-detail?slug=<?= $blog['slug'] ?>" class="text-primary fs-18px" title="<?= htmlspecialchars($blog['title']) ?>">
                                        <img src="<?= $image_path ?>" class="img-fluid w-100" alt="<?= htmlspecialchars($blog['title']) ?>" style="height: 240px; object-fit: cover;">
                                    </a>
                                </figure>
                                <div class="card-body p-0">
                                    <ul class="post-meta mt-5 list-inline lh-1.5 d-flex flex-wrap fs-13px text-uppercase ls-1 fw-semibold m-0 text-muted" style="font-size: 12px; letter-spacing: 0.5px;">
                                        <li class="list-inline-item border-end pe-3 me-3">
                                            <a class="text-reset text-decoration-none text-primary-hover" href="all-blogs?category[]=<?= $first_cat_id ?>" title="<?= htmlspecialchars($first_cat) ?>"><?= htmlspecialchars($first_cat) ?></a>
                                        </li>
                                        <li class="list-inline-item"><?= date('M jS, Y', strtotime($blog['published_at'])) ?></li>
                                    </ul>
                                    <h5 class="card-title fs-5 lh-1.5 mt-3 pt-2 mb-0 fw-semibold">
                                        <a class="text-primary fs-18px" href="blog-detail?slug=<?= $blog['slug'] ?>" title="<?= htmlspecialchars($blog['title']) ?>">
                                            <?= htmlspecialchars($blog['title']) ?>
                                        </a>
                                    </h5>
                                </div>
                            </article>
                        </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="col-12 py-5 text-center">
                            <h4>No blogs found.</h4>
                            <a href="all-blogs" class="btn btn-outline-primary mt-3">Clear Filters</a>
                        </div>
                    <?php endif; ?>
                    
                </div>
                
                <?php if($total_pages > 1): ?>
                <nav class="d-flex mt-5 pt-5 justify-content-center animate__fadeInUp animate__animated" aria-label="pagination">
                    <ul class="pagination m-0">
                        <?php if($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link rounded-circle d-flex align-items-center justify-content-center border-0 text-dark" href="<?= $base_qs ?>page=<?= $page - 1 ?>" aria-label="Previous">
                                <i class="fas fa-angle-double-left"></i>
                            </a>
                        </li>
                        <?php endif; ?>

                        <?php for($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                <a class="page-link <?= $i == $page ? 'bg-primary border-primary text-white' : 'text-primary border-0' ?>" href="<?= $base_qs ?>page=<?= $i ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>

                        <?php if($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link rounded-circle d-flex align-items-center justify-content-center border-0 text-primary" href="<?= $base_qs ?>page=<?= $page + 1 ?>" aria-label="Next">
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </nav>
                <?php endif; ?>
                
            </div>

            <!-- Sidebar Column -->
            <div class="col-lg-4">
                <div class="position-sticky top-0 pt-4">
                    
                    <!-- Search Widget -->
                    <aside class="primary-sidebar mt-12 pt-2 mt-lg-0 pt-lg-0 ps-xl-9 ms-xl-2">
                        <div class="widget widget-search mb-5">
                            <h4 class="widget-title fs-6 mb-4 fw-bold">Search</h4>
                            <form action="all-blogs" method="GET">
                                <div class="input-group">
                                    <input type="search" name="search" class="form-control rounded-0 py-2" placeholder="Search" value="<?= htmlspecialchars($search) ?>">
                                    <button type="submit" class="btn btn-light rounded-0 px-4 border-0">
                                        <svg class="icon icon-magnifying-glass-light"><use xlink:href="#icon-magnifying-glass-light"></use></svg>
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Categories Widget -->
                        <div class="widget widget-category mb-5">
                            <h4 class="widget-title fs-6 mb-4 fw-bold">Category</h4>
                            <form action="all-blogs" method="GET" id="category_filter_form">
                                <?php if($search): ?><input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>"><?php endif; ?>
                                <?php if($tag_filter): ?><input type="hidden" name="tag" value="<?= htmlspecialchars($tag_filter) ?>"><?php endif; ?>
                                
                                <ul class="list-unstyled mb-0" id="widget_category">
                                    <?php foreach($categories as $cat): ?>
                                        <li class="mb-2">
                                            <div class="d-flex align-items-center">
                                                <input class="form-check-input me-4 mt-0" type="checkbox" name="category[]" value="<?= $cat['id'] ?>" onchange="document.getElementById('category_filter_form').submit();" <?= in_array($cat['id'], $category_filters) ? 'checked' : '' ?> id="cat_<?= $cat['id'] ?>" style="cursor: pointer;">
                                                <label class="form-check-label <?= in_array($cat['id'], $category_filters) ? 'active-filter' : '' ?>" for="cat_<?= $cat['id'] ?>" style="cursor: pointer;">
                                                    <?= htmlspecialchars($cat['name']) ?>
                                                </label>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </form>
                        </div>
                        
                        <!-- Recent Posts Widget -->
                        <div class="widget widget-post mb-5">
                            <h4 class="widget-title fs-6 mb-5 fw-bold">Recent Blogs</h4>
                            <ul class="list-unstyled mb-0 row gy-3 gx-0">
                                <?php if($recent_result && $recent_result->num_rows > 0): ?>
                                    <?php while($rec = $recent_result->fetch_assoc()): 
                                        $r_img = "uploads/blogs/" . $rec['image'];
                                        if(!file_exists($r_img) || empty($rec['image'])) $r_img = "assets/images/placeholder.jpg";
                                        
                                        $r_cats = json_decode($rec['categories'], true);
                                        $r_cat_name = 'Blog';
                                        if(is_array($r_cats) && count($r_cats) > 0){
                                            $r_cat_name = getCatName($r_cats[0], $conn);
                                        }
                                    ?>
                                    <li class="col-12 mb-5">
                                        <div class="card border-0 flex-row bg-transparent align-items-center">
                                            <figure class="flex-shrink-0 mb-0 me-5" style="width: 60px;">
                                                <a href="blog-detail?slug=<?= $rec['slug'] ?>" class="d-block">
                                                    <img src="<?= $r_img ?>" class="img-fluid rounded" alt="<?= htmlspecialchars($rec['title']) ?>" style="height: 60px; object-fit: cover;">
                                                </a>
                                            </figure>
                                            <div class="card-body p-0">
                                                <h5 class="fw-semibold ls-1 text-uppercase mb-1" style="font-size: 11px; color: #888;"><?= $r_cat_name ?></h5>
                                                <h4 class="card-title mb-0" style="font-size: 16px; line-height: 1.3;">
                                                    <a class="text-decoration-none text-primary hover-hover-underline fw-semibold fs-15px" href="blog-detail?slug=<?= $rec['slug'] ?>">
                                                        <?= htmlspecialchars($rec['title']) ?>
                                                    </a>
                                                </h4>
                                            </div>
                                        </div>
                                    </li>
                                    <?php endwhile; ?>
                                <?php endif; ?>
                            </ul>
                        </div>
                        
                        <!-- Tags Widget 
                        <div class="widget widget-tags">
                            <h4 class="widget-title fs-6 mb-4 fw-bold">Tags</h4>
                            <ul class="w-100 list-unstyled d-flex flex-wrap mb-0 gap-2">
                                <?php foreach($all_tags_list as $tag): ?>
                                    <li class="me-6 mt-4">
                                        <a href="all-blogs?tag=<?= urlencode($tag) ?>" class="text-reset d-block text-decoration-none text-body-emphasis-hover text-hover-underline">
                                            <?= htmlspecialchars($tag) ?>
                                        </a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div> -->
                        
                    </aside>

                </div>
            </div>
            
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<?php include 'layouts/footer.php'; ?>
</body>
</html>
