<?php
session_start();
require_once '../db.php'; // Adjust path if needed
include 'menu.php';

// Fetch blog posts with categories
$stmt = $pdo->query("
    SELECT blogs.*, categories.name AS category 
    FROM blogs 
    LEFT JOIN categories ON blogs.category_id = categories.id 
    ORDER BY blogs.created_at DESC
");
$blogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
  <title>Manage Blogs</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      border: 1px solid #ccc;
      padding: 8px;
      font-family: Arial, sans-serif;
    }
    th {
      background-color: #f2f2f2;
    }
    a {
      color: #007BFF;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>
  <h1>All Blog Posts</h1>
  <a href="add_blog.php">Add New Blog</a><br><br>
  <table>
    <tr><th>Title</th><th>Category</th><th>Created</th><th>Actions</th></tr>
    <?php foreach ($blogs as $row): ?>
    <tr>
      <td><?= htmlspecialchars($row['title']) ?></td>
      <td><?= htmlspecialchars($row['category'] ?? 'Uncategorized') ?></td>
      <td><?= date('Y-m-d', strtotime($row['created_at'])) ?></td>
      <td>
        <a href="edit_blog.php?id=<?= $row['id'] ?>">Edit</a> | 
        <a href="delete_blog.php?id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete this blog post?')">Delete</a>
      </td>
    </tr>
    <?php endforeach; ?>
  </table>
</body>
</html>
