<?php
require 'config/db.php';

// Get Post by Slug
if (!isset($_GET['slug'])) {
    header("Location: blog.php"); exit();
}
$slug = $_GET['slug'];

$stmt = $pdo->prepare("SELECT * FROM posts WHERE slug = ?");
$stmt->execute([$slug]);
$post = $stmt->fetch();

if (!$post) {
    header("Location: blog.php"); exit();
}

// Update Views
$pdo->prepare("UPDATE posts SET views = views + 1 WHERE id = ?")->execute([$post['id']]);

// Set Dynamic SEO Tags (Override header default)
$page_title = $post['title'] . " - Tools Empire Blog";
$page_desc = substr(strip_tags($post['content']), 0, 150);
$page_img = "https://toolsempire.net/" . $post['image'];

// Include Header (Manual meta injection logic would go here in a complex setup, but standard header is fine for now)
include 'includes/header.php';
?>

<div class="container" style="max-width: 800px; padding-top: 40px; padding-bottom: 60px;">
    
    <div style="text-align: center; margin-bottom: 30px;">
        <h1 style="font-size: 36px; color: #2c3e50; margin-bottom: 10px;"><?php echo htmlspecialchars($post['title']); ?></h1>
        <p style="color: #888; font-size: 14px;">
            <i class="far fa-calendar"></i> <?php echo date('F d, Y', strtotime($post['created_at'])); ?> &nbsp;|&nbsp; 
            <i class="far fa-eye"></i> <?php echo $post['views']; ?> Views
        </p>
    </div>

    <?php if($post['image']): ?>
        <img src="<?php echo $post['image']; ?>" style="width: 100%; border-radius: 8px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
    <?php endif; ?>

    <div class="blog-content" style="font-size: 18px; line-height: 1.8; color: #333;">
        <?php echo nl2br($post['content']); // Output raw content (allows HTML tags if sanitized properly) ?>
    </div>

    <hr style="margin: 50px 0; border: 0; border-top: 1px solid #eee;">

    <!-- CTA: Convert Readers to Buyers -->
    <div style="background: #f0f8ff; padding: 30px; border-radius: 12px; text-align: center;">
        <h3>Looking for Premium Tools?</h3>
        <p>Get genuine license keys at student prices instantly.</p>
        <a href="index.php" class="btn btn-primary" style="width: auto; display: inline-block; padding: 12px 30px;">Browse Shop</a>
    </div>

</div>

<?php include 'includes/footer.php'; ?>