<?php
require_once __DIR__ . '/config/config.php';
$pageTitle = 'Blog - Logbook Loans & Landlord Loans Insights Kenya';
$metaDescription = 'Expert advice on logbook loans, landlord loans, car financing and financial tips in Kenya. Stay informed with Fantom Capital\'s blog.';

// Filters
$search = trim($_GET['search'] ?? '');
$categorySlug = trim($_GET['category'] ?? '');
$tagSlug = trim($_GET['tag'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 9;
$offset = ($page - 1) * $perPage;

$where = "WHERE bp.status = 'published'";
$params = [];

if ($search) {
    $where .= " AND (bp.title LIKE ? OR bp.excerpt LIKE ? OR bp.content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($categorySlug) {
    $where .= " AND bc.slug = ?";
    $params[] = $categorySlug;
}
if ($tagSlug) {
    $where .= " AND bp.id IN (SELECT pt.post_id FROM blog_post_tags pt JOIN blog_tags bt ON pt.tag_id = bt.id WHERE bt.slug = ?)";
    $params[] = $tagSlug;
}

// Count total
$countStmt = $db->prepare("SELECT COUNT(*) FROM blog_posts bp LEFT JOIN blog_categories bc ON bp.category_id = bc.id $where");
$countStmt->execute($params);
$totalPosts = $countStmt->fetchColumn();
$totalPages = max(1, ceil($totalPosts / $perPage));

// Fetch posts
$stmt = $db->prepare("
    SELECT bp.*, bc.name as category_name, bc.slug as category_slug, au.full_name as author_name
    FROM blog_posts bp
    LEFT JOIN blog_categories bc ON bp.category_id = bc.id
    LEFT JOIN admin_users au ON bp.author_id = au.id
    $where
    ORDER BY bp.is_featured DESC, bp.published_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$posts = $stmt->fetchAll();

// Featured post (first featured or most recent)
$featuredPost = null;
if ($page === 1 && !$search && !$categorySlug && !$tagSlug) {
    $featuredPost = $posts[0] ?? null;
    if ($featuredPost) {
        $posts = array_slice($posts, 1);
    }
}

// Categories
$categories = $db->query("
    SELECT bc.*, COUNT(bp.id) as post_count 
    FROM blog_categories bc 
    LEFT JOIN blog_posts bp ON bc.id = bp.category_id AND bp.status='published'
    GROUP BY bc.id HAVING post_count > 0 ORDER BY post_count DESC
")->fetchAll();

// Popular tags
$popularTags = $db->query("
    SELECT bt.name, bt.slug, COUNT(pt.post_id) as cnt 
    FROM blog_tags bt 
    JOIN blog_post_tags pt ON bt.id = pt.tag_id 
    JOIN blog_posts bp ON pt.post_id = bp.id AND bp.status='published'
    GROUP BY bt.id ORDER BY cnt DESC LIMIT 15
")->fetchAll();

// Active filter label
$filterLabel = '';
if ($categorySlug) {
    foreach ($categories as $c) { if ($c['slug'] === $categorySlug) $filterLabel = $c['name']; }
}
if ($tagSlug) {
    $filterLabel = 'Tag: ' . $tagSlug;
}

include __DIR__ . '/includes/header.php';
?>
<main>

<!-- Hero -->
<section class="bg-gradient-to-br from-primary-blue via-blue-800 to-blue-900 text-white py-14 md:py-20 relative overflow-hidden">
    <div class="absolute inset-0 opacity-10">
        <div class="absolute top-10 left-10 w-72 h-72 bg-primary-green rounded-full filter blur-3xl"></div>
        <div class="absolute bottom-10 right-10 w-96 h-96 bg-blue-400 rounded-full filter blur-3xl"></div>
    </div>
    <div class="container mx-auto px-4 text-center relative z-10">
        <h1 class="text-3xl md:text-5xl font-extrabold mb-4">Fantom Capital Blog</h1>
        <p class="text-lg md:text-xl text-white/80 max-w-2xl mx-auto mb-8">Expert insights on logbook loans, landlord loans, car financing, and smart money management in Kenya.</p>
        <form action="" method="GET" class="max-w-xl mx-auto flex gap-2">
            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search articles..." class="flex-1 px-5 py-3 rounded-full text-gray-800 text-sm focus:ring-2 focus:ring-primary-green focus:outline-none shadow-lg">
            <button type="submit" class="bg-primary-green text-white px-6 py-3 rounded-full font-bold hover:bg-opacity-90 transition shadow-lg">Search</button>
        </form>
    </div>
</section>

<!-- Breadcrumbs -->
<div class="bg-gray-50 border-b">
    <div class="container mx-auto px-4 py-3">
        <nav class="text-xs text-gray-500 flex items-center gap-2">
            <a href="<?php echo SITE_URL; ?>" class="hover:text-primary-blue transition">Home</a>
            <span>/</span>
            <span class="text-gray-700 font-medium">Blog</span>
            <?php if ($filterLabel): ?>
            <span>/</span>
            <span class="text-primary-blue font-medium"><?php echo htmlspecialchars($filterLabel); ?></span>
            <?php endif; ?>
        </nav>
    </div>
</div>

<section class="container mx-auto px-4 py-10">
    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- Main Content -->
        <div class="lg:col-span-3">
            <?php if ($search): ?>
            <div class="mb-6 flex items-center justify-between">
                <p class="text-gray-600">Showing <?php echo $totalPosts; ?> result<?php echo $totalPosts !== 1 ? 's' : ''; ?> for "<strong><?php echo htmlspecialchars($search); ?></strong>"</p>
                <a href="<?php echo SITE_URL; ?>/blogs.php" class="text-primary-blue text-sm hover:underline">Clear search</a>
            </div>
            <?php endif; ?>

            <?php if ($filterLabel && !$search): ?>
            <div class="mb-6 flex items-center justify-between">
                <h2 class="text-xl font-bold text-gray-900"><?php echo htmlspecialchars($filterLabel); ?></h2>
                <a href="<?php echo SITE_URL; ?>/blogs.php" class="text-primary-blue text-sm hover:underline">View all posts</a>
            </div>
            <?php endif; ?>

            <!-- Featured Post -->
            <?php if ($featuredPost): 
                $fImg = $featuredPost['featured_image'] ? ((strpos($featuredPost['featured_image'], 'http') === 0) ? $featuredPost['featured_image'] : SITE_URL . '/' . $featuredPost['featured_image']) : '';
                $fReadTime = max(1, round(str_word_count(strip_tags($featuredPost['content'])) / 200));
            ?>
            <a href="<?php echo SITE_URL; ?>/blog/<?php echo $featuredPost['slug']; ?>" class="block mb-8 group">
                <div class="bg-white rounded-2xl shadow-sm overflow-hidden border border-gray-100 hover:shadow-lg transition duration-300">
                    <div class="grid md:grid-cols-2">
                        <?php if ($fImg): ?>
                        <div class="h-64 md:h-80 overflow-hidden">
                            <img src="<?php echo $fImg; ?>" alt="<?php echo htmlspecialchars($featuredPost['title']); ?>" class="w-full h-full object-cover group-hover:scale-105 transition duration-500">
                        </div>
                        <?php endif; ?>
                        <div class="p-6 md:p-8 flex flex-col justify-center">
                            <div class="flex items-center gap-2 mb-3">
                                <?php if ($featuredPost['is_featured']): ?>
                                <span class="bg-yellow-100 text-yellow-700 text-xs font-bold px-2 py-1 rounded-full">Featured</span>
                                <?php endif; ?>
                                <?php if ($featuredPost['category_name']): ?>
                                <span class="bg-blue-50 text-primary-blue text-xs font-semibold px-2 py-1 rounded-full"><?php echo htmlspecialchars($featuredPost['category_name']); ?></span>
                                <?php endif; ?>
                            </div>
                            <h2 class="text-xl md:text-2xl font-extrabold text-gray-900 group-hover:text-primary-blue transition mb-3 leading-tight"><?php echo htmlspecialchars($featuredPost['title']); ?></h2>
                            <?php if ($featuredPost['excerpt']): ?>
                            <p class="text-gray-500 text-sm leading-relaxed mb-4 line-clamp-3"><?php echo htmlspecialchars($featuredPost['excerpt']); ?></p>
                            <?php endif; ?>
                            <div class="flex items-center gap-4 text-xs text-gray-400 mt-auto">
                                <span><?php echo htmlspecialchars($featuredPost['author_name'] ?? 'Fantom Capital'); ?></span>
                                <span><?php echo $featuredPost['published_at'] ? date('M d, Y', strtotime($featuredPost['published_at'])) : ''; ?></span>
                                <span><?php echo $fReadTime; ?> min read</span>
                            </div>
                        </div>
                    </div>
                </div>
            </a>
            <?php endif; ?>

            <!-- Posts Grid -->
            <?php if (empty($posts) && !$featuredPost): ?>
            <div class="text-center py-16">
                <div class="text-6xl mb-4">📰</div>
                <h3 class="text-lg font-semibold text-gray-700 mb-2">No articles found</h3>
                <p class="text-gray-500">
                    <?php echo $search ? 'Try a different search term.' : 'Check back soon for new articles!'; ?>
                </p>
            </div>
            <?php else: ?>
            <div class="grid md:grid-cols-2 xl:grid-cols-3 gap-6">
                <?php foreach ($posts as $p): 
                    $pImg = $p['featured_image'] ? ((strpos($p['featured_image'], 'http') === 0) ? $p['featured_image'] : SITE_URL . '/' . $p['featured_image']) : '';
                    $pReadTime = max(1, round(str_word_count(strip_tags($p['content'])) / 200));
                ?>
                <a href="<?php echo SITE_URL; ?>/blog/<?php echo $p['slug']; ?>" class="bg-white rounded-xl shadow-sm overflow-hidden border border-gray-100 group hover:shadow-md transition duration-300 flex flex-col">
                    <?php if ($pImg): ?>
                    <div class="h-48 overflow-hidden">
                        <img src="<?php echo $pImg; ?>" alt="<?php echo htmlspecialchars($p['title']); ?>" class="w-full h-full object-cover group-hover:scale-105 transition duration-500" loading="lazy">
                    </div>
                    <?php else: ?>
                    <div class="h-48 bg-gradient-to-br from-primary-blue/10 to-primary-green/10 flex items-center justify-center">
                        <svg class="w-12 h-12 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z"/></svg>
                    </div>
                    <?php endif; ?>
                    <div class="p-5 flex flex-col flex-1">
                        <div class="flex items-center gap-2 mb-2">
                            <?php if ($p['category_name']): ?>
                            <span class="bg-blue-50 text-primary-blue text-[10px] font-semibold px-2 py-0.5 rounded-full"><?php echo htmlspecialchars($p['category_name']); ?></span>
                            <?php endif; ?>
                            <span class="text-gray-400 text-[10px]"><?php echo $pReadTime; ?> min read</span>
                        </div>
                        <h3 class="font-bold text-gray-900 group-hover:text-primary-blue transition leading-snug line-clamp-2 mb-2"><?php echo htmlspecialchars($p['title']); ?></h3>
                        <?php if ($p['excerpt']): ?>
                        <p class="text-gray-500 text-sm line-clamp-2 mb-3"><?php echo htmlspecialchars($p['excerpt']); ?></p>
                        <?php endif; ?>
                        <div class="flex items-center justify-between mt-auto pt-3 border-t border-gray-50 text-xs text-gray-400">
                            <span><?php echo $p['published_at'] ? date('M d, Y', strtotime($p['published_at'])) : ''; ?></span>
                            <span class="text-primary-blue font-semibold group-hover:translate-x-1 transition-transform inline-flex items-center gap-1">Read <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg></span>
                        </div>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <div class="flex justify-center gap-2 mt-10">
                <?php if ($page > 1): ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="px-4 py-2 bg-white border rounded-lg text-sm hover:bg-gray-50 transition">&laquo; Prev</a>
                <?php endif; ?>
                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" class="px-4 py-2 border rounded-lg text-sm transition <?php echo $i === $page ? 'bg-primary-blue text-white border-primary-blue' : 'bg-white hover:bg-gray-50'; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="px-4 py-2 bg-white border rounded-lg text-sm hover:bg-gray-50 transition">Next &raquo;</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Sidebar -->
        <aside class="space-y-6">
            <!-- Categories -->
            <?php if ($categories): ?>
            <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
                <h4 class="font-bold text-gray-900 mb-4 text-sm uppercase tracking-wide">Categories</h4>
                <div class="space-y-1">
                    <a href="<?php echo SITE_URL; ?>/blogs.php" class="flex justify-between items-center text-sm py-2 px-3 rounded-lg transition <?php echo !$categorySlug ? 'bg-primary-blue text-white' : 'text-gray-600 hover:bg-gray-50'; ?>">
                        <span>All Posts</span>
                        <span class="text-xs font-bold <?php echo !$categorySlug ? 'bg-white/20 px-2 py-0.5 rounded-full' : 'bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full'; ?>"><?php echo $totalPosts; ?></span>
                    </a>
                    <?php foreach ($categories as $cat): ?>
                    <a href="<?php echo SITE_URL; ?>/blogs.php?category=<?php echo $cat['slug']; ?>" class="flex justify-between items-center text-sm py-2 px-3 rounded-lg transition <?php echo $categorySlug === $cat['slug'] ? 'bg-primary-blue text-white' : 'text-gray-600 hover:bg-gray-50'; ?>">
                        <span><?php echo htmlspecialchars($cat['name']); ?></span>
                        <span class="text-xs font-bold <?php echo $categorySlug === $cat['slug'] ? 'bg-white/20 px-2 py-0.5 rounded-full' : 'bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full'; ?>"><?php echo $cat['post_count']; ?></span>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Tags -->
            <?php if ($popularTags): ?>
            <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
                <h4 class="font-bold text-gray-900 mb-4 text-sm uppercase tracking-wide">Popular Topics</h4>
                <div class="flex flex-wrap gap-2">
                    <?php foreach ($popularTags as $t): ?>
                    <a href="<?php echo SITE_URL; ?>/blogs.php?tag=<?php echo $t['slug']; ?>" class="text-xs font-medium px-3 py-1.5 rounded-full transition <?php echo $tagSlug === $t['slug'] ? 'bg-primary-blue text-white' : 'bg-gray-100 text-gray-600 hover:bg-primary-blue hover:text-white'; ?>">
                        <?php echo htmlspecialchars($t['name']); ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- CTA -->
            <div class="bg-gradient-to-br from-primary-blue to-blue-800 rounded-xl p-6 text-white text-center">
                <h4 class="font-bold text-lg mb-2">Need Quick Financing?</h4>
                <p class="text-white/80 text-sm mb-4">Get a logbook loan or landlord loan approved within 24 hours.</p>
                <a href="<?php echo SITE_URL; ?>/#loan-form" class="inline-block bg-primary-green text-white px-6 py-2.5 rounded-full text-sm font-bold hover:bg-opacity-90 transition shadow-lg">Apply Now</a>
            </div>

            <!-- Newsletter -->
            <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
                <h4 class="font-bold text-gray-900 mb-2">Stay Updated</h4>
                <p class="text-gray-500 text-sm mb-3">Get the latest financial tips and loan insights delivered to your inbox.</p>
                <form onsubmit="event.preventDefault(); alert('Thank you for subscribing!');">
                    <input type="email" placeholder="Your email address" required class="w-full px-4 py-2 border rounded-lg text-sm mb-2 focus:ring-2 focus:ring-primary-blue focus:outline-none">
                    <button type="submit" class="w-full bg-primary-blue text-white py-2 rounded-lg text-sm font-bold hover:bg-opacity-90 transition">Subscribe</button>
                </form>
            </div>
        </aside>
    </div>
</section>

</main>

<style>.line-clamp-2{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.line-clamp-3{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}</style>

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