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

$id = !empty($_GET['id']) ? (int)$_GET['id'] : null;
$district = null;
if ($id) {
    $stmt = db()->prepare('SELECT * FROM districts WHERE id = ?');
    $stmt->execute([$id]);
    $district = $stmt->fetch();
    if (!$district) { header('Location: /admin/districts.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, '-');

    $uploadedImage = null;
    if (!empty($_FILES['hero_image']['tmp_name']) && is_uploaded_file($_FILES['hero_image']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['hero_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true)) {
            $dir = __DIR__ . '/../assets/images/districts/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $filename = 'district-' . time() . '.' . $ext;
            move_uploaded_file($_FILES['hero_image']['tmp_name'], $dir . $filename);
            $uploadedImage = 'assets/images/districts/' . $filename;
        }
    }

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

    if (empty($errors)) {
        $fields = [
            'name' => $name, 'slug' => $slug,
            'summary' => trim($_POST['summary'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
            'hero_image' => $uploadedImage ?: ($district['hero_image'] ?? 'assets/images/districts/nyarutarama.jpg'),
            'avg_price_indicator' => trim($_POST['avg_price_indicator'] ?? ''),
            'growth_indicator' => trim($_POST['growth_indicator'] ?? ''),
            'lat' => !empty($_POST['lat']) ? (float)$_POST['lat'] : null,
            'lng' => !empty($_POST['lng']) ? (float)$_POST['lng'] : null,
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
        ];
        if ($district) {
            $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($fields)));
            db()->prepare("UPDATE districts SET $set WHERE id = :id")->execute($fields + ['id' => $district['id']]);
            $districtId = $district['id'];
        } else {
            $cols = implode(', ', array_keys($fields));
            $ph = implode(', ', array_map(fn($k) => ":$k", array_keys($fields)));
            db()->prepare("INSERT INTO districts ($cols) VALUES ($ph)")->execute($fields);
            $districtId = (int)db()->lastInsertId();
        }
        flash_set('success', 'District saved.');
        header('Location: /admin/district-edit.php?id=' . $districtId);
        exit;
    }
}

$pageTitle = $district ? 'Edit District' : 'Add District';
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" enctype="multipart/form-data" 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($district['name'] ?? '') ?>" required></div>
    <div class="field"><label>Slug</label><input type="text" name="slug" value="<?= e($district['slug'] ?? '') ?>" placeholder="auto-generated if blank"></div>
  </div>
  <div class="field mb-4"><label>Summary (one line, used in cards)</label><input type="text" name="summary" value="<?= e($district['summary'] ?? '') ?>"></div>
  <div class="field mb-4"><label>Full Description</label><textarea name="description" rows="4"><?= e($district['description'] ?? '') ?></textarea></div>
  <div class="field-row mb-4">
    <div class="field"><label>Price Positioning</label><input type="text" name="avg_price_indicator" value="<?= e($district['avg_price_indicator'] ?? '') ?>" placeholder="e.g. Premium"></div>
    <div class="field"><label>Growth Outlook</label><input type="text" name="growth_indicator" value="<?= e($district['growth_indicator'] ?? '') ?>" placeholder="e.g. Stable, high demand"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field"><label>Latitude</label><input type="text" name="lat" value="<?= e($district['lat'] ?? '-1.9441') ?>"></div>
    <div class="field"><label>Longitude</label><input type="text" name="lng" value="<?= e($district['lng'] ?? '30.0619') ?>"></div>
    <div class="field"><label>Sort Order</label><input type="number" name="sort_order" value="<?= e($district['sort_order'] ?? '0') ?>"></div>
  </div>
  <?php if (!empty($district['hero_image'])): ?>
    <div class="media-frame rounded-md aspect-4-3 mb-4" style="max-width:320px;"><img src="/<?= e($district['hero_image']) ?>" alt="" width="320" height="240"></div>
  <?php endif; ?>
  <div class="field mb-6"><label>Hero Image</label><input type="file" name="hero_image" accept="image/*"></div>
  <button type="submit" class="btn btn-primary btn-lg">Save District</button>
</form>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
