<?php
require_once __DIR__ . "/../../config/db.php";

$clients = $conn->query("SELECT idClient, nom FROM clients ORDER BY nom ASC")->fetchAll(PDO::FETCH_ASSOC);

$produits = $conn->query("
    SELECT id, nom, prix_vente 
    FROM produits 
    ORDER BY nom ASC
")->fetchAll(PDO::FETCH_ASSOC);

$produitsOptions = '';
foreach ($produits as $p) {
    $produitsOptions .= '<option value="'.$p['id'].'" data-prix="'.$p['prix_vente'].'">'
        .htmlspecialchars($p['nom']).'</option>';
}
?>

<div class="modal fade" id="ajouterCommandeModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">

      <form method="POST" action="/eagle_client_istanbulcups/api/devis/ajouterCMD.php">

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

        <div class="modal-body">

          <!-- Client + date -->
          <div class="row mb-3">
            <div class="col-md-4">
              <label>Client</label>
              <select name="client_id" class="form-control" required>
                <option value="">-- Choisir --</option>
                <?php foreach ($clients as $c): ?>
                  <option value="<?= $c['idClient'] ?>">
                    <?= htmlspecialchars($c['nom']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-4">
              <label>Date</label>
              <input type="datetime-local" name="date_commande"
                     class="form-control"
                     value="<?= date('Y-m-d\TH:i') ?>">
            </div>
          </div>

          <!-- PRODUITS -->
          <div id="commandeProduits">

            <div class="row mb-2" id="ligne0">

              <div class="col-md-4">
                <label>Designation </label>
                <select name="produits[0][id]"
                        class="form-control produitSelect"
                        onchange="updatePrix(0)">
                  <option value="">Produit</option>
                  <?= $produitsOptions ?>
                </select>
              </div>

              <div class="col-md-2">
                <label>Quantité </label>
                <input type="number"
                       name="produits[0][quantite]"
                       class="form-control qte"
                       value="1"
                       min="1"
                       oninput="calculLigne(0)">
              </div>

              <div class="col-md-2">
                <label>Prix Vente </label>
                <input type="number"
                       id="prix0"
                       class="form-control prix"
                       oninput="calculLigne(0)">
              </div>

              <div class="col-md-2">
                <label>Total </label>
                <input type="text"
                       id="total0"
                       class="form-control total"
                       readonly>
              </div>

              <div class="col-md-2">
                <button type="button"
                        class="btn btn-danger"
                        onclick="removeLigne(0)">
                  🗑️
                </button>
              </div>

            </div>

          </div>

          <button type="button"
                  class="btn btn-success btn-sm mt-2"
                  onclick="addLigne()">
            ➕ Ajouter produit
          </button>

          <!-- TOTAL -->
          <div class="row mt-3">
            <div class="col-md-4">
              <label>Total TTC</label>
              <input type="text" id="totalCommande"
                     name="total_ttc"
                     class="form-control" readonly>
            </div>
          </div>

        </div>

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

      </form>

    </div>
  </div>
</div>

<script>
let index = 1;

function addLigne() {

  let html = `
  <div class="row mb-2" id="ligne${index}">
    <div class="col-md-4">
      <select name="produits[${index}][id]" class="form-control produitSelect"
              onchange="updatePrix(${index})">
        <option value="">Produit</option>
        ${document.querySelector('.produitSelect').innerHTML}
      </select>
    </div>

    <div class="col-md-2">
      <input type="number" name="produits[${index}][quantite]"
             class="form-control qte"
             value="1" min="1"
             oninput="calculLigne(${index})">
    </div>

    <div class="col-md-2">
      <input type="number" id="prix${index}" class="form-control prix"
             oninput="calculLigne(${index})">
    </div>

    <div class="col-md-2">
      <input type="text" id="total${index}" class="form-control total" readonly>
    </div>

    <div class="col-md-2">
      <button type="button" class="btn btn-danger"
              onclick="removeLigne(${index})">🗑️</button>
    </div>
  </div>
  `;

  document.getElementById("commandeProduits")
          .insertAdjacentHTML("beforeend", html);

  index++;
}

function removeLigne(i) {
  document.getElementById("ligne"+i)?.remove();
  calculTotal();
}

function updatePrix(i) {
  let select = document.querySelector(`#ligne${i} .produitSelect`);
  let prix = select.selectedOptions[0].dataset.prix || 0;

  document.getElementById("prix"+i).value = prix;
  calculLigne(i);
}

function calculLigne(i) {
  let q = document.querySelector(`#ligne${i} .qte`).value || 0;
  let p = document.getElementById("prix"+i).value || 0;

  document.getElementById("total"+i).value = (q * p).toFixed(2);

  calculTotal();
}

function calculTotal() {
  let total = 0;

  document.querySelectorAll(".total").forEach(el => {
    total += parseFloat(el.value || 0);
  });

  document.getElementById("totalCommande").value = total.toFixed(2);
}
</script>