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

$iconKeys = ['villa', 'house', 'townhouse', 'apartment', 'penthouse', 'duplex', 'office', 'retail', 'hotel', 'warehouse', 'land', 'development', 'agriculture', 'commercial'];

$id = !empty($_GET['id']) ? (int)$_GET['id'] : null;
$category = null;
if ($id) {
    $stmt = db()->prepare('SELECT * FROM property_categories WHERE id = ?');
    $stmt->execute([$id]);
    $category = $stmt->fetch();
    if (!$category) { header('Location: /admin/categories.php'); exit; }
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check()) $errors[] = 'Session expired, please try again.';
    $name = trim($_POST['name'] ?? '');
    $slug = trim($_POST['slug'] ?? '') ?: preg_replace('/[^a-z0-9]+/', '-', strtolower($name));
    $slug = trim($slug, '-');

    if ($name === '') $errors[] = 'Name is required.';

    if (empty($errors)) {
        $fields = [
            'name' => $name, 'slug' => $slug,
            'icon' => in_array($_POST['icon'] ?? '', $iconKeys, true) ? $_POST['icon'] : 'house',
            'description' => trim($_POST['description'] ?? ''),
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
        ];
        if ($category) {
            $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($fields)));
            db()->prepare("UPDATE property_categories SET $set WHERE id = :id")->execute($fields + ['id' => $category['id']]);
            $categoryId = $category['id'];
        } else {
            $cols = implode(', ', array_keys($fields));
            $ph = implode(', ', array_map(fn($k) => ":$k", array_keys($fields)));
            db()->prepare("INSERT INTO property_categories ($cols) VALUES ($ph)")->execute($fields);
            $categoryId = (int)db()->lastInsertId();
        }
        flash_set('success', 'Category saved.');
        header('Location: /admin/category-edit.php?id=' . $categoryId);
        exit;
    }
}

$pageTitle = $category ? 'Edit Category' : 'Add Category';
include __DIR__ . '/includes/layout-header.php';
$flash = flash_get('success');
?>
<?php if ($flash): ?><div class="form-success mb-6"><?= e($flash) ?></div><?php endif; ?>
<?php foreach ($errors as $err): ?><div class="form-error mb-4"><?= e($err) ?></div><?php endforeach; ?>

<form method="post" class="admin-card">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <div class="field-row mb-4">
    <div class="field"><label>Name</label><input type="text" name="name" value="<?= e($category['name'] ?? '') ?>" required></div>
    <div class="field"><label>Slug</label><input type="text" name="slug" value="<?= e($category['slug'] ?? '') ?>" placeholder="auto-generated if blank"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field">
      <label>Icon</label>
      <select name="icon">
        <?php foreach ($iconKeys as $k): ?><option value="<?= e($k) ?>" <?= ($category['icon'] ?? '') === $k ? 'selected' : '' ?>><?= e(ucfirst($k)) ?></option><?php endforeach; ?>
      </select>
    </div>
    <div class="field"><label>Sort Order</label><input type="number" name="sort_order" value="<?= e($category['sort_order'] ?? '0') ?>"></div>
  </div>
  <div class="field mb-6"><label>Description</label><textarea name="description" rows="3"><?= e($category['description'] ?? '') ?></textarea></div>
  <button type="submit" class="btn btn-primary btn-lg">Save Category</button>
</form>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
