<?php
require_once __DIR__ . '/config.php';
$extra_head = '<link rel="stylesheet" href="/site/styles/blog.css">';
require_once __DIR__ . '/includes/header.php';
// Get slug from URL
$slug = $_GET['slug'] ?? '';

if (!$slug) {
    http_response_code(404);
    echo "<h1>404 Not Found</h1>";
    exit;
}

// Fetch the blog post with author username
try {
    $stmt = $pdo->prepare("
        SELECT posts.*, admin_users.username AS author_name 
        FROM posts 
        LEFT JOIN admin_users ON posts.created_by = admin_users.id 
        WHERE posts.slug = ?
    ");
    $stmt->execute([$slug]);
    $post = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$post) {
        http_response_code(404);
        echo "<h1>Post not found</h1>";
        exit;
    }
} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}

// Determine the featured image path or fallback
$featuredImage = !empty($post['image_path']) ? '/' . $post['image_path'] : '/site/assets/hero.jpg';

// Author username fallback
$authorUsername = !empty($post['author_name']) ? $post['author_name'] : 'Admin';

?>

<main>

  <!-- Featured Image Hero -->
  <section class="hero position-relative" style="height: 60vh; overflow: hidden;">
    <img src="<?= htmlspecialchars($featuredImage) ?>" alt="<?= htmlspecialchars($post['title']) ?>" class="hero-bg" />
<div class="hero-content text-white text-center position-absolute top-50 start-50 translate-middle w-100" style="max-width: 600px;">
      <h1 class="display-4 fw-bold"><?= htmlspecialchars($post['title']) ?></h1>
      <p class="mt-2 info-by  text-white"><?= date('F j, Y', strtotime($post['created_at'] ?? '')) ?> · By <?= htmlspecialchars($authorUsername) ?></p>
    </div>
  </section>

  <!-- Blog Content -->
  <section class="container py-5">
    <article class="post-content">
      <?= $post['content'] ?>
    </article>
  </section>

</main>

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