<?php
// Ensure this path jumps up from public/ to the root for config
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/ad-display.php';

$settings_file = __DIR__ . '/../config/site-settings.json';
$site_name = 'tipspac';
if (file_exists($settings_file)) {
    $loaded = json_decode(file_get_contents($settings_file), true);
    if (!empty($loaded['site_name'])) $site_name = $loaded['site_name'];
}

// ==========================================
// DYNAMIC PAGINATION, TIME-LOCK & CATEGORIES
// ==========================================
$limit = 10; // Articles per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Check if a category filter is active
$active_category = trim($_GET['category'] ?? '');

// Base Time-Lock Condition
$where_clause = "WHERE (publish_date <= NOW() OR (publish_date IS NULL AND created_at <= NOW()))";
$params = [];

if (!empty($active_category)) {
    $where_clause .= " AND category = :category";
    $params['category'] = $active_category;
}

try {
    // 1. Get Total Records for Pagination
    $countSql = "SELECT COUNT(*) FROM news " . $where_clause;
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total_records = $countStmt->fetchColumn();
    
    $total_pages = ceil($total_records / $limit);
    if ($total_pages < 1) $total_pages = 1;

    // 2. Fetch the Actual Articles
    $sql = "SELECT * FROM news " . $where_clause . " ORDER BY COALESCE(publish_date, created_at) DESC LIMIT :limit OFFSET :offset";
    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $val) {
        $stmt->bindValue(':' . $key, $val);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 3. Fetch Dynamic Sidebar Categories & Counts
    $catSql = "SELECT category, COUNT(*) as count FROM news WHERE (publish_date <= NOW() OR (publish_date IS NULL AND created_at <= NOW())) GROUP BY category ORDER BY count DESC";
    $sidebar_categories = $pdo->query($catSql)->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $articles = [];
    $sidebar_categories = [];
    $total_pages = 1;
}
?>

<?php require_once __DIR__ . '/includes/header.php'; ?>

<!-- Neural Background -->
<div class="fixed inset-0 z-0 pointer-events-none opacity-20 bg-cover bg-center bg-no-repeat" style="background-image: url('https://images.unsplash.com/photo-1579952363873-27f3bade9f55?q=80&w=2000&auto=format&fit=crop');"></div>
<div class="fixed inset-0 z-0 bg-gradient-to-t from-[#020617] via-[#020617]/85 to-transparent pointer-events-none"></div>
<canvas id="neuralCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0 opacity-40"></canvas>

<main class="relative z-10 flex-1 w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-10 pb-20">

    <!-- Page Header -->
    <div class="mb-10 text-center md:text-left">
        <div class="inline-flex items-center space-x-2 bg-emerald-500/10 border border-emerald-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-emerald-400 mb-3">
            <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
            <span>Insights & Analysis</span>
        </div>
        <h1 class="text-4xl md:text-5xl font-black tracking-tight text-white">
            <?php echo !empty($active_category) ? htmlspecialchars($active_category) : 'Blog & <span class="text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-cyan-400">Predictions</span>'; ?>
        </h1>
        <p class="text-sm mt-2 max-w-xl text-slate-400">Daily insights, system architecture logs, and deep match breakdowns.</p>
    </div>

    <!-- Ad Slot -->
    <div class="w-full mb-8 flex justify-center">
        <?php display_ad_slot($pdo, 'header'); ?>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        
        <!-- Main Content -->
        <div class="lg:col-span-8 space-y-6">
            
            <?php if (empty($articles)): ?>
                <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800/80 rounded-2xl p-12 text-center shadow-lg">
                    <span class="text-4xl mb-4 block">📰</span>
                    <h3 class="text-white font-bold tracking-widest uppercase mb-2">No Articles Available</h3>
                    <p class="text-slate-400 text-sm">
                        <?php echo !empty($active_category) ? "No published content found in the '" . htmlspecialchars($active_category) . "' category." : "Our neural engine is currently compiling new insights. Check back later."; ?>
                    </p>
                    <?php if(!empty($active_category)): ?>
                        <a href="blog.php" class="inline-block mt-4 text-xs text-emerald-400 font-bold tracking-widest uppercase hover:text-emerald-300">← Clear Filters</a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <?php foreach ($articles as $art): 
                    $pub_date = date("F j, Y", strtotime($art['publish_date'] ?? $art['created_at']));
                    $time_ago = timeAgo($art['publish_date'] ?? $art['created_at']);
                    $img_url = !empty($art['featured_image']) ? SITE_URL . '/' . htmlspecialchars($art['featured_image']) : 'https://images.unsplash.com/photo-1518098682722-e99c43a406b2?q=80&w=600&auto=format&fit=crop';
                    $category_name = htmlspecialchars($art['category'] ?? 'General');
                ?>
                    <article class="bg-slate-900/60 backdrop-blur-xl border border-slate-800/80 rounded-2xl p-4 sm:p-5 flex flex-col sm:flex-row gap-5 md:gap-6 hover:border-emerald-500/30 transition-all duration-300 group shadow-lg">
                        <!-- Image -->
                        <div class="w-full sm:w-64 aspect-[16/9] sm:aspect-[4/3] rounded-xl overflow-hidden shrink-0 relative bg-slate-950 border border-slate-800">
                            <div class="absolute inset-0 bg-cover bg-center group-hover:scale-105 transition-transform duration-500" style="background-image: url('<?php echo $img_url; ?>');"></div>
                        </div>
                        <!-- Content -->
                        <div class="flex flex-col justify-center py-2 flex-1">
                            <h2 class="text-xl md:text-2xl font-black mb-2 leading-tight text-white group-hover:text-emerald-400 transition-colors">
                                <a href="blog-single.php?id=<?php echo $art['id']; ?>"><?php echo htmlspecialchars($art['title']); ?></a>
                            </h2>
                            <div class="flex flex-wrap gap-2 mb-3">
                                <a href="?category=<?php echo urlencode($category_name); ?>" class="px-3 py-1 rounded-lg text-[10px] font-bold border border-emerald-500/20 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20 transition-colors">
                                    <?php echo $category_name; ?>
                                </a>
                            </div>
                            <div class="flex items-center gap-3 text-xs text-slate-400">
                                <span class="flex items-center gap-1">
                                    <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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                    <?php echo $pub_date; ?>
                                </span>
                                <span class="text-slate-500">•</span>
                                <span class="flex items-center gap-1">
                                    <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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                    <?php echo $time_ago; ?>
                                </span>
                            </div>
                            <a href="blog-single.php?id=<?php echo $art['id']; ?>" class="mt-4 inline-flex items-center gap-2 text-[11px] font-bold text-emerald-400 hover:text-emerald-300 transition-colors uppercase tracking-wider group/link">
                                Read More
                                <svg class="w-3.5 h-3.5 group-hover/link:translate-x-1 transition-transform" 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"></path></svg>
                            </a>
                        </div>
                    </article>
                <?php endforeach; ?>
            <?php endif; ?>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="flex justify-center pt-6">
                    <div class="flex items-center space-x-2 bg-slate-900/60 border border-slate-800 p-1.5 rounded-xl backdrop-blur">
                        
                        <?php 
                        $buildUrl = function($pageNum) use ($active_category) {
                            $url = "?page=" . $pageNum;
                            if(!empty($active_category)) $url .= "&category=" . urlencode($active_category);
                            return $url;
                        };
                        ?>

                        <?php if ($page > 1): ?>
                            <a href="<?php echo $buildUrl($page - 1); ?>" class="px-3 py-1.5 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">Prev</a>
                        <?php else: ?>
                            <span class="px-3 py-1.5 text-xs font-bold text-slate-600 cursor-not-allowed rounded-lg">Prev</span>
                        <?php endif; ?>

                        <?php 
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        
                        if($start > 1) {
                            echo '<a href="'.$buildUrl(1).'" class="px-3 py-1.5 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">1</a>';
                            if($start > 2) echo '<span class="px-2 text-slate-600">...</span>';
                        }

                        for ($i = $start; $i <= $end; $i++): 
                        ?>
                            <a href="<?php echo $buildUrl($i); ?>" class="px-3 py-1.5 rounded-lg text-xs font-bold transition <?php echo $i == $page ? 'border border-emerald-500/30 bg-emerald-500/10 text-emerald-400' : 'text-slate-400 hover:text-white hover:bg-slate-800'; ?>"><?php echo $i; ?></a>
                        <?php endfor; ?>

                        <?php 
                        if($end < $total_pages) {
                            if($end < $total_pages - 1) echo '<span class="px-2 text-slate-600">...</span>';
                            echo '<a href="'.$buildUrl($total_pages).'" class="px-3 py-1.5 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">'.$total_pages.'</a>';
                        }
                        ?>

                        <?php if ($page < $total_pages): ?>
                            <a href="<?php echo $buildUrl($page + 1); ?>" class="px-3 py-1.5 text-xs font-bold text-slate-400 hover:text-white transition rounded-lg">Next</a>
                        <?php else: ?>
                            <span class="px-3 py-1.5 text-xs font-bold text-slate-600 cursor-not-allowed rounded-lg">Next</span>
                        <?php endif; ?>

                    </div>
                </div>
            <?php endif; ?>

        </div>

        <!-- Sidebar -->
        <div class="lg:col-span-4 space-y-6">
            
            <!-- Search -->
            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800/80 rounded-2xl p-5 md:p-6 shadow-lg">
                <form action="blog.php" method="GET" class="relative">
                    <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                        <svg class="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                    </div>
                    <input type="text" name="search" placeholder="Search articles..." class="w-full bg-slate-950/50 border border-slate-800 text-white rounded-xl py-3 pl-11 pr-4 text-sm focus:outline-none focus:border-emerald-500 transition-colors shadow-inner placeholder-slate-500">
                </form>
            </div>

            <!-- Categories -->
            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800/80 rounded-2xl p-5 md:p-6 shadow-lg">
                
                <div class="flex items-center space-x-3 mb-6 border-b border-slate-800 pb-4">
                    <div class="w-1 h-6 bg-emerald-500 rounded-sm"></div>
                    <h3 class="text-xl font-black tracking-tight text-white">Categories</h3>
                </div>
                
                <?php if(empty($sidebar_categories)): ?>
                    <p class="text-xs text-slate-500">No categories found.</p>
                <?php else: ?>
                    <ul class="space-y-1">
                        <li>
                            <a href="blog.php" class="flex justify-between items-center py-2.5 text-[13px] font-bold hover:pl-2 transition-all duration-300 group border-b border-slate-800/50 <?php echo empty($active_category) ? 'pl-2 text-emerald-400' : ''; ?>">
                                <span class="<?php echo empty($active_category) ? 'text-emerald-400' : 'text-slate-300 group-hover:text-emerald-400'; ?> transition-colors">All Content</span>
                            </a>
                        </li>

                        <?php foreach($sidebar_categories as $cat): 
                            $cat_name = htmlspecialchars($cat['category']);
                            $is_active = ($active_category === $cat['category']);
                        ?>
                            <li>
                                <a href="?category=<?php echo urlencode($cat['category']); ?>" class="flex justify-between items-center py-2.5 text-[13px] font-bold hover:pl-2 transition-all duration-300 group border-b border-slate-800/50 last:border-0 <?php echo $is_active ? 'pl-2' : ''; ?>">
                                    <span class="<?php echo $is_active ? 'text-emerald-400' : 'text-slate-300 group-hover:text-emerald-400'; ?> transition-colors">
                                        <?php echo $cat_name; ?>
                                    </span>
                                    <span class="text-[11px] transition-colors <?php echo $is_active ? 'text-emerald-500' : 'text-slate-500 group-hover:text-emerald-500'; ?>">
                                        (<?php echo $cat['count']; ?>)
                                    </span>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>

            <!-- Recent Posts (optional) -->
            <div class="bg-slate-900/60 backdrop-blur-xl border border-slate-800/80 rounded-2xl p-5 md:p-6 shadow-lg">
                <div class="flex items-center space-x-3 mb-6 border-b border-slate-800 pb-4">
                    <div class="w-1 h-6 bg-cyan-400 rounded-sm"></div>
                    <h3 class="text-xl font-black tracking-tight text-white">Recent Posts</h3>
                </div>
                <?php 
                // We already have $articles, but only up to 3
                $recent = array_slice($articles, 0, 3);
                ?>
                <?php if(!empty($recent)): ?>
                    <ul class="space-y-3">
                        <?php foreach($recent as $r): ?>
                            <li>
                                <a href="blog-single.php?id=<?php echo $r['id']; ?>" class="block hover:pl-2 transition-all">
                                    <span class="text-sm font-bold text-white hover:text-emerald-400 transition-colors"><?php echo htmlspecialchars($r['title']); ?></span>
                                    <span class="text-[10px] text-slate-500 block"><?php echo date("M d, Y", strtotime($r['publish_date'] ?? $r['created_at'])); ?></span>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p class="text-xs text-slate-500">No recent posts.</p>
                <?php endif; ?>
            </div>

        </div>
    </div>

    <!-- Ad Slot -->
    <div class="w-full flex justify-center py-6">
        <?php display_ad_slot($pdo, 'in_content'); ?>
    </div>

</main>

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

<script>
    // Helper time ago function in JS (optional, but we used PHP)
    // The neural background canvas remains unchanged

    const canvas = document.getElementById("neuralCanvas");
    if(canvas) {
        const ctx = canvas.getContext("2d");
        let width, height;
        let particles = [];
        let mouse = { x: null, y: null, radius: 150 };
        
        window.addEventListener('mousemove', function(e) {
            mouse.x = e.x;
            mouse.y = e.y;
        });

        function initCanvas() {
            width = canvas.width = window.innerWidth;
            height = canvas.height = window.innerHeight;
            particles = [];
            let particleCount = (width * height) / 12000;
            
            for (let i = 0; i < particleCount; i++) {
                particles.push({
                    x: Math.random() * width,
                    y: Math.random() * height,
                    vx: (Math.random() - 0.5) * 1.5,
                    vy: (Math.random() - 0.5) * 1.5,
                    radius: Math.random() * 1.5 + 0.5
                });
            }
        }

        function animateCanvas() {
            ctx.clearRect(0, 0, width, height);
            
            for (let i = 0; i < particles.length; i++) {
                let p = particles[i];
                p.x += p.vx;
                p.y += p.vy;
                
                if (p.x < 0 || p.x > width) p.vx *= -1;
                if (p.y < 0 || p.y > height) p.vy *= -1;
                
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                ctx.fillStyle = "rgba(16, 185, 129, 0.3)";
                ctx.fill();
                
                for (let j = i + 1; j < particles.length; j++) {
                    let p2 = particles[j];
                    let dist = Math.sqrt(Math.pow(p.x - p2.x, 2) + Math.pow(p.y - p2.y, 2));
                    
                    if (dist < 100) {
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(p2.x, p2.y);
                        ctx.strokeStyle = `rgba(16, 185, 129, ${1 - dist/100})`;
                        ctx.lineWidth = 0.5;
                        ctx.stroke();
                    }
                }
                
                if (mouse.x && mouse.y) {
                    let mouseDist = Math.sqrt(Math.pow(p.x - mouse.x, 2) + Math.pow(p.y - mouse.y, 2));
                    if (mouseDist < mouse.radius) {
                        ctx.beginPath();
                        ctx.moveTo(p.x, p.y);
                        ctx.lineTo(mouse.x, mouse.y);
                        ctx.strokeStyle = `rgba(16, 185, 129, ${0.8 - mouseDist/mouse.radius})`;
                        ctx.lineWidth = 1;
                        ctx.stroke();
                    }
                }
            }
            requestAnimationFrame(animateCanvas);
        }
        
        window.addEventListener("resize", initCanvas);
        initCanvas();
        animateCanvas();
    }

    // PHP timeAgo function for use in the template
    <?php
    function timeAgo($timestamp) {
        if (empty($timestamp)) return 'Just now';
        $diff = time() - strtotime($timestamp);
        if ($diff < 60) return $diff . 's ago';
        if ($diff < 3600) return floor($diff / 60) . 'm ago';
        if ($diff < 86400) return floor($diff / 3600) . 'h ago';
        if ($diff < 604800) return floor($diff / 86400) . 'd ago';
        return date("M d", strtotime($timestamp));
    }
    ?>
</script>