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

function csrf_check_get(): bool {
    return isset($_GET['csrf']) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $_GET['csrf']);
}

if (!empty($_GET['delete']) && csrf_check_get()) {
    $stmt = db()->prepare('DELETE FROM properties WHERE id = ?');
    $stmt->execute([(int)$_GET['delete']]);
    flash_set('success', 'Property deleted.');
    header('Location: /admin/properties.php');
    exit;
}

$properties = db()->query('SELECT p.*, c.name AS category_name, d.name AS district_name FROM properties p LEFT JOIN property_categories c ON c.id=p.category_id LEFT JOIN districts d ON d.id=p.district_id ORDER BY p.created_at DESC')->fetchAll();

$pageTitle = 'Properties';
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($properties) ?> total listings</p>
  <a href="/admin/property-edit.php" class="btn btn-primary">+ Add Property</a>
</div>
<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th>Title</th><th>Status</th><th>Category</th><th>District</th><th>Price</th><th>Featured</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($properties as $p): ?>
        <tr>
          <td><a href="/properties/<?= e($p['slug']) ?>" target="_blank" class="fw-semibold"><?= e($p['title']) ?></a></td>
          <td><span class="badge <?= $p['status'] === 'rent' ? 'badge-rent' : 'badge-sale' ?>"><?= e($p['status']) ?></span></td>
          <td><?= e($p['category_name']) ?></td>
          <td><?= e($p['district_name']) ?></td>
          <td><?= e($p['currency']) ?> <?= money((float)$p['price']) ?></td>
          <td><?= $p['is_featured'] ? icon('check', 16) : '—' ?></td>
          <td class="flex gap-2">
            <a href="/admin/property-edit.php?id=<?= (int)$p['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/properties.php?delete=<?= (int)$p['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this property? This cannot be undone.')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
