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

$id = !empty($_GET['id']) ? (int)$_GET['id'] : null;
$dev = null;
if ($id) {
    $stmt = db()->prepare('SELECT * FROM developments WHERE id = ?');
    $stmt->execute([$id]);
    $dev = $stmt->fetch();
    if (!$dev) { header('Location: /admin/developments.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, '-');
    $highlights = json_encode(array_values(array_filter(array_map('trim', explode("\n", $_POST['highlights'] ?? '')))));

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

    if ($name === '' || empty($_POST['district_id'])) $errors[] = 'Name and district are required.';

    if (empty($errors)) {
        $fields = [
            'name' => $name, 'slug' => $slug,
            'district_id' => (int)$_POST['district_id'],
            'cover_image' => $uploadedCover ?: ($dev['cover_image'] ?? 'assets/images/properties/villa-ext-a.jpg'),
            'starting_price' => (float)($_POST['starting_price'] ?? 0),
            'currency' => trim($_POST['currency'] ?? 'RWF') ?: 'RWF',
            'completion_date' => !empty($_POST['completion_date']) ? $_POST['completion_date'] : null,
            'status' => in_array($_POST['status'] ?? '', ['off-plan', 'under-construction', 'near-completion'], true) ? $_POST['status'] : 'off-plan',
            'highlights' => $highlights,
            'description' => trim($_POST['description'] ?? ''),
            'is_featured' => !empty($_POST['is_featured']) ? 1 : 0,
        ];

        if ($dev) {
            $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($fields)));
            db()->prepare("UPDATE developments SET $set WHERE id = :id")->execute($fields + ['id' => $dev['id']]);
            $devId = $dev['id'];
        } else {
            $cols = implode(', ', array_keys($fields));
            $ph = implode(', ', array_map(fn($k) => ":$k", array_keys($fields)));
            db()->prepare("INSERT INTO developments ($cols) VALUES ($ph)")->execute($fields);
            $devId = (int)db()->lastInsertId();
        }
        flash_set('success', 'Development saved.');
        header('Location: /admin/development-edit.php?id=' . $devId);
        exit;
    }
}

if ($dev) {
    $dev['highlights_text'] = implode("\n", json_decode($dev['highlights'] ?: '[]', true));
}

$pageTitle = $dev ? 'Edit Development' : 'Add Development';
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>Project Name</label><input type="text" name="name" value="<?= e($dev['name'] ?? '') ?>" required></div>
    <div class="field"><label>Slug</label><input type="text" name="slug" value="<?= e($dev['slug'] ?? '') ?>" placeholder="auto-generated if blank"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field">
      <label>District</label>
      <select name="district_id">
        <?php foreach (get_districts() as $d): ?><option value="<?= $d['id'] ?>" <?= ($dev['district_id'] ?? 0) == $d['id'] ? 'selected' : '' ?>><?= e($d['name']) ?></option><?php endforeach; ?>
      </select>
    </div>
    <div class="field">
      <label>Status</label>
      <select name="status">
        <option value="off-plan" <?= ($dev['status'] ?? '') === 'off-plan' ? 'selected' : '' ?>>Off-Plan</option>
        <option value="under-construction" <?= ($dev['status'] ?? '') === 'under-construction' ? 'selected' : '' ?>>Under Construction</option>
        <option value="near-completion" <?= ($dev['status'] ?? '') === 'near-completion' ? 'selected' : '' ?>>Near Completion</option>
      </select>
    </div>
  </div>
  <div class="field-row mb-4">
    <div class="field"><label>Starting Price</label><input type="number" step="0.01" name="starting_price" value="<?= e($dev['starting_price'] ?? '') ?>" required></div>
    <div class="field"><label>Currency</label><input type="text" name="currency" value="<?= e($dev['currency'] ?? 'RWF') ?>"></div>
    <div class="field"><label>Completion Date</label><input type="date" name="completion_date" value="<?= e($dev && $dev['completion_date'] ? date('Y-m-d', strtotime($dev['completion_date'])) : '') ?>"></div>
  </div>
  <div class="field mb-4"><label>Description</label><textarea name="description" rows="4"><?= e($dev['description'] ?? '') ?></textarea></div>
  <div class="field mb-4"><label>Investment Highlights (one per line)</label><textarea name="highlights" rows="5"><?= e($dev['highlights_text'] ?? '') ?></textarea></div>
  <div class="checkbox-row mb-4"><label class="checkbox-row"><input type="checkbox" name="is_featured" value="1" <?= !empty($dev['is_featured']) ? 'checked' : '' ?>> Featured project</label></div>
  <?php if (!empty($dev['cover_image'])): ?>
    <div class="media-frame rounded-md aspect-4-3 mb-4" style="max-width:320px;"><img src="/<?= e($dev['cover_image']) ?>" alt="" width="320" height="240"></div>
  <?php endif; ?>
  <div class="field mb-6"><label>Cover Image</label><input type="file" name="cover_image" accept="image/*"></div>
  <button type="submit" class="btn btn-primary btn-lg">Save Development</button>
</form>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
