<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();
$db = getDB();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$prop = null;
$images = [];
$errors = [];
$isEdit = false;

if ($id) {
    $stmt = $db->prepare("SELECT * FROM properties WHERE id = ?");
    $stmt->execute([$id]);
    $prop = $stmt->fetch();
    if (!$prop) { setFlash('error','Propriété introuvable.'); redirect(SITE_URL . '/admin/properties'); }
    $images = getPropertyImages($id);
    $isEdit = true;
}

// SAVE
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRF($_POST['csrf_token'] ?? '')) { setFlash('error','Session expirée.'); redirect(SITE_URL . '/admin/property_edit' . ($id ? "?id=$id" : '')); }

    $title      = sanitize($_POST['title'] ?? '');
    $description= $_POST['description'] ?? '';
    $type       = sanitize($_POST['type'] ?? '');
    $status     = sanitize($_POST['status'] ?? 'vente');
    $city       = sanitize($_POST['city'] ?? '');
    $address    = sanitize($_POST['address'] ?? '');
    $price      = !empty($_POST['price']) ? (float)$_POST['price'] : null;
    $price_label= sanitize($_POST['price_label'] ?? '');
    $surface    = !empty($_POST['surface']) ? (int)$_POST['surface'] : null;
    $rooms      = !empty($_POST['rooms']) ? (int)$_POST['rooms'] : null;
    $bedrooms   = !empty($_POST['bedrooms']) ? (int)$_POST['bedrooms'] : null;
    $bathrooms  = !empty($_POST['bathrooms']) ? (int)$_POST['bathrooms'] : null;
    $year_built = !empty($_POST['year_built']) ? (int)$_POST['year_built'] : null;
    $featured   = !empty($_POST['featured']) ? 1 : 0;
    $pub_status = sanitize($_POST['publication_status'] ?? 'brouillon');
    $lat        = !empty($_POST['lat']) ? (float)$_POST['lat'] : null;
    $lng        = !empty($_POST['lng']) ? (float)$_POST['lng'] : null;

    if (!$title) $errors[] = 'Le titre est obligatoire.';
    if (!$type)  $errors[] = 'Le type est obligatoire.';
    if (!$city)  $errors[] = 'La ville est obligatoire.';

    if (empty($errors)) {
        $slug = slugify($title) . ($isEdit ? '' : '-' . time());

        if (!$price_label && $price) {
            $price_label = number_format($price, 0, ',', ' ') . ' MAD';
        } elseif (!$price_label) {
            $price_label = 'Prix sur demande';
        }

        if ($isEdit) {
            $stmt = $db->prepare("UPDATE properties SET title=?,slug=?,description=?,type=?,status=?,city=?,address=?,price=?,price_label=?,surface=?,rooms=?,bedrooms=?,bathrooms=?,year_built=?,featured=?,publication_status=?,lat=?,lng=? WHERE id=?");
            $stmt->execute([$title,$slug,htmlspecialchars_decode($description),$type,$status,$city,$address,$price,$price_label,$surface,$rooms,$bedrooms,$bathrooms,$year_built,$featured,$pub_status,$lat,$lng,$id]);
        } else {
            $stmt = $db->prepare("INSERT INTO properties (title,slug,description,type,status,city,address,price,price_label,surface,rooms,bedrooms,bathrooms,year_built,featured,publication_status,lat,lng) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([$title,$slug,htmlspecialchars_decode($description),$type,$status,$city,$address,$price,$price_label,$surface,$rooms,$bedrooms,$bathrooms,$year_built,$featured,$pub_status,$lat,$lng]);
            $id = $db->lastInsertId();
        }

        // Handle new image uploads
        if (!empty($_FILES['images']['name'][0])) {
            $sortStart = count($images);
            foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
                if ($_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) continue;
                $ext = strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg','jpeg','png','webp'])) continue;
                $fname = 'property_' . $id . '_' . uniqid() . '.' . $ext;
                $targetDir = __DIR__ . '/../assets/uploads/properties/';
                if (!is_dir($targetDir)) mkdir($targetDir, 0755, true);
                if (move_uploaded_file($tmp, $targetDir . $fname)) {
                    $isPrimary = ($sortStart === 0 && $i === 0) ? 1 : 0;
                    $db->prepare("INSERT INTO property_images (property_id,image_path,is_primary,sort_order) VALUES (?,?,?,?)")
                       ->execute([$id, 'assets/uploads/properties/' . $fname, $isPrimary, $sortStart + $i]);
                }
            }
        }

        // Handle primary image selection
        if (!empty($_POST['primary_image'])) {
            $db->prepare("UPDATE property_images SET is_primary = 0 WHERE property_id = ?")->execute([$id]);
            $db->prepare("UPDATE property_images SET is_primary = 1 WHERE id = ? AND property_id = ?")->execute([(int)$_POST['primary_image'], $id]);
        }

        // Handle image deletions
        if (!empty($_POST['delete_images'])) {
            foreach ((array)$_POST['delete_images'] as $imgId) {
                $imgId = (int)$imgId;
                $row = $db->prepare("SELECT image_path FROM property_images WHERE id = ? AND property_id = ?");
                $row->execute([$imgId, $id]); $row = $row->fetch();
                if ($row) {
                    @unlink(__DIR__ . '/../' . $row['image_path']);
                    $db->prepare("DELETE FROM property_images WHERE id = ?")->execute([$imgId]);
                }
            }
        }

        setFlash('success', $isEdit ? 'Propriété mise à jour.' : 'Propriété créée.');
        redirect(SITE_URL . '/admin/property_edit?id=' . $id);
    }
}

$types = getPropertyTypes(); $zones = getZones();
$pageTitle = $isEdit ? 'Modifier la propriété' : 'Nouvelle propriété'; $activeNav = 'properties';
include __DIR__ . '/layout.php';
?>

<?php if (!empty($errors)): ?>
<div class="bg-red-50 border border-red-200 p-4 mb-6">
  <?php foreach($errors as $e): ?><p class="text-sm text-red-700 font-sans"><?=htmlspecialchars($e)?></p><?php endforeach; ?>
</div>
<?php endif; ?>

<div class="max-w-4xl">
  <form method="POST" enctype="multipart/form-data" class="space-y-8" id="property-form">
    <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>

    <!-- Basic Info -->
    <div class="bg-white border border-gray-200 p-8">
      <h2 class="font-serif text-lg font-light text-black mb-6">Informations générales</h2>
      <div class="grid grid-cols-1 gap-6">
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre *</label>
          <input type="text" name="title" value="<?=htmlspecialchars($prop['title']??'')?>" required class="input-underline"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Description</label>
          <div id="desc-editor" class="quill-editor min-h-[200px]"><?=htmlspecialchars_decode(htmlspecialchars($prop['description']??''))?></div>
          <input type="hidden" name="description" id="desc-editor_value" value="<?=htmlspecialchars($prop['description']??'')?>"/>
        </div>
      </div>
    </div>

    <!-- Type, Status, City -->
    <div class="bg-white border border-gray-200 p-8">
      <h2 class="font-serif text-lg font-light text-black mb-6">Classification</h2>
      <div class="grid grid-cols-2 lg:grid-cols-3 gap-6">
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Type de bien *</label>
          <select name="type" required class="select-underline">
            <option value="">Sélectionner...</option>
            <?php foreach($types as $v=>$l): ?>
            <option value="<?=$v?>" <?=($prop['type']??'')===$v?'selected':''?>><?=$l?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Statut</label>
          <select name="status" class="select-underline">
            <option value="vente" <?=($prop['status']??'')==='vente'?'selected':''?>>À vendre</option>
            <option value="location" <?=($prop['status']??'')==='location'?'selected':''?>>À louer</option>
          </select>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Zone / Ville *</label>
          <input type="text" name="city" value="<?=htmlspecialchars($prop['city']??'')?>" required class="input-underline" list="city-list"/>
          <datalist id="city-list">
            <?php foreach($zones as $z): ?><option value="<?=htmlspecialchars($z)?>"><?php endforeach; ?>
          </datalist>
        </div>
        <div class="lg:col-span-3">
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Adresse</label>
          <input type="text" name="address" value="<?=htmlspecialchars($prop['address']??'')?>" class="input-underline"/>
        </div>
      </div>
    </div>

    <!-- Price & Specs -->
    <div class="bg-white border border-gray-200 p-8">
      <h2 class="font-serif text-lg font-light text-black mb-6">Prix & Caractéristiques</h2>
      <div class="grid grid-cols-2 lg:grid-cols-3 gap-6">
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Prix (MAD)</label>
          <input type="number" name="price" value="<?=htmlspecialchars($prop['price']??'')?>" class="input-underline" step="1000" min="0"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Libellé du prix</label>
          <input type="text" name="price_label" value="<?=htmlspecialchars($prop['price_label']??'')?>" class="input-underline" placeholder="Auto-calculé si vide"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Surface (m²)</label>
          <input type="number" name="surface" value="<?=htmlspecialchars($prop['surface']??'')?>" class="input-underline" min="1"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Pièces</label>
          <input type="number" name="rooms" value="<?=htmlspecialchars($prop['rooms']??'')?>" class="input-underline" min="1"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Chambres</label>
          <input type="number" name="bedrooms" value="<?=htmlspecialchars($prop['bedrooms']??'')?>" class="input-underline" min="0"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Salles de bain</label>
          <input type="number" name="bathrooms" value="<?=htmlspecialchars($prop['bathrooms']??'')?>" class="input-underline" min="0"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Année de construction</label>
          <input type="number" name="year_built" value="<?=htmlspecialchars($prop['year_built']??'')?>" class="input-underline" min="1900" max="<?=date('Y')?>"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Latitude</label>
          <input type="text" name="lat" value="<?=htmlspecialchars($prop['lat']??'')?>" class="input-underline" placeholder="33.5240"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Longitude</label>
          <input type="text" name="lng" value="<?=htmlspecialchars($prop['lng']??'')?>" class="input-underline" placeholder="-7.8259"/>
        </div>
      </div>
    </div>

    <!-- Photos -->
    <div class="bg-white border border-gray-200 p-8">
      <h2 class="font-serif text-lg font-light text-black mb-6">Photos</h2>
      <?php if (!empty($images)): ?>
      <div class="grid grid-cols-3 sm:grid-cols-4 gap-3 mb-6">
        <?php foreach($images as $img): ?>
        <div class="relative group">
          <img src="<?= SITE_URL ?>/<?=htmlspecialchars($img['image_path'])?>" class="w-full aspect-square object-cover <?=$img['is_primary']?'ring-2 ring-black':''?>" alt=""/>
          <?php if($img['is_primary']): ?><span class="absolute top-1 left-1 bg-black text-white text-[9px] px-2 py-0.5 font-sans">Principale</span><?php endif; ?>
          <div class="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
            <label class="bg-white text-black text-[9px] px-2 py-1 cursor-pointer font-sans">
              <input type="radio" name="primary_image" value="<?=$img['id']?>" class="hidden"/>
              ★ Principale
            </label>
            <label class="bg-red-500 text-white text-[9px] px-2 py-1 cursor-pointer font-sans">
              <input type="checkbox" name="delete_images[]" value="<?=$img['id']?>" class="hidden"/>
              Supprimer
            </label>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
      <div>
        <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Ajouter des photos</label>
        <input type="file" name="images[]" multiple accept="image/*" class="text-sm font-sans text-gray-600 file:mr-4 file:py-2 file:px-4 file:border file:border-gray-200 file:text-xs file:font-sans file:tracking-[0.1em] file:uppercase file:cursor-pointer hover:file:border-black"/>
        <p class="text-xs text-gray-400 font-sans mt-1">JPG, PNG ou WebP. Multiple images acceptées.</p>
      </div>
    </div>

    <!-- Publication Options -->
    <div class="bg-white border border-gray-200 p-8">
      <h2 class="font-serif text-lg font-light text-black mb-6">Publication</h2>
      <div class="flex flex-wrap gap-8">
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-3">Statut de publication</label>
          <div class="flex gap-3">
            <label class="cursor-pointer flex items-center gap-2">
              <input type="radio" name="publication_status" value="publie" <?=($prop['publication_status']??'brouillon')==='publie'?'checked':''?>>
              <span class="text-sm font-sans">Publié</span>
            </label>
            <label class="cursor-pointer flex items-center gap-2">
              <input type="radio" name="publication_status" value="brouillon" <?=($prop['publication_status']??'brouillon')==='brouillon'?'checked':''?>>
              <span class="text-sm font-sans">Brouillon</span>
            </label>
          </div>
        </div>
        <div class="flex items-center gap-3">
          <input type="checkbox" name="featured" id="featured" value="1" <?=!empty($prop['featured'])?'checked':''?> class="w-4 h-4 accent-black"/>
          <label for="featured" class="text-sm font-sans cursor-pointer">Afficher en page d'accueil (vedette)</label>
        </div>
      </div>
    </div>

    <!-- Buttons -->
    <div class="flex gap-4">
      <button type="submit" class="bg-black text-white text-xs tracking-[0.15em] uppercase px-8 py-3 hover:bg-gray-900 transition-colors font-sans">Enregistrer</button>
      <a href="<?= SITE_URL ?>/admin/properties" class="border border-gray-200 text-xs tracking-[0.15em] uppercase px-8 py-3 hover:bg-gray-50 transition-colors font-sans text-gray-600">Annuler</a>
    </div>
  </form>
</div>

<?php include __DIR__ . '/layout_footer.php'; ?>
