<?php
// ============================================
// INITIALIZATION
// ============================================
if (session_status() === PHP_SESSION_NONE) session_start();
require_once 'config.php';

$brand = getBrand();
$sid = session_id();
$cartCount = function_exists('getCartCount') ? getCartCount($sid) : 0;
$whatsapp_number = $brand['whatsapp'] ?? '01775121112';

// ============================================
// FILTERS & PAGINATION
// ============================================
$category_slug = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 6;
$offset = ($page - 1) * $limit;

// Build WHERE clause
$where = "WHERE p.status = 'published'";
if ($category_slug) {
    $cat_id = $conn->query("SELECT id FROM blog_categories WHERE slug = '$category_slug'")->fetch_assoc()['id'] ?? 0;
    if ($cat_id) $where .= " AND p.category_id = $cat_id";
}
if ($search) {
    $search_esc = $conn->real_escape_string($search);
    $where .= " AND (p.title LIKE '%$search_esc%' OR p.content LIKE '%$search_esc%')";
}

// Total posts for pagination
$total = $conn->query("SELECT COUNT(*) as c FROM blog_posts p $where")->fetch_assoc()['c'];
$total_pages = ceil($total / $limit);

// Fetch posts
$query = "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
          ORDER BY p.published_at DESC
          LIMIT $limit OFFSET $offset";
$posts = $conn->query($query);

// ============================================
// SIDEBAR DATA
// ============================================
// Recent posts
$recent_posts = $conn->query("SELECT id, title, slug, image, published_at FROM blog_posts WHERE status = 'published' ORDER BY published_at DESC LIMIT 5");
// Categories
$categories = $conn->query("SELECT * FROM blog_categories ORDER BY name");
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>ব্লগ | <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></title>
    <meta name="description" content="স্বাস্থ্য টিপস, হোমিওপ্যাথি আর্টিকেল ও সর্বশেষ সংবাদ পড়ুন।">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <style>
        <?= function_exists('generateDynamicCSS') ? generateDynamicCSS() : '' ?>
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:var(--body_font,'Hind Siliguri'),sans-serif;font-size:16px;line-height:1.6;color:var(--text_color,#1a1a2e);background:var(--body_bg,#fff);overflow-x:hidden}
        #navbar{background:var(--primary_color,#2d6a4f)!important;padding:12px 0;transition:.3s;z-index:1000;box-shadow:0 2px 15px rgba(0,0,0,.1);position:fixed;top:0;left:0;right:0}
        #navbar.scrolled{background:var(--primary_dark,#1b4332)!important;padding:8px 0}
        .navbar-brand{color:#fff!important;font-weight:700;font-size:clamp(1rem,4vw,1.2rem);display:flex;align-items:center;gap:8px}
        .nav-logo{height:clamp(30px,5vw,38px);border-radius:50%;border:2px solid rgba(255,255,255,.3);object-fit:cover}
        .nav-link{color:rgba(255,255,255,.9)!important;font-weight:500;padding:8px 12px!important;transition:.3s}
        .nav-link:hover{color:#fff!important;transform:translateY(-2px)}
        .login-nav{background:#fff;padding:8px 0;position:fixed;top:60px;left:0;right:0;z-index:999;border-bottom:2px solid #eee;display:flex;justify-content:center;gap:clamp(5px,2vw,15px);flex-wrap:wrap;box-shadow:0 2px 5px rgba(0,0,0,.05)}
        .login-nav a{padding:clamp(5px,2vw,10px) clamp(10px,3vw,20px);border-radius:30px;font-size:clamp(.7rem,2.5vw,.85rem);font-weight:600;text-decoration:none;transition:.3s}
        .login-nav a:hover{transform:translateY(-2px)}
        .btn-login-admin{background:#dc3545;color:#fff}
        .btn-login-patient{background:#007bff;color:#fff}
        .btn-login-student{background:#17a2b8;color:#fff}
        .btn-login-doctor{background:#28a745;color:#fff}
        .page-header{background:linear-gradient(135deg,var(--primary_dark,#1b4332),var(--primary_color,#2d6a4f));color:#fff;padding:160px 0 60px;margin-top:70px;text-align:center}
        .page-header h1{font-size:2.5rem;font-weight:700}
        .blog-card{border:none;border-radius:20px;box-shadow:0 5px 20px rgba(0,0,0,.08);transition:.3s;overflow:hidden;height:100%}
        .blog-card:hover{transform:translateY(-8px);box-shadow:0 15px 30px rgba(0,0,0,.15)}
        .blog-img{height:220px;object-fit:cover;width:100%}
        .sidebar-card{background:#fff;border-radius:20px;padding:20px;box-shadow:0 5px 15px rgba(0,0,0,.05);margin-bottom:30px}
        .sidebar-card h5{border-left:4px solid var(--primary_color);padding-left:12px;margin-bottom:20px}
        .recent-post-item{display:flex;gap:12px;margin-bottom:15px;padding-bottom:15px;border-bottom:1px solid #eee}
        .recent-post-img{width:70px;height:70px;object-fit:cover;border-radius:12px}
        .category-list li{margin-bottom:10px}
        .category-list a{color:var(--text_color);text-decoration:none;transition:.3s;display:block;padding:5px 0}
        .category-list a:hover{color:var(--primary_color);transform:translateX(5px)}
        .pagination .page-link{color:var(--primary_color)}
        .pagination .active .page-link{background:var(--primary_color);border-color:var(--primary_color);color:#fff}
        footer{background:#0a0a0a;color:#aaa;padding:40px 0 20px;margin-top:50px}
        .wa-float{position:fixed;bottom:30px;right:30px;width:60px;height:60px;background:#25D366;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:32px;color:#fff;z-index:999;box-shadow:0 4px 15px rgba(37,211,102,.3);transition:.3s;animation:waPulse 2s infinite;text-decoration:none}
        .wa-float:hover{transform:scale(1.1);animation:none}
        @keyframes waPulse{0%{transform:scale(1);box-shadow:0 4px 15px rgba(37,211,102,.3)}50%{transform:scale(1.08);box-shadow:0 8px 30px rgba(37,211,102,.5)}100%{transform:scale(1);box-shadow:0 4px 15px rgba(37,211,102,.3)}}
        @media (max-width:768px){.login-nav{top:55px}.page-header{margin-top:55px;padding:120px 0 40px}.page-header h1{font-size:1.8rem}}
        @media (max-width:576px){.login-nav{top:50px}.page-header{margin-top:50px}}
    </style>
</head>
<body>

<!-- NAVBAR (same as index.php) -->
<nav class="navbar navbar-expand-lg fixed-top" id="navbar">
    <div class="container">
        <a class="navbar-brand" href="index.php">
            <?php if(!empty($brand['logo'])): ?>
                <img src="<?= htmlspecialchars($brand['logo']) ?>" alt="Logo" class="nav-logo">
            <?php else: ?>
                <span style="font-size:1.5rem;">🏥</span>
            <?php endif; ?>
            <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?>
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navMenu"><span class="navbar-toggler-icon"></span></button>
        <div class="collapse navbar-collapse" id="navMenu">
            <ul class="navbar-nav ms-auto align-items-lg-center">
                <li class="nav-item"><a class="nav-link" href="index.php#home">হোম</a></li>
                <li class="nav-item"><a class="nav-link" href="index.php#doctors">ডাক্তার</a></li>
                <li class="nav-item"><a class="nav-link" href="index.php#services">সেবা</a></li>
                <li class="nav-item"><a class="nav-link" href="index.php#products">পণ্য</a></li>
                <li class="nav-item"><a class="nav-link active" href="blog.php">ব্লগ</a></li>
                <li class="nav-item"><a class="nav-link" href="index.php#tutorials">টিউটোরিয়াল</a></li>
                <li class="nav-item"><a class="nav-link" href="index.php#contact">যোগাযোগ</a></li>
                <li class="nav-item ms-lg-1 mt-2 mt-lg-0">
                    <a href="cart.php" class="btn btn-warning" style="color:#fff!important; position:relative;">
                        <i class="fas fa-shopping-cart"></i> কার্ট
                        <?php if($cartCount > 0): ?>
                        <span style="position:absolute; top:-8px; right:-8px; background:#dc3545; color:#fff; font-size:0.7rem; width:20px; height:20px; border-radius:50%; display:inline-flex; align-items:center; justify-content:center;"><?= $cartCount ?></span>
                        <?php endif; ?>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- SECOND NAVBAR -->
<div class="login-nav">
    <a href="admin.php" class="btn-login-admin"><i class="fas fa-user-shield"></i> অ্যাডমিন</a>
    <a href="opd/" class="btn-login-patient"><i class="fas fa-user-injured"></i> রোগী</a>
    <a href="lms/" class="btn-login-student"><i class="fas fa-user-graduate"></i> শিক্ষার্থী</a>
    <a href="doctor.php" class="btn-login-doctor"><i class="fas fa-user-md"></i> ডাক্তার</a>
</div>

<!-- PAGE HEADER -->
<div class="page-header">
    <div class="container">
        <h1><i class="fas fa-newspaper"></i> স্বাস্থ্য ব্লগ</h1>
        <p class="lead">সর্বশেষ স্বাস্থ্য টিপস, হোমিওপ্যাথি আর্টিকেল ও সংবাদ</p>
        <form method="get" class="mt-4">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="আপনার পছন্দের বিষয় খুঁজুন..." value="<?= htmlspecialchars($search) ?>">
                        <button class="btn btn-light" type="submit"><i class="fas fa-search"></i></button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- BLOG CONTENT -->
<section class="py-5">
    <div class="container">
        <div class="row g-4">
            <!-- Main Content -->
            <div class="col-lg-8">
                <div class="row g-4">
                    <?php if($posts && $posts->num_rows > 0): while($post = $posts->fetch_assoc()): ?>
                    <div class="col-md-6" data-aos="fade-up">
                        <div class="blog-card h-100">
                            <?php if($post['image']): ?>
                                <img src="<?= htmlspecialchars($post['image']) ?>" class="blog-img" alt="<?= htmlspecialchars($post['title']) ?>">
                            <?php else: ?>
                                <div class="blog-img bg-primary d-flex align-items-center justify-content-center"><i class="fas fa-newspaper fa-3x text-white opacity-50"></i></div>
                            <?php endif; ?>
                            <div class="p-4">
                                <?php if($post['category_name']): ?>
                                    <a href="?category=<?= $post['category_slug'] ?>" class="badge bg-info mb-2 text-decoration-none"><?= htmlspecialchars($post['category_name']) ?></a>
                                <?php endif; ?>
                                <h5><a href="single_post.php?id=<?= $post['id'] ?>" class="text-dark text-decoration-none"><?= htmlspecialchars($post['title']) ?></a></h5>
                                <p class="text-muted small"><?= htmlspecialchars(substr(strip_tags($post['excerpt'] ?: $post['content']), 0, 120)) ?>...</p>
                                <div class="d-flex justify-content-between text-muted small mb-3">
                                    <span><i class="far fa-user"></i> <?= htmlspecialchars($post['author'] ?? 'Admin') ?></span>
                                    <span><i class="far fa-eye"></i> <?= number_format($post['views'] ?? 0) ?></span>
                                    <span><i class="far fa-calendar"></i> <?= date('d M Y', strtotime($post['published_at'] ?? $post['created_at'])) ?></span>
                                </div>
                                <a href="single_post.php?id=<?= $post['id'] ?>" class="btn btn-primary btn-sm rounded-pill">বিস্তারিত <i class="fas fa-arrow-right"></i></a>
                            </div>
                        </div>
                    </div>
                    <?php endwhile; else: ?>
                        <div class="col-12 text-center py-5">
                            <i class="fas fa-newspaper fa-3x text-muted mb-3"></i>
                            <h5>কোনো পোস্ট পাওয়া যায়নি</h5>
                            <p class="text-muted">অনুগ্রহ করে অন্য কীওয়ার্ড দিয়ে চেষ্টা করুন।</p>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Pagination -->
                <?php if($total_pages > 1): ?>
                <nav class="mt-5">
                    <ul class="pagination justify-content-center">
                        <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page-1])) ?>">পূর্ববর্তী</a>
                        </li>
                        <?php for($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
                        </li>
                        <?php endfor; ?>
                        <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page+1])) ?>">পরবর্তী</a>
                        </li>
                    </ul>
                </nav>
                <?php endif; ?>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Categories -->
                <div class="sidebar-card">
                    <h5><i class="fas fa-tags"></i> ক্যাটাগরি</h5>
                    <ul class="list-unstyled category-list">
                        <?php while($cat = $categories->fetch_assoc()): ?>
                        <li><a href="?category=<?= $cat['slug'] ?>"><i class="fas fa-angle-right"></i> <?= htmlspecialchars($cat['name']) ?></a></li>
                        <?php endwhile; ?>
                    </ul>
                </div>

                <!-- Recent Posts -->
                <div class="sidebar-card">
                    <h5><i class="fas fa-clock"></i> সাম্প্রতিক পোস্ট</h5>
                    <?php while($recent = $recent_posts->fetch_assoc()): ?>
                    <div class="recent-post-item">
                        <?php if($recent['image']): ?>
                            <img src="<?= htmlspecialchars($recent['image']) ?>" class="recent-post-img" alt="">
                        <?php else: ?>
                            <div class="recent-post-img bg-light d-flex align-items-center justify-content-center"><i class="fas fa-newspaper text-muted"></i></div>
                        <?php endif; ?>
                        <div>
                            <a href="single_post.php?id=<?= $recent['id'] ?>" class="text-dark text-decoration-none fw-semibold"><?= htmlspecialchars($recent['title']) ?></a>
                            <div class="small text-muted"><?= date('d M Y', strtotime($recent['published_at'])) ?></div>
                        </div>
                    </div>
                    <?php endwhile; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- FOOTER (same as index.php) -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <h5 style="color:#fff;"><?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></h5>
                <p><?= htmlspecialchars($brand['about'] ?? '') ?></p>
            </div>
            <div class="col-md-6 text-md-end">
                <p><i class="fas fa-phone"></i> <?= htmlspecialchars($brand['phone'] ?? '') ?></p>
                <p><i class="fas fa-envelope"></i> <?= htmlspecialchars($brand['email'] ?? '') ?></p>
                <div>
                    <?php if($brand['facebook']): ?>
                        <a href="<?= htmlspecialchars($brand['facebook']) ?>" class="text-white me-2"><i class="fab fa-facebook fa-lg"></i></a>
                    <?php endif; ?>
                    <?php if($brand['youtube']): ?>
                        <a href="<?= htmlspecialchars($brand['youtube']) ?>" class="text-white me-2"><i class="fab fa-youtube fa-lg"></i></a>
                    <?php endif; ?>
                    <a href="https://wa.me/88<?= htmlspecialchars($whatsapp_number) ?>" style="color:var(--accent_color)"><i class="fab fa-whatsapp fa-lg"></i></a>
                </div>
            </div>
        </div>
        <hr>
        <div class="row align-items-center">
            <div class="col-md-6 text-center text-md-start">
                <p class="mb-0 small">© <?= date('Y') ?> <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?>. সর্বস্বত্ব সংরক্ষিত।</p>
            </div>
            <div class="col-md-6 text-center text-md-end">
                <a href="https://www.onesbd.com/host" target="_blank" class="dev-credit"><i class="fas fa-globe"></i> Developed by <strong>OneSBD</strong></a>
            </div>
        </div>
    </div>
</footer>

<!-- Floating WhatsApp Button -->
<a href="https://wa.me/88<?= htmlspecialchars($whatsapp_number) ?>" target="_blank" class="wa-float"><i class="fab fa-whatsapp"></i></a>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<script>
AOS.init({ duration: 800, once: true, offset: 80 });
$(window).scroll(function() {
    $('#navbar').toggleClass('scrolled', $(this).scrollTop() > 50);
});
</script>
</body>
</html>