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

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

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check()) { $errors[] = 'Session expired. Please try again.'; }

    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '') ?: preg_replace('/[^a-z0-9]+/', '-', strtolower($title));
    $slug = trim($slug, '-');
    $status = in_array($_POST['status'] ?? '', ['sale', 'rent'], true) ? $_POST['status'] : 'sale';
    $categoryId = (int)($_POST['category_id'] ?? 0);
    $districtId = (int)($_POST['district_id'] ?? 0);
    $price = (float)($_POST['price'] ?? 0);
    $currency = trim($_POST['currency'] ?? 'RWF') ?: 'RWF';
    $pricePeriod = in_array($_POST['price_period'] ?? '', ['month', 'year'], true) ? $_POST['price_period'] : '';
    $features = json_encode(array_values(array_filter(array_map('trim', explode("\n", $_POST['features'] ?? '')))));
    $amenities = json_encode(array_values(array_filter(array_map('trim', explode("\n", $_POST['amenities'] ?? '')))));
    $agentId = !empty($_POST['agent_id']) ? (int)$_POST['agent_id'] : null;

    if ($title === '' || !$categoryId || !$districtId) $errors[] = 'Title, category and district are required.';

    if (empty($errors)) {
        $fields = [
            'title' => $title, 'slug' => $slug, 'status' => $status,
            'category_id' => $categoryId, 'district_id' => $districtId,
            'sector' => trim($_POST['sector'] ?? ''), 'neighborhood' => trim($_POST['neighborhood'] ?? ''),
            'address' => trim($_POST['address'] ?? ''), 'price' => $price, 'currency' => $currency, 'price_period' => $pricePeriod,
            'bedrooms' => (int)($_POST['bedrooms'] ?? 0), 'bathrooms' => (int)($_POST['bathrooms'] ?? 0),
            'land_size_sqm' => (int)($_POST['land_size_sqm'] ?? 0), 'building_size_sqm' => (int)($_POST['building_size_sqm'] ?? 0),
            'short_description' => trim($_POST['short_description'] ?? ''), 'description' => trim($_POST['description'] ?? ''),
            'features' => $features, 'amenities' => $amenities,
            'investment_score' => (int)($_POST['investment_score'] ?? 70),
            'estimated_rent' => !empty($_POST['estimated_rent']) ? (float)$_POST['estimated_rent'] : null,
            'lat' => !empty($_POST['lat']) ? (float)$_POST['lat'] : null,
            'lng' => !empty($_POST['lng']) ? (float)$_POST['lng'] : null,
            'video_url' => trim($_POST['video_url'] ?? ''), 'tour_360_url' => trim($_POST['tour_360_url'] ?? ''),
            'is_featured' => !empty($_POST['is_featured']) ? 1 : 0, 'is_new' => !empty($_POST['is_new']) ? 1 : 0,
            'agent_id' => $agentId,
            'meta_title' => trim($_POST['meta_title'] ?? ''), 'meta_description' => trim($_POST['meta_description'] ?? ''),
        ];

        if ($property) {
            $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($fields)));
            $stmt = db()->prepare("UPDATE properties SET $set WHERE id = :id");
            $stmt->execute($fields + ['id' => $property['id']]);
            $propertyId = $property['id'];
        } else {
            $cols = implode(', ', array_keys($fields));
            $placeholders = implode(', ', array_map(fn($k) => ":$k", array_keys($fields)));
            $stmt = db()->prepare("INSERT INTO properties ($cols) VALUES ($placeholders)");
            $stmt->execute($fields);
            $propertyId = (int)db()->lastInsertId();
        }

        /* Handle image uploads */
        if (!empty($_FILES['images']['name'][0])) {
            $uploadDir = __DIR__ . '/../uploads/properties/' . $propertyId . '/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            $sortStmt = db()->prepare('SELECT COALESCE(MAX(sort_order),0) FROM property_images WHERE property_id = ?');
            $sortStmt->execute([$propertyId]);
            $sort = (int)$sortStmt->fetchColumn();
            foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
                if (!is_uploaded_file($tmp)) continue;
                $ext = strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true)) continue;
                $sort++;
                $filename = 'img-' . time() . '-' . $sort . '.' . $ext;
                move_uploaded_file($tmp, $uploadDir . $filename);
                $relPath = 'uploads/properties/' . $propertyId . '/' . $filename;
                $insertImg = db()->prepare('INSERT INTO property_images (property_id, image_path, alt_text, sort_order) VALUES (?, ?, ?, ?)');
                $insertImg->execute([$propertyId, $relPath, $title, $sort]);
            }
        }

        flash_set('success', 'Property saved successfully.');
        header('Location: /admin/property-edit.php?id=' . $propertyId);
        exit;
    }
}

if ($property) {
    $property['features_text'] = implode("\n", json_decode($property['features'] ?: '[]', true));
    $property['amenities_text'] = implode("\n", json_decode($property['amenities'] ?: '[]', true));
    $images = get_property_images($property['id']);
}

$pageTitle = $property ? 'Edit Property' : 'Add Property';
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()) ?>">
  <h3>Basic Information</h3>
  <div class="field-row mb-4">
    <div class="field"><label>Title</label><input type="text" name="title" value="<?= e($property['title'] ?? '') ?>" required></div>
    <div class="field"><label>Slug (URL, optional)</label><input type="text" name="slug" value="<?= e($property['slug'] ?? '') ?>" placeholder="auto-generated if blank"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field">
      <label>Status</label>
      <select name="status">
        <option value="sale" <?= ($property['status'] ?? '') === 'sale' ? 'selected' : '' ?>>For Sale</option>
        <option value="rent" <?= ($property['status'] ?? '') === 'rent' ? 'selected' : '' ?>>For Rent</option>
      </select>
    </div>
    <div class="field">
      <label>Category</label>
      <select name="category_id">
        <?php foreach (get_categories() as $c): ?><option value="<?= $c['id'] ?>" <?= ($property['category_id'] ?? 0) == $c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option><?php endforeach; ?>
      </select>
    </div>
    <div class="field">
      <label>District</label>
      <select name="district_id">
        <?php foreach (get_districts() as $d): ?><option value="<?= $d['id'] ?>" <?= ($property['district_id'] ?? 0) == $d['id'] ? 'selected' : '' ?>><?= e($d['name']) ?></option><?php endforeach; ?>
      </select>
    </div>
  </div>
  <div class="field-row mb-4">
    <div class="field"><label>Sector</label><input type="text" name="sector" value="<?= e($property['sector'] ?? '') ?>"></div>
    <div class="field"><label>Neighborhood</label><input type="text" name="neighborhood" value="<?= e($property['neighborhood'] ?? '') ?>"></div>
    <div class="field"><label>Full Address</label><input type="text" name="address" value="<?= e($property['address'] ?? '') ?>"></div>
  </div>

  <h3 class="mt-6">Pricing</h3>
  <div class="field-row mb-4">
    <div class="field"><label>Price</label><input type="number" step="0.01" name="price" value="<?= e($property['price'] ?? '') ?>" required></div>
    <div class="field"><label>Currency</label><input type="text" name="currency" value="<?= e($property['currency'] ?? 'RWF') ?>"></div>
    <div class="field">
      <label>Price Period (rent only)</label>
      <select name="price_period">
        <option value="" <?= ($property['price_period'] ?? '') === '' ? 'selected' : '' ?>>N/A (sale)</option>
        <option value="month" <?= ($property['price_period'] ?? '') === 'month' ? 'selected' : '' ?>>Per Month</option>
        <option value="year" <?= ($property['price_period'] ?? '') === 'year' ? 'selected' : '' ?>>Per Year</option>
      </select>
    </div>
  </div>

  <h3 class="mt-6">Specifications</h3>
  <div class="field-row mb-4">
    <div class="field"><label>Bedrooms</label><input type="number" name="bedrooms" value="<?= e($property['bedrooms'] ?? '0') ?>"></div>
    <div class="field"><label>Bathrooms</label><input type="number" name="bathrooms" value="<?= e($property['bathrooms'] ?? '0') ?>"></div>
    <div class="field"><label>Land Size (m²)</label><input type="number" name="land_size_sqm" value="<?= e($property['land_size_sqm'] ?? '0') ?>"></div>
    <div class="field"><label>Building Size (m²)</label><input type="number" name="building_size_sqm" value="<?= e($property['building_size_sqm'] ?? '0') ?>"></div>
  </div>

  <h3 class="mt-6">Descriptions</h3>
  <div class="field mb-4"><label>Short Description (used in listings/meta)</label><input type="text" name="short_description" value="<?= e($property['short_description'] ?? '') ?>"></div>
  <div class="field mb-4"><label>Full Description</label><textarea name="description" rows="6"><?= e($property['description'] ?? '') ?></textarea></div>
  <div class="field-row mb-4">
    <div class="field"><label>Features (one per line)</label><textarea name="features" rows="6"><?= e($property['features_text'] ?? '') ?></textarea></div>
    <div class="field"><label>Amenities (one per line)</label><textarea name="amenities" rows="6"><?= e($property['amenities_text'] ?? '') ?></textarea></div>
  </div>

  <h3 class="mt-6">Investment &amp; Media</h3>
  <div class="field-row mb-4">
    <div class="field"><label>Investment Score (0-100)</label><input type="number" min="0" max="100" name="investment_score" value="<?= e($property['investment_score'] ?? '70') ?>"></div>
    <div class="field"><label>Estimated Monthly Rent (for ROI calc)</label><input type="number" name="estimated_rent" value="<?= e($property['estimated_rent'] ?? '') ?>"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field"><label>Latitude</label><input type="text" name="lat" value="<?= e($property['lat'] ?? '-1.9441') ?>"></div>
    <div class="field"><label>Longitude</label><input type="text" name="lng" value="<?= e($property['lng'] ?? '30.0619') ?>"></div>
  </div>
  <div class="field-row mb-4">
    <div class="field"><label>Video URL (embed)</label><input type="text" name="video_url" value="<?= e($property['video_url'] ?? '') ?>"></div>
    <div class="field"><label>360° Tour URL</label><input type="text" name="tour_360_url" value="<?= e($property['tour_360_url'] ?? '') ?>"></div>
  </div>
  <div class="field mb-4">
    <label>Assigned Agent</label>
    <select name="agent_id">
      <option value="">None</option>
      <?php foreach (get_agents() as $a): ?><option value="<?= $a['id'] ?>" <?= ($property['agent_id'] ?? 0) == $a['id'] ? 'selected' : '' ?>><?= e($a['name']) ?></option><?php endforeach; ?>
    </select>
  </div>
  <div class="flex gap-6 mb-6">
    <label class="checkbox-row"><input type="checkbox" name="is_featured" value="1" <?= !empty($property['is_featured']) ? 'checked' : '' ?>> Featured listing</label>
    <label class="checkbox-row"><input type="checkbox" name="is_new" value="1" <?= !empty($property['is_new']) ? 'checked' : '' ?>> Mark as "New"</label>
  </div>

  <h3 class="mt-6">SEO</h3>
  <div class="field mb-4"><label>Meta Title</label><input type="text" name="meta_title" value="<?= e($property['meta_title'] ?? '') ?>"></div>
  <div class="field mb-6"><label>Meta Description</label><textarea name="meta_description" rows="2"><?= e($property['meta_description'] ?? '') ?></textarea></div>

  <h3 class="mt-6">Photos</h3>
  <?php if (!empty($images)): ?>
    <div class="grid grid-4 mb-4">
      <?php foreach ($images as $img): ?>
        <div class="media-frame rounded-md aspect-4-3"><img src="/<?= e($img['image_path']) ?>" alt="<?= e($img['alt_text']) ?>" width="200" height="150"></div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
  <div class="field mb-6">
    <label>Upload New Photos (JPG, PNG, WebP)</label>
    <input type="file" name="images[]" multiple accept="image/*">
  </div>

  <button type="submit" class="btn btn-primary btn-lg">Save Property</button>
</form>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
