<?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 districts WHERE id = ?')->execute([(int)$_GET['delete']]);
    flash_set('success', 'District deleted.');
    header('Location: /admin/districts.php');
    exit;
}

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