{% extends "base_frontoffice.html" %}

{% block content %}
<style>

    .cart-box {
      border: 1px solid #ccc;
      border-radius: 10px;
      padding: 20px;
      background-color: #f8f9fa;
    }
    
  .fxHead{
    overflow: auto;
    height: 450px;
  }
  .fxHead thead th {
    position: sticky;
    top: 0;
    z-index: 1;
    background-color: #F56565;

  }
    
  </style>
<section>
    <div class="container mt-4">
      
        <h4>Commande fournisseur</h4>

      <div class="row">
        <div class="col-sm-12 col-md-7 order-2 order-md-1  text-white">
          <div class=" mt-5">
            <input type="text " id="tableSearch" class="form-control mb-3 w-50" placeholder="Rechercher un article..." >
            <div class="table-responsive fxHead">
            <table class="table table-sm table-stripped table-responsive" id="articleTable">
                <tbody>

                    {% for article in all_articles %}
                     <tr>
                        <td><span class="text-dark">{{ article.code }}</span></td>
                        <td><span class="text-dark">{{ article.nom }}</span></td>
                        <td>
                          <a class="btn btn-outline-dark btn-sm"
                             href="#"
                             data-bs-toggle="modal"
                             data-bs-target="#productModal"
                             data-article_id="{{ article.id }}"
                             data-nom="{{ article.nom }}"
                             data-code="{{ article.code }}"
                             onclick="open_product_modal(this)">
                            Ajouter
                          </a>
                        </td>
                      </tr>
                    {% endfor %}
                </tbody>
            </table>
             </div>  
            </div>
        </div>
        <div class="col-sm-12 col-md-5 order-1 order-md-2  text-white mt-5">
            <div class="cart-box text-center">
            <h4 class="text-center text-dark">Commande fournisseur</h4>
            
            <ul class="list-group mb-3" id="cart-items">
              <li class="list-group-item text-muted" id="empty-cart">Panier vide</li>
            </ul>
            
            <button class="btn btn-warning btn-sm btn-block"  data-bs-toggle="modal" data-bs-target="#saveLivraison" id="saveBtn" disabled>ENREGISTRER</button>
            <a class="btn btn-danger btn-sm btn-block" href="#" onclick="cancel_all()">ANNULER TOUT</a>
            </div>
          </div>
        </div>
        
      </div>
    </div>
</section>
<div class="modal fade" id="productModal" tabindex="-1" aria-labelledby="productModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="productModalLabel">Ajout commande</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form>
          <!-- Quantity -->
          <div class="mb-3">
            <label for="quantityInput" class="form-label">Quantité</label>
            <input type="number" class="form-control" id="quantityInput" min="1" value="1" onclick="this.value = ''">
          </div>

          <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="add2cart()" data-bs-dismiss="modal" id='add2cartBtn'>Ajouter</button>
      </div>
        </form>
      </div>
      
    </div>
  </div>
</div>

<div class="modal fade" id="saveLivraison" tabindex="-1" aria-labelledby="productModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="productModalLabel">ENREGISTREMENT COMMANDE</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form action="/save/panier_commande" method="POST">
          <!-- Quantity -->
          <div class="mb-3">
            <label for="quantityInput" class="form-label">DATE</label>
            <input type="date" class="form-control" name="date" required>
          </div>
        
          <div class="mb-3">
            <label for="montant" class="form-label">MONTANT COMMANDE</label>
            <input type="number" class="form-control"  min="0" step="0.01" value="0" onclick="this.value = ''" required autocomplete="off" name="montant" id="montantInput">
          </div>
          <div id="montantInWords" class="form-text mt-2"></div>
          <div class="modal-footer">
        <button type="submit" class="btn btn-primary" >Ajouter</button>
        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Annuler</button>
      </div>
        </form>
      </div>
      
    </div>
  </div>
</div>
<script src="../static/js/chiffre2lettre.js"></script>
<script>

  const montantInput = document.getElementById('montantInput');
  const montantInWords = document.getElementById('montantInWords');


   montantInput.addEventListener('input', () => {
    montantInput.value = montantInput.value.replace(/[^0-9+ ]/g, ''); 
    const value = parseInt(montantInput.value);
    if (!isNaN(value) && value <= 1000000000) {
      montantInWords.textContent = NumberToLetter(value) + ' Ariary';
    } else {
      montantInWords.textContent = '';
    }
  });
</script>
<script>
document.getElementById("tableSearch").addEventListener("keyup", function () {
  const input = this.value.toLowerCase();
  const rows = document.querySelectorAll("#articleTable tbody tr");

  rows.forEach(row => {
    const rowText = row.innerText.toLowerCase();
    row.style.display = rowText.includes(input) ? "" : "none";
  });
});
</script>

<script>
const ARTICLES = {{ ARTICLE | tojson }};
var cartItems={};
var savedItem={{ commande | tojson }};
var selectedProduct = {};
window.onload=function(){
    var all_number =$(".money");
    for (let number of all_number){
      number.textContent=parseFloat(number.textContent).toLocaleString("fr-FR", {minimumFractionDigits:2});
    };
    rebuild();
    updateCartDisplay();
};

function rebuild(){
    for(let index in savedItem){
        let article_id=savedItem[index]["article_id"];
        let code=savedItem[index]["code"];
        let nom=savedItem[index]["nom"];
        let quantity=parseInt(savedItem[index]["quantity"]);
        let sous_total=parseFloat(savedItem[index]["sous_total"]);
        let prix_achat=parseFloat(savedItem[index]["prix_achat"]);
        if (cartItems[article_id]) {
        cartItems[article_id].quantity = quantity;
        cartItems[article_id].sous_total = sous_total;
      } else {
        cartItems[article_id] = {article_id, code, nom, quantity, prix_achat,sous_total};
      }
    }
}

function open_product_modal(button) {
  selectedProduct.code = button.dataset.code;
  selectedProduct.nom = button.dataset.nom;
  selectedProduct.article_id=parseInt(button.dataset.article_id)
  // Optional: reset inputs
  document.getElementById("quantityInput").value = 1;

}



function add2cart() {
    const quantity = parseInt(document.getElementById("quantityInput").value);
    var code=selectedProduct.code;
    var nom=selectedProduct.nom;
    let article_id=selectedProduct.article_id
      if (cartItems[article_id]) {
        cartItems[article_id].quantity = quantity;
      } else {
        cartItems[article_id] = {article_id, code, nom, quantity};
      }
      cart2server();
}



function cart2server(){
    const cartData = Object.values(cartItems);
    console.log(cartData);
    
    fetch("/commande/update", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(cartData)
    })
    .then(res => res.json())
    .then(data => {
      
      if(data["status"]==="ERROR"){
        for(let i of data["error"]){
          delete cartItems[i["name"]];
          alert("STOCK RESTANT "+i["name"]+"= "+i["stock"]);
        }
      }
      updateCartDisplay();
    })
    .catch(err => {
      console.error("Checkout failed:", err);
      
    });
}



  const cartList = document.getElementById("cart-items");


  function updateCartDisplay() {
    cartList.innerHTML = '';


    for (const key in cartItems) {
      const item = cartItems[key];

      const li = document.createElement("li");
      li.className = "list-group-item d-block d-lg-flex justify-content-between align-items-center";

      // Item name and quantity
      const nameSpan = document.createElement("span");
      nameSpan.classList="badge badge-info text-dark"
      nameSpan.textContent = `${item.code}  ${item.nom} `;

      const controls = document.createElement("span");
      controls.innerHTML = item.quantity;

      // Remove button
      const removeBtn = document.createElement("button");
      removeBtn.className = "remove-btn mx-2";
      removeBtn.textContent = "×";
      removeBtn.title = "Remove";
      removeBtn.onclick = () => {
        delete cartItems[key];
        cart2server();
        updateCartDisplay();
      };
      controls.appendChild(removeBtn);
      li.appendChild(nameSpan);
      li.appendChild(controls);
      cartList.appendChild(li);
    }
    let saveBtn=document.getElementById("saveBtn");
  if (Object.keys(cartItems).length === 0) {
      const li = document.createElement("li");
      li.id = "empty-cart";
      li.className = "list-group-item text-muted";
      li.textContent = "Panier vide";
      cartList.appendChild(li);
      saveBtn.setAttribute("disabled",true);
    }else{
      saveBtn.removeAttribute("disabled");
    }
    
  }


  document.addEventListener("keydown", function(event){
    const modal=document.getElementById("productModal");
    if(modal.classList.contains("show")&&event.key==="Enter"){
        event.preventDefault();
        document.getElementById("add2cartBtn").click();

    }
  })

  function cancel_all() {
    cartItems={};
    cart2server();

  }
</script>

{% endblock %}