<?php
require_once "inc/config.php";
require_once "inc/functions.php";
checkLogin();

$role = $_SESSION['admin']['role'] ?? 'admin';
$admin_countries = $_SESSION['admin']['countries'] ?? 'all';
$admin_cities = $_SESSION['admin']['cities'] ?? 'all';

// --- AJOUT / MODIFICATION ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $id = $_POST['id'] ?? null;
    $titre = trim($_POST['titre']);
    $description = trim($_POST['description']);
    $categorie = trim($_POST['categorie']);
    $ville = trim($_POST['ville']);
    $pays = trim($_POST['pays']);
    $nom = trim($_POST['nom']);
    $tel = trim($_POST['tel']);
    $email = trim($_POST['email']);
    $type = trim($_POST['type']);
    $prix = floatval($_POST['prix']);
    $statut = $_POST['statut'] ?? '1';
    $photo = trim($_POST['photo']);
    $ajtle = date('Y-m-d H:i:s');
    $createdby = $_SESSION['admin']['email'] ?? 'system';

    if (empty($id)) {
        $stmt = $dbh->prepare("INSERT INTO mondialisa_annonces 
            (ref, user_ref, titre, description, categorie, ville, pays, nom, tel, email, type, ajtle, photo, prix, top, statut) 
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
            uniqid('ANN-'), '', $titre, $description, $categorie, $ville, $pays,
            $nom, $tel, $email, $type, $ajtle, $photo, $prix, 0, $statut
        ]);
        showMsg('success', "Listing inserted.");
    } else {
        $stmt = $dbh->prepare("UPDATE mondialisa_annonces 
            SET titre=?, description=?, categorie=?, ville=?, pays=?, nom=?, tel=?, email=?, type=?, prix=?, statut=?, photo=? 
            WHERE id=?");
        $stmt->execute([
            $titre, $description, $categorie, $ville, $pays, $nom, $tel, $email,
            $type, $prix, $statut, $photo, $id
        ]);
        showMsg('success', "Listing updated.");
    }

    header("Location: annonces.php");
    exit;
}

// --- SUPPRESSION ---
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $dbh->prepare("DELETE FROM mondialisa_annonces WHERE id=?");
    $stmt->execute([$id]);
    showMsg('success', "Annonce supprimée.");
    header("Location: annonces.php");
    exit;
}

// --- LISTE DES ANNONCES ---
$sql = "SELECT * FROM mondialisa_annonces ORDER BY id DESC";
$stmt = $dbh->query($sql);
$annonces = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include "inc/header.php"; ?>
<?php include "inc/sidebar.php"; ?>

<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
  <?php include "inc/topbar.php"; ?>
  
  <div class="pt-3 pb-2 mb-3 border-bottom d-flex justify-content-between align-items-center">
    <h2>📢 Classifieds</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#annonceModal">➕ New</button>
  </div>

  <?php displayMsgs(); ?>

  <div class="table-responsive">
    <table class="table table-hover align-middle table-bordered">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Title</th>
          <th>Category</th>
          <th>Price</th>
          <th>Name</th>
          <th>City</th>
          <th>Country</th>
          <th>Type</th>
          <th>Statut</th>
          <th>Created</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($annonces as $a): ?>
        <tr>
          <td><?= $a['id'] ?></td>
          <td><?= htmlspecialchars($a['titre']) ?></td>
          <td><?= htmlspecialchars($a['categorie']) ?></td>
          <td><?= number_format($a['prix'], 2) ?> DH</td>
          <td><?= htmlspecialchars($a['nom']) ?></td>
          <td><?= htmlspecialchars($a['ville']) ?></td>
          <td><?= htmlspecialchars($a['pays']) ?></td>
          <td><?= htmlspecialchars($a['type']) ?></td>
          <td>
            <span class="badge bg-<?= $a['statut'] == '1' ? 'success' : 'secondary' ?>">
              <?= $a['statut'] ?>
            </span>
          </td>
          <td><?= htmlspecialchars($a['ajtle']) ?></td>
          <td>
            <button class="btn btn-sm btn-outline-primary" 
                    onclick='editAnnonce(<?= json_encode($a, JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'>✏️</button>
            <a href="?delete=<?= $a['id'] ?>" class="btn btn-sm btn-outline-danger"
               onclick="return confirm('Confirm delete ?')">🗑️</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</main>

<!-- 🧩 Modal Ajout / Edition -->
<div class="modal fade" id="annonceModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="post">
      <div class="modal-header">
        <h5 class="modal-title">New listing</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="annonce_id">

        <div class="row">
          <div class="col-md-6 mb-3">
            <label>Title</label>
            <input type="text" name="titre" id="annonce_titre" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Category</label>
            <input type="text" name="categorie" id="annonce_categorie" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Name</label>
            <input type="text" name="nom" id="annonce_nom" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Email</label>
            <input type="email" name="email" id="annonce_email" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Tel</label>
            <input type="text" name="tel" id="annonce_tel" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Price</label>
            <input type="number" step="0.01" name="prix" id="annonce_prix" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Country</label>
            <input type="text" name="pays" id="annonce_pays" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>City</label>
            <input type="text" name="ville" id="annonce_ville" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Type</label>
            <select name="type" id="annonce_type" class="form-select">
              <option value="offre">Offer</option>
              <option value="demande">Demand</option>
            </select>
          </div>
          <div class="col-md-6 mb-3">
            <label>Statut</label>
            <select name="statut" id="annonce_statut" class="form-select">
              <option value="1">Online</option>
              <option value="0">Offline</option>
            </select>
          </div>
          <div class="col-md-12 mb-3">
            <label>Description</label>
            <textarea name="description" id="annonce_description" class="form-control" rows="4"></textarea>
          </div>
          <div class="col-md-12 mb-3">
            <label>Photo (URL)</label>
            <input type="text" name="photo" id="annonce_photo" class="form-control">
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" name="save" class="btn btn-primary">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
function editAnnonce(a) {
  document.getElementById('annonce_id').value = a.id;
  document.getElementById('annonce_titre').value = a.titre;
  document.getElementById('annonce_description').value = a.description;
  document.getElementById('annonce_categorie').value = a.categorie;
  document.getElementById('annonce_nom').value = a.nom;
  document.getElementById('annonce_tel').value = a.tel;
  document.getElementById('annonce_email').value = a.email;
  document.getElementById('annonce_prix').value = a.prix;
  document.getElementById('annonce_pays').value = a.pays;
  document.getElementById('annonce_ville').value = a.ville;
  document.getElementById('annonce_type').value = a.type;
  document.getElementById('annonce_statut').value = a.statut;
  document.getElementById('annonce_photo').value = a.photo;
  document.querySelector('#annonceModal .modal-title').textContent = "Modify listing";
  new bootstrap.Modal(document.getElementById('annonceModal')).show();
}
</script>

<?php include "inc/footer.php"; ?>
