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

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

$categories = db()->query('SELECT * FROM property_categories ORDER BY sort_order')->fetchAll();
$pageTitle = 'Property Categories';
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($categories) ?> categories</p>
  <a href="/admin/category-edit.php" class="btn btn-primary">+ Add Category</a>
</div>
<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th></th><th>Name</th><th>Icon Key</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($categories as $c): ?>
        <tr>
          <td><?= category_icon($c['icon']) ?></td>
          <td class="fw-semibold"><?= e($c['name']) ?></td>
          <td><?= e($c['icon']) ?></td>
          <td class="flex gap-2">
            <a href="/category/<?= e($c['slug']) ?>" target="_blank" class="btn btn-outline btn-sm">View</a>
            <a href="/admin/category-edit.php?id=<?= (int)$c['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/categories.php?delete=<?= (int)$c['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this category? Properties assigned to it will need reassigning.')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
