<?php foreach ($commandes as $c): ?>
<div class="modal fade" id="livrerCommande<?= $c['id'] ?>" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header bg-primary text-white">
        <h5>Confirmer livraison</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        Voulez-vous livrer la commande <b><?= $c['numero'] ?></b> ?
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>

        <button class="btn btn-primary btnConfirmLivraison"
                data-id="<?= $c['id'] ?>">
          Confirmer
        </button>
      </div>

    </div>
  </div>
</div>
<?php endforeach; ?>


<script>
document.addEventListener("DOMContentLoaded", function () {

  document.querySelectorAll(".btnConfirmLivraison").forEach(btn => {

    btn.addEventListener("click", function () {

      const id = this.dataset.id;

      if (!id) {
        alert("ID commande invalide");
        return;
      }

      // Désactiver bouton pour éviter double clic
      this.disabled = true;
      this.innerText = "Traitement...";

      fetch("/eagle_client_istanbulcups/api/devis/livrer.php", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ commande_id: id })
      })
      .then(res => res.json())
      .then(data => {

        if (data.success) {
          alert("Commande livrée avec succès");
          location.reload(); // refresh
        } else {
          alert(data.message || "Erreur");
          this.disabled = false;
          this.innerText = "Confirmer";
        }

      })
      .catch(err => {
        console.error(err);
        alert("Erreur serveur");
        this.disabled = false;
        this.innerText = "Confirmer";
      });

    });

  });

});
</script>