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

$developments = db()->query('SELECT dv.*, d.name AS district_name FROM developments dv LEFT JOIN districts d ON d.id = dv.district_id ORDER BY dv.created_at DESC')->fetchAll();

$pageTitle = 'New Developments';
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($developments) ?> projects</p>
  <a href="/admin/development-edit.php" class="btn btn-primary">+ Add Development</a>
</div>
<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th>Name</th><th>District</th><th>Starting Price</th><th>Status</th><th>Completion</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($developments as $dv): ?>
        <tr>
          <td class="fw-semibold"><?= e($dv['name']) ?></td>
          <td><?= e($dv['district_name']) ?></td>
          <td><?= e($dv['currency']) ?> <?= money((float)$dv['starting_price']) ?></td>
          <td><span class="badge badge-outline"><?= e(development_status_label($dv['status'])) ?></span></td>
          <td><?= $dv['completion_date'] ? date('M Y', strtotime($dv['completion_date'])) : 'TBC' ?></td>
          <td class="flex gap-2">
            <a href="/new-development" target="_blank" class="btn btn-outline btn-sm">View</a>
            <a href="/admin/development-edit.php?id=<?= (int)$dv['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/developments.php?delete=<?= (int)$dv['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this development?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($developments)): ?><tr><td colspan="6" class="text-center text-muted">No developments yet.</td></tr><?php endif; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
