<?php
include 'includes/db.php';
include 'includes/header.php';

// Pagination settings
$limit = 6;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Filter & Search handling
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category = isset($_GET['category']) ? trim($_GET['category']) : '';

$where_clauses = ["deleted_at IS NULL", "(status = 'published' OR status IS NULL)"];
$params = [];
$types = "";

if ($search !== '') {
    $where_clauses[] = "(title LIKE ? OR content LIKE ?)";
    $search_param = "%" . $search . "%";
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "ss";
}

if ($category !== '' && strtolower($category) !== 'all') {
    $where_clauses[] = "(title LIKE ? OR content LIKE ?)";
    $cat_param = "%" . $category . "%";
    $params[] = $cat_param;
    $params[] = $cat_param;
    $types .= "ss";
}

$where_sql = implode(" AND ", $where_clauses);

// Count total posts
$count_query = "SELECT COUNT(*) as total FROM blogs WHERE $where_sql";
$total_posts = 0;
try {
    if (!empty($params)) {
        $stmt_count = $conn->prepare($count_query);
        $stmt_count->bind_param($types, ...$params);
        $stmt_count->execute();
        $total_posts = $stmt_count->get_result()->fetch_assoc()['total'];
        $stmt_count->close();
    } else {
        $total_posts = $conn->query($count_query)->fetch_assoc()['total'];
    }
} catch (Exception $e) {
    $total_posts = 0;
}

$total_pages = ceil($total_posts / $limit);
if ($total_pages < 1) $total_pages = 1;

// Fetch current page blogs
$blogs_res = [];
$query = "SELECT * FROM blogs WHERE $where_sql ORDER BY created_at DESC LIMIT ? OFFSET ?";
try {
    $types_fetch = $types . "ii";
    $params_fetch = array_merge($params, [$limit, $offset]);
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types_fetch, ...$params_fetch);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $blogs_res[] = $row;
    }
    $stmt->close();
} catch (Exception $e) {
    $blogs_res = [];
}

// Fallback images for cards without uploaded image
$default_images = [
    '/bm/our servies image/Our Services/Construction_of_Building.jpeg',
    '/bm/our servies image/Our Services/Petro-Pump-Retail-Outlet.jpeg',
    '/bm/our servies image/Our Services/fabrication_wor.jpeg',
    '/bm/our servies image/Our Services/Aluminium_work.jpeg',
    '/bm/our servies image/Our Services/interior_work.jpeg',
    '/bm/our servies image/Our Services/Development_road.jpeg'
];

// Helper to determine category name
function getBlogCategory($title, $content) {
    $text = strtolower($title . ' ' . substr($content, 0, 300));
    if (strpos($text, 'petro') !== false || strpos($text, 'iocl') !== false || strpos($text, 'bpcl') !== false || strpos($text, 'hpcl') !== false || strpos($text, 'outlet') !== false) {
        return 'Petroleum Outlet';
    } elseif (strpos($text, 'steel') !== false || strpos($text, 'ai') !== false || strpos($text, 'fabrication') !== false) {
        return 'Steel & Fabrication';
    } elseif (strpos($text, 'aluminium') !== false || strpos($text, 'glass') !== false) {
        return 'Aluminium Work';
    } elseif (strpos($text, 'interior') !== false || strpos($text, 'furniture') !== false) {
        return 'Interior Design';
    } elseif (strpos($text, 'road') !== false || strpos($text, 'infrastructure') !== false || strpos($text, 'highway') !== false) {
        return 'Road Works';
    } else {
        return 'Civil Construction';
    }
}
?>

<!-- Link Dedicated Blog Stylesheet -->
<link rel="stylesheet" href="/bm/assets/css/blog.css">

<div class="bm-blog-wrapper">

    <!-- 1. BREADCRUMBS -->
    <nav class="bm-breadcrumb-nav" aria-label="breadcrumb">
        <div class="container">
            <ul class="bm-breadcrumb-list">
                <li><a href="/bm/"><i class="fas fa-home me-1"></i> Home</a></li>
                <li class="bm-breadcrumb-sep"><i class="fas fa-chevron-right"></i></li>
                <li><span class="bm-breadcrumb-current">Blogs</span></li>
                <?php if ($category && strtolower($category) !== 'all'): ?>
                    <li class="bm-breadcrumb-sep"><i class="fas fa-chevron-right"></i></li>
                    <li><span class="bm-breadcrumb-current"><?php echo htmlspecialchars($category); ?></span></li>
                <?php endif; ?>
            </ul>
        </div>
    </nav>

    <!-- 2. HERO TOP BANNER (LAKSHYA STYLE) -->
    <div class="bannerTopInnerPage bgPrimary">
        <div class="containerFull">
            <div class="banner-row">
                <div class="leftInnerPagePr">
                    <span class="badge-tag"><i class="fas fa-layer-group"></i> Balimeen Insights</span>
                    <h1 class="heading bannerHeading">Blogs &amp; Articles</h1>
                    <p>Explore comprehensive insights, modern engineering breakthroughs, and architectural expertise curated by Balimeen Private Limited.</p>
                </div>
                <div class="rightInnerPagePr">
                    <div class="blogMobileImg">
                        <img src="/bm/our servies image/Our Services/Construction_of_Building.jpeg" alt="Balimeen Blog Banner" loading="eager">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 3. FILTER, CATEGORY TABS & SEARCH SECTION -->
    <section class="blog-filter-section">
        <div class="filter-header-row">
            <h2 class="filter-title">Recent Blogs</h2>
            
            <div class="filter-controls">
                <!-- Search Box with Live / Form Support -->
                <form action="/bm/blog.php" method="get" class="blog-search-box" id="blogSearchForm">
                    <i class="fas fa-search blog-search-icon"></i>
                    <input type="text" 
                           name="search" 
                           id="blogSearchInput"
                           class="blog-search-input" 
                           placeholder="Search by blog title..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                    <?php if ($category): ?>
                        <input type="hidden" name="category" value="<?php echo htmlspecialchars($category); ?>">
                    <?php endif; ?>
                </form>

                <!-- Category Pills (Desktop) -->
                <div class="category-filter-nav">
                    <a href="/bm/blog.php<?php echo $search ? '?search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo empty($category) || strtolower($category) === 'all' ? 'active' : ''; ?>">All</a>
                    <a href="/bm/blog.php?category=Civil<?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo strtolower($category) === 'civil' ? 'active' : ''; ?>">Civil &amp; Architecture</a>
                    <a href="/bm/blog.php?category=Petroleum<?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo strtolower($category) === 'petroleum' ? 'active' : ''; ?>">Petroleum Outlets</a>
                    <a href="/bm/blog.php?category=Steel<?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo strtolower($category) === 'steel' ? 'active' : ''; ?>">Fabrication &amp; Steel</a>
                    <a href="/bm/blog.php?category=Aluminium<?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo strtolower($category) === 'aluminium' ? 'active' : ''; ?>">Aluminium</a>
                    <a href="/bm/blog.php?category=Interior<?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo strtolower($category) === 'interior' ? 'active' : ''; ?>">Interior Design</a>
                    <a href="/bm/blog.php?category=Road<?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="category-btn <?php echo strtolower($category) === 'road' ? 'active' : ''; ?>">Roads</a>
                </div>
            </div>
        </div>
    </section>

    <!-- 4. BLOG GRID SECTION (2-COLUMN CARDS LIKE LAKSHYA COMMERCE) -->
    <div class="blog-grid-container">
        <div class="blog-grid-2col" id="blogGrid">
            <?php if (!empty($blogs_res)): ?>
                <?php foreach ($blogs_res as $idx => $blog): 
                    $postSlug = urlencode($blog['title']);
                    $postUrl = '/bm/blog_post/' . $postSlug;
                    
                    // Extract readable plain text excerpt & image fallback
                    $content_raw = $blog['content'];
                    $json_data = json_decode($content_raw, true);
                    $plain_text = '';
                    $content_img = '';
                    if ($json_data && isset($json_data['blocks'])) {
                        foreach ($json_data['blocks'] as $block) {
                            if (isset($block['data']['text'])) {
                                $plain_text .= strip_tags($block['data']['text']) . ' ';
                            }
                            if (empty($content_img)) {
                                if ($block['type'] === 'image' && !empty($block['data']['file']['url'])) {
                                    $content_img = $block['data']['file']['url'];
                                } elseif ($block['type'] === 'gallery' && !empty($block['data']['urls'][0])) {
                                    $content_img = $block['data']['urls'][0];
                                }
                            }
                        }
                    } else {
                        $plain_text = strip_tags($content_raw);
                    }

                    // Choose image
                    $imgUrl = !empty($blog['image_url']) ? $blog['image_url'] : (!empty($content_img) ? $content_img : $default_images[$idx % count($default_images)]);
                    if (strpos($imgUrl, '/') !== 0 && strpos($imgUrl, 'http') !== 0) {
                        $imgUrl = '/bm/' . $imgUrl;
                    }
                    $plain_text = trim(preg_replace('/\s+/', ' ', $plain_text));
                    $excerpt = mb_substr($plain_text, 0, 135) . (mb_strlen($plain_text) > 135 ? '...' : '');

                    // Determine Category & Read time
                    $catName = getBlogCategory($blog['title'], $plain_text);
                    $words = str_word_count($plain_text);
                    $mins = max(2, ceil($words / 180));
                ?>
                <article class="careerBox trainingProgramBox blogBox" data-title="<?php echo htmlspecialchars(strtolower($blog['title'])); ?>" data-cat="<?php echo htmlspecialchars(strtolower($catName)); ?>">
                    <div class="head">
                        <span class="card-category-tag"><?php echo htmlspecialchars($catName); ?></span>
                        <a href="<?php echo $postUrl; ?>">
                            <img src="<?php echo htmlspecialchars($imgUrl); ?>" 
                                 alt="<?php echo htmlspecialchars($blog['title']); ?>" 
                                 loading="lazy" 
                                 onerror="this.src='/bm/our servies image/Our Services/Construction_of_Building.jpeg'">
                        </a>
                    </div>
                    <div class="body">
                        <a class="title" href="<?php echo $postUrl; ?>">
                            <?php echo htmlspecialchars($blog['title']); ?>
                        </a>
                        <div class="iconWrap">
                            <p class="iconBox">
                                <i class="fas fa-user-circle"></i>
                                <span>By Balimeen Team</span>
                            </p>
                            <p class="iconBox">
                                <i class="far fa-calendar-alt"></i>
                                <span><?php echo date('d M Y', strtotime($blog['created_at'])); ?></span>
                            </p>
                            <p class="iconBox">
                                <i class="far fa-clock"></i>
                                <span><?php echo $mins; ?> min read</span>
                            </p>
                        </div>
                        <p class="blog-card-excerpt">
                            <?php echo htmlspecialchars($excerpt); ?>
                        </p>
                        <div class="blog-card-footer">
                            <a href="<?php echo $postUrl; ?>" class="btn-read-more">
                                Read More <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    </div>
                </article>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="no-blogs-found">
                    <i class="far fa-newspaper"></i>
                    <h3>No Articles Found</h3>
                    <p>There are currently no blog posts matching your search criteria.</p>
                    <a href="/bm/blog.php" class="btn-read-more" style="justify-content: center; margin-top: 15px;">
                        <i class="fas fa-undo"></i> View All Articles
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- 5. PAGINATION (LAKSHYA STYLE) -->
    <?php if ($total_pages > 1): ?>
    <div class="blogsFooter">
        <nav class="webPagination" aria-label="Blog Page Navigation">
            <ul class="pagination">
                <!-- Previous Button -->
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <?php if ($page > 1): ?>
                        <a class="page-link" href="/bm/blog.php?page=<?php echo $page - 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $category ? '&category=' . urlencode($category) : ''; ?>">
                            <i class="fas fa-angle-left"></i> Previous
                        </a>
                    <?php else: ?>
                        <span class="page-link"><i class="fas fa-angle-left"></i> Previous</span>
                    <?php endif; ?>
                </li>

                <!-- Page Info / Numbers -->
                <li class="page-item disabled">
                    <span class="page-link" style="font-weight: 600; color: var(--bm-blue-dark);">
                        Page <?php echo $page; ?> of <?php echo $total_pages; ?>
                    </span>
                </li>

                <!-- Next Button -->
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <?php if ($page < $total_pages): ?>
                        <a class="page-link" href="/bm/blog.php?page=<?php echo $page + 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $category ? '&category=' . urlencode($category) : ''; ?>">
                            Next <i class="fas fa-angle-right"></i>
                        </a>
                    <?php else: ?>
                        <span class="page-link">Next <i class="fas fa-angle-right"></i></span>
                    <?php endif; ?>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>

    <!-- 6. BOTTOM CONSULTATION / CTA BANNER (LAKSHYA STYLE) -->
    <section class="blog-cta-section">
        <div class="blog-cta-card">
            <div class="blog-cta-content">
                <h3>Plan Your Next Project with Balimeen</h3>
                <p>Have questions about petrol pump outlet setup, steel fabrication, or civil construction? Get in touch with our certified engineers today.</p>
            </div>
            <div class="blog-cta-actions">
                <a href="/bm/contact" class="btn-cta-white">
                    <i class="fas fa-phone-alt"></i> Request Free Consultation
                </a>
            </div>
        </div>
    </section>

</div>

<script>
// Live Search Filter for blog cards
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('blogSearchInput');
    const blogCards = document.querySelectorAll('.careerBox.blogBox');

    if (searchInput && blogCards.length > 0) {
        searchInput.addEventListener('input', function() {
            const query = this.value.toLowerCase().trim();
            blogCards.forEach(card => {
                const title = card.getAttribute('data-title') || '';
                const cat = card.getAttribute('data-cat') || '';
                if (title.includes(query) || cat.includes(query)) {
                    card.style.display = 'flex';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    }
});
</script>

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