<?php
if (!defined("APP_LOADED")) { exit; }

// Assure que la session est démarrée
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// --- Génération captcha ---
$op = (rand(0,1) === 1) ? '+' : '-';
$a = rand(1,9);
$b = ($op === '+') ? rand(1,9) : rand(0,$a);
$_SESSION['captcha_result'] = ($op === '+') ? $a + $b : $a - $b;
?>

<div class="container mt-4">
    <h3><?= trad('Create New Listing'); ?></h3>
    <hr>

<?php if(isset($_SESSION['COUNTRY']) && !empty($_SESSION['COUNTRY'])) : ?>

<form id="annonceForm" enctype="multipart/form-data" method="post" action="save_annonce.php">


<!-- ⭐ MULTI-PHOTO UPLOADER -------------------------------- -->
<div class="mb-3">
    <label class="form-label">Photos</label>

    <label class="btn btn-primary mb-2">
        + Add Photos
        <input type="file" id="photosInput" name="photos[]" accept="image/*" multiple hidden>
    </label>

    <div id="photoPreview" class="preview-grid"></div>

    <input type="hidden" name="sorted_photos" id="sortedPhotos">
</div>

<style>
.preview-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.preview-item {
    width: 110px;
    height: 110px;
    border: 2px solid #ccc;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
    cursor: grab;
}

.preview-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.main-badge {
    position: absolute;
    top: 5px;
    left: 5px;
    background: #28a745;
    color: white;
    padding: 2px 6px;
    font-size: 12px;
    border-radius: 4px;
    display: none;
}

.preview-item.main .main-badge {
    display: block;
}

.remove-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(255,0,0,0.8);
    color: white;
    border: none;
    border-radius: 50%;
    width: 22px;
    height: 22px;
    cursor: pointer;
    text-align: center;
}
</style>
<!-- END PHOTOS ------------------------------------------ -->


<hr/>
<!-- TYPE -->
<div class="mb-3">
    <label class="form-label d-block"><?= trad('Type') ?></label>

    <div class="form-check form-check-inline">
        <input class="form-check-input" type="radio" name="type" value="offre" checked>
        <label class="form-check-label"><?= trad('type_offer') ?></label>
    </div>

    <div class="form-check form-check-inline">
        <input class="form-check-input" type="radio" name="type" value="demande">
        <label class="form-check-label"><?= trad('type_request') ?></label>
    </div>
</div>


<!-- CATEGORY -->
<div class="mb-3">
    <label class="form-label"><?= trad('Category') ?></label>
    <div class="cats d-flex flex-wrap gap-2">
        
       <div class="cats">
  <label>
    <input type="radio" name="cat" value="immobilier" hidden>
    <div class="cat">🏠 <?= trad('Real Estate'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="vehicule" hidden>
    <div class="cat">🚗 <?= trad('Vehicles'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="emploi" hidden>
    <div class="cat">👔 <?= trad('Jobs'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="market" hidden>
    <div class="cat">🛍️ <?= trad('Market'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="b2b" hidden>
    <div class="cat">💼 <?= trad('B2B'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="ecole" hidden>
    <div class="cat">🎓 <?= trad('School & Training'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="rencontre" hidden>
    <div class="cat">💞 <?= trad('Dating'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="loisir" hidden>
    <div class="cat">🎨 <?= trad('Leisure'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="voyage" hidden>
    <div class="cat">✈️ <?= trad('Travel'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="sante" hidden>
    <div class="cat">🩺 <?= trad('Health'); ?></div>
  </label>

  <label>
    <input type="radio" name="cat" value="autre" hidden>
    <div class="cat">✨ <?= trad('Others'); ?></div>
  </label>
</div>
     
    </div>
</div>


<!-- TITLE -->
<div class="mb-3">
    <label class="form-label"><?= trad('Title') ?></label>
    <input type="text" class="form-control" name="titre" required>
</div>

<!-- DESCRIPTION -->
<div class="mb-3">
    <label class="form-label"><?= trad('Description') ?></label>
    <textarea class="form-control" name="description" rows="4" required></textarea>
</div>

<!-- PRICE -->
<div class="mb-3">
    <label class="form-label"><?= trad('Price') ?></label>
    <input type="number" class="form-control" name="prix" required>
</div>

<!-- CITY -->
<div class="mb-3">
    <label class="form-label"><?= trad('City') ?></label>
    <input type="text" id="location" class="form-control" name="ville" autocomplete="off" required>
    <div id="suggestions" class="list-group mt-1" style="position:relative; z-index:2000;"></div>
</div>

<!-- PHONE -->
<div class="mb-3">
    <label class="form-label"><?= trad('Phone') ?></label>
    <input type="tel" class="form-control" name="tel" required value="<?= htmlspecialchars($_SESSION['user']['tel'] ?? '') ?>">
</div>

<!-- IF NOT LOGGED -->
<?php if (!isset($_SESSION['user']) || empty($_SESSION['user']['connected'])): ?>
<div class="mb-3">
    <label class="form-label"><?= trad('Password') ?></label>
    <input type="password" class="form-control" name="mdp" required>
</div>

<div class="mb-3">
    <label class="form-label"><?= trad('Your name') ?></label>
    <input type="text" class="form-control" name="nom" required>
</div>

<div class="mb-3">
    <label class="form-label">Email</label>
    <input type="email" class="form-control" name="email">
</div>
<?php endif; ?>

<!-- note -->
<div class="mb-3">
    <label class="form-label"><?= trad('Note') ?></label>
    <textarea class="form-control" name="note" rows="4" required></textarea>
</div>

   <div class="mb-3">
                <label for="captcha"><?= htmlspecialchars(trad('What is')) ?> <?= (int)$a ?> <?= htmlspecialchars($op) ?> <?= (int)$b ?> ?</label>
                <input type="text" name="captcha" id="captcha" class="form-control" required placeholder="<?= htmlspecialchars(trad('Enter the result')) ?>">
            </div>



<button type="submit" class="btn btn-success"><?= trad('Submit') ?></button>
</form>

<?php endif; ?>
</div>


<!-- ⭐⭐⭐ JAVASCRIPT MULTI-PHOTO COMPLETE ⭐⭐⭐ -->
<script>
let photoArray = [];
const photosInput = document.getElementById("photosInput");
const photoPreview = document.getElementById("photoPreview");
const form = document.getElementById("annonceForm");

photosInput?.addEventListener("change", function(e){
    const files = Array.from(e.target.files);
    photoArray.push(...files);
    photosInput.value = "";
    updatePreview();
});

function updatePreview(){
    photoPreview.innerHTML = "";
    photoArray.forEach((file, index) => {
        let r = new FileReader();
        r.onload = ev => {
            let div = document.createElement("div");
            div.className = "preview-item" + (index === 0 ? " main":"");
            div.draggable = true;
            div.innerHTML = `
                <span class="main-badge">MAIN</span>
                <img src="${ev.target.result}">
                <button type="button" class="remove-btn" data-i="${index}">×</button>
            `;

            div.addEventListener("click", e=>{
                if(e.target.classList.contains("remove-btn")) return;
                setMainPhoto(index);
            });

            div.querySelector(".remove-btn").addEventListener("click", e=>{
                e.stopPropagation();
                removePhoto(index);
            });

            div.addEventListener("dragstart", dragStart);
            div.addEventListener("dragover", dragOver);
            div.addEventListener("drop", drop);

            photoPreview.appendChild(div);
        };
        r.readAsDataURL(file);
    });

    document.getElementById("sortedPhotos").value = photoArray.map(f => f.name).join(",");
}

function removePhoto(i){
    photoArray.splice(i,1);
    updatePreview();
}

function setMainPhoto(i){
    if(i === 0) return;
    const f = photoArray.splice(i,1)[0];
    photoArray.unshift(f);
    updatePreview();
}

let dragSrcIndex = null;
function dragStart(e){ dragSrcIndex = [...this.parentNode.children].indexOf(this); }
function dragOver(e){ e.preventDefault(); }
function drop(e){
    const dropIndex = [...this.parentNode.children].indexOf(this);
    const moved = photoArray.splice(dragSrcIndex,1)[0];
    photoArray.splice(dropIndex,0,moved);
    dragSrcIndex = null;
    updatePreview();
}

form?.addEventListener("submit", function(){
    const dt = new DataTransfer();
    photoArray.forEach(f => dt.items.add(f));
    photosInput.files = dt.files;
});
</script>


<style>
  .hero {
  position: relative;
  background: url('img/default-ad.webp') center/cover no-repeat;
  color: #1115e0ff;
  text-align: center;
  padding: 60px 20px;
}
  .cats {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
    color: #202022ff;
  gap: 12px;
  margin-top: 10px;
}

.cats label {
  cursor: pointer;
}

.cat {
  background: #c8cae9ff;
  border-radius: 12px;
  padding: 10px 20px;
  font-size: 1rem;
font-weight: normal;
  transition: 0.3s;
  border: 2px solid transparent;
}

/* Effet hover */
.cat:hover {
  background: #0077ff;
  color: white;
}

/* Effet quand le bouton radio est coché */
.cats input[type="radio"]:checked + .cat {
  background: #0077ff;
  color: white;
  border-color: #005fd1;
}
</style>

<script>
document.getElementById('location').addEventListener('input', function() {
  const query = this.value;
  const suggestionBox = document.getElementById('suggestions');

  if (query.length < 2) {
    suggestionBox.innerHTML = '';
    return;
  }

  fetch('ajax_cities.php?q=' + encodeURIComponent(query))
    .then(res => res.json())
    .then(data => {
      suggestionBox.innerHTML = '';
      data.forEach(city => {
        const div = document.createElement('div');
        div.textContent = city.name + (city.country ? " (" + city.country + ")" : "");
        div.classList.add('suggestion-item');
        div.onclick = () => {
          document.getElementById('location').value = city.name;
          suggestionBox.innerHTML = '';
        };
        suggestionBox.appendChild(div);
      });
    });
});
</script>

