<?php
session_start();

require_once "../../config/db.php";
// Fetch all blogs
$stmt = $pdo->query("SELECT * FROM blogs ORDER BY created_at DESC");
$blogs = $stmt->fetchAll();

if (!isset($_SESSION["admin_logged_in"])) {
  // Not logged in
  header("Location: /admin/login.php");
  exit;
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Blog List</title>
  <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/slick.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/responsive.css">
</head>
<body>
    <div class="body-bg">
        <?php include '../includes/sidebar.php'; ?>

        <section class="nftmax-adashboard nftmax-show">
        <div class="heading d-flex justify-content-between py-2">
        <h2>Blog List</h2>
            <a href="create.php" class="h-auto w-auto btn-one">Add New Blog</a>
        </div>

            <div class="row">
  <?php foreach ($blogs as $blog): ?>
    <div class="col-md-4 mb-4">
      <div class="card h-100 shadow-sm">
        <?php if (!empty($blog['featured_image'])): ?>
          <img src="../<?= htmlspecialchars($blog['featured_image']) ?>" 
               class="card-img-top" 
               alt="<?= htmlspecialchars($blog['title']) ?>">
        <?php endif; ?>

        <div class="card-body d-flex flex-column">
          <h5 class="card-title"><?= htmlspecialchars($blog['title']) ?></h5>
          <p class="card-text text-muted">
            <?= htmlspecialchars(substr(strip_tags($blog['content']), 0, 100)) ?>...
          </p>

          <div class="mt-auto">

            <div class="d-flex gap-2">
              <a href="edit.php?id=<?= $blog['id'] ?>" 
                 class="btn btn-dark btn-sm flex-fill">
                Edit
              </a>
              <a href="delete.php?id=<?= $blog['id'] ?>" 
                 class="btn btn-danger btn-sm flex-fill" 
                 onclick="return confirm('Delete this blog?')">
                Delete
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
</div>

        </section>
    </div>


    <script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script>
    <script src="../assets/js/jquery-3.6.3.min.js"></script>
  <script src="../assets/js/slick.min.js"></script>
  <script src="../assets/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/js/chart.js"></script>
  <script src="../assets/js/custom.js"></script>
  <script src="../assets/js/modeControl.js"></script>
</body>
</html>
