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

$fournisseurs = $conn->query("SELECT id, nom FROM fournisseurs")->fetchAll(PDO::FETCH_ASSOC);
$produits = $conn->query("
  SELECT p.id, p.nom, COALESCE(SUM(sd.quantite),0) AS stock
  FROM produits p
  LEFT JOIN stock_depot sd ON p.id = sd.produit_id
  GROUP BY p.id, p.nom
")->fetchAll(PDO::FETCH_ASSOC);

$numeroBC = "BC-".date('Ymd-His');
?>

<div class="container-fluid">
<h1 class="mt-4">Achats fournisseurs</h1>

    <ol class="breadcrumb mb-4">
        <li class="breadcrumb-item">
            <a href="index.php?page=dashboard">Tableau de bord</a>
        </li>
        <li class="breadcrumb-item active">Achats fournisseurs</li>
    </ol>

<form method="POST"
      action="/eagle_client_istanbulcups/api/achats/commande_fournisseur_save.php">

<input type="hidden" name="numero" value="<?= $numeroBC ?>">

<div class="row">
  <div class="col-md-4">
    <label>Fournisseur</label>
    <select name="fournisseur_id" class="form-control" required>
      <option value="">-- Choisir fournisseur --</option>
      <?php foreach($fournisseurs as $f): ?>
        <option value="<?= $f['id'] ?>"><?= htmlspecialchars($f['nom']) ?></option>
      <?php endforeach ?>
    </select>
  </div>

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

<hr>

<table class="table table-bordered" id="tableProduits">
<thead class="table-dark">
<tr>
  <th>Produit</th>
  <th>Stock</th>
  <th>Qté commandée</th>
  <th></th>
</tr>
</thead>
<tbody></tbody>
</table>

<button type="button" class="btn btn-secondary" id="btnAdd">+ Produit</button>
<button type="submit" class="btn btn-primary">Enregistrer</button>
</form>
</div>

<?php include __DIR__ . "/../../includes/layout_end.php"; ?>

<script>
$(function(){

const produits = <?= json_encode($produits) ?>;
let idx = 0;

$("#btnAdd").click(function(){

  let options = produits.map(p =>
    `<option value="${p.id}" data-stock="${p.stock}">
       ${p.nom}
     </option>`
  ).join('');

  $("#tableProduits tbody").append(`
    <tr>
      <td>
        <select name="produits[${idx}][produit_id]"
                class="form-control prodSelect"
                required>
          ${options}
        </select>
      </td>
      <td class="stock text-center">0</td>
      <td>
        <input type="number"
               name="produits[${idx}][quantite]"
               min="1"
               class="form-control"
               required>
      </td>
      <td class="text-center">
        <button type="button" class="btn btn-danger btn-sm remove">×</button>
      </td>
    </tr>
  `);

  idx++;
});

$(document).on("change",".prodSelect",function(){
  let stock = $(this).find(":selected").data("stock");
  $(this).closest("tr").find(".stock").text(stock);
});

$(document).on("click",".remove",function(){
  $(this).closest("tr").remove();
});

});
</script>
