<?php
require_once __DIR__ . '/includes/auth.php';
require_admin();

if (!empty($_GET['delete']) && isset($_GET['csrf']) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $_GET['csrf'])) {
    db()->prepare('DELETE FROM blog_posts WHERE id = ?')->execute([(int)$_GET['delete']]);
    flash_set('success', 'Post deleted.');
    header('Location: /admin/blog.php');
    exit;
}

$posts = db()->query('SELECT * FROM blog_posts ORDER BY published_at DESC')->fetchAll();
$pageTitle = 'Blog & News';
include __DIR__ . '/includes/layout-header.php';
$flash = flash_get('success');
?>
<?php if ($flash): ?><div class="form-success mb-6"><?= e($flash) ?></div><?php endif; ?>
<div class="flex justify-between items-center mb-6">
  <p class="text-muted"><?= count($posts) ?> posts</p>
  <a href="/admin/blog-edit.php" class="btn btn-primary">+ Add Post</a>
</div>
<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th>Title</th><th>Type</th><th>Category</th><th>Published</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($posts as $p): ?>
        <tr>
          <td class="fw-semibold"><?= e($p['title']) ?></td>
          <td><span class="badge badge-outline"><?= e($p['type']) ?></span></td>
          <td><?= e($p['category']) ?></td>
          <td><?= date('M j, Y', strtotime($p['published_at'])) ?></td>
          <td class="flex gap-2">
            <a href="/<?= $p['type'] === 'news' ? 'news' : 'blog' ?>/<?= e($p['slug']) ?>" target="_blank" class="btn btn-outline btn-sm">View</a>
            <a href="/admin/blog-edit.php?id=<?= (int)$p['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/blog.php?delete=<?= (int)$p['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this post?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
