{% extends "base_frontoffice.html" %}

{% block content %}
 <div class="container ">
  <div class="row mt-5">
    <!-- Cart Section -->
    <div class="col-md-6">
      <h4 class="mb-3">Votre Panier</h4>
       
      <ul class="list-group mb-3" id="cart-items">
        {% for article ,data in CHECKOUT.items() %}
        <li class="list-group-item d-block d-lg-flex justify-content-between align-items-center"><span class="badge badge-info text-dark">{{article.full_name}} <span class="money">{{data["prix_unit"]}}</span>  x {{data["quantity"]}}</span><br><span class="badge badge-danger text-dark money">-{{data["remise"]}}</span><span class="money">{{data["subtotal"]}}</span>
        </li>
        {% endfor %}
        <li class="list-group-item d-flex justify-content-between">
          <span>Total remise</span>
          <strong class="money">{{REMISE}}</strong>
        </li>
        <li class="list-group-item d-flex justify-content-between">
          <span>Net à payer</span>
          <strong class="money" >{{TOTAL}}</strong>
        </li>
        <li class="list-group-item d-flex justify-content-between">
          <span >Total en lettre</span>
          <strong id="total_letter">{{TOTAL}}</strong>
        </li>
      </ul>
      

    </div>

    <!-- Billing Form Section -->
    <div class="col-md-6">
      <h4 class="mb-3">Information</h4>
      <form method="POST" action="/checkout/cart" onkeydown="return event.key !== 'Enter'" id="cartForm">
          
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">Client</span>
              <select class="form-control "  name="client" onchange="selectClient(this)">
                <option value="0">NOUVEAU CLIENT</option>
                {% for client in all_client %}
                  <option value="{{client.id}}" data-name="{{client.nom}}" data-phone="{{client.phone}}">{{client.full_name}}</option>
                {% endfor %}
              </select>
          </div>
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">Téléphone</span>
          <input type="tel" pattern="[0-9\s+]+" maxlength="30" class="form-control" id="phone" required name="phone" autocomplete="off">
          </div>
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">Nom</span>
          <input type="text" class="form-control" id="nom" required name="nom" autocomplete="off">
          </div>
          
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">Adresse</span>
          <input type="text" class="form-control" id="address"  name="address" autocomplete="off">
        </div>
           <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">Date commande</span>
          <input type="date" class="form-control" id="date"  name="date" required>
        </div>

        <hr class="my-4">
        <h4 class="mb-3">Livraison</h4>
            {% for article ,data in CHECKOUT.items() %}
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">{{article.code}}</span>
          <input type="number" class="form-control w-50 livraison"  required name="livraison_{{article.id}}" value="0" min="0" onclick="this.value = ''" max="{{data['quantity']}}" data-article='{{article.id}}' onchange="quantity_change(this)" data-pu="{{article.prix_vente_html}}">
          </div>
          <div id="error_{{article.id}}" class="text-danger mt-1" style="display: none;">La quantité dépasse le max.</div>
          {% endfor %}
        <hr class="my-4">
        <h4 class="mb-3">Règlement</h4>
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">MONTANT</span>
          <input type="number" class="form-control" id="moneyInput"  required min="0" step="0.01" name="montant" autocomplete="off" onclick="this.value = ''">
          </div>
          <div id="moneyInWords" class="form-text mt-2"></div>
          
          <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-light" id="basic-addon1">MODE DE PAIEMENT</span>
            <select class="form-control " required  name="mode">
              <option value="ESPECE">ESPECE</option>
              <option value="MOBILE MONEY">MOBILE MONEY</option>
              <option value="VIREMENT">VIREMENT</option>
              <option value="CHEQUE">CHEQUE</option>
            </select>
          </div>
          <div class="input-group mb-1">
          <span class="input-group-text bg-secondary text-light" id="basic-addon1">CAISSE</span>
              <select class="form-control "  name="caisse">
                {% for caisse in all_caisse %}
                  <option value="{{caisse.id}}">{{caisse.name}}</option>
                {% endfor %}
              </select>
          </div>
         

        <hr class="my-4">
        <button class="btn btn-primary btn-lg w-100" type="button" data-bs-toggle="modal" data-bs-target="#confirmationModal" onclick="show_confirmation()" disabled id="submitBtn">ENREGISTRER COMMANDE</button>
      </form>
    </div>

</div>
</div>

<div class="modal fade" id="confirmationModal" tabindex="-1" aria-labelledby="cancelLabel" >
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="cancelLabel">CONFIRMATION COMMANDE</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
        <div class="table-responsive mt-1">
        <table class="table table-sm align-items-center justify-content-center mb-0">
            <tbody id="client_body">
            </tbody>
        </table> 
        </div> 
        <div class="table-responsive my-3">
        <table class="table table-sm align-items-center justify-content-center mb-0">
            <thead class="table-light">
                <tr>
                    <th>Ref</th>
                    <th>PU</th>
                    <th>Qté</th>
                    <th>Rem</th>
                    <th>Montant</th>
                    <th>A livrer</th>
                </tr>
            </thead>
            <tbody id="commande_body">
             </tbody>
        </table> 
        </div>
         <hr>
         <h5 class="modal-title">Règlement</h5>
        <div class="table-responsive mt-1">
        <table class="table table-sm align-items-center justify-content-center mb-0">
            <tbody id="reglement_body">
            </tbody>
        </table> 
        </div>
        
      <div class="modal-footer">
        <button type="submit" class="btn btn-warning" form="cartForm">ENREGISTRER</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">FERMER</button>
      </div>
    </div>
   
  </div>
</div>
</div>
<script>
  var savedItem={{ data | tojson }};
  var cartItems={};
  window.onload=function(){
    var all_number =$(".money");
    for (let number of all_number){

      number.textContent=parseFloat(number.textContent).toLocaleString("fr-FR", {minimumFractionDigits:2});
    };

    const total_letter=document.getElementById("total_letter");
   total_letter.textContent= NumberToLetter(parseInt(total_letter.textContent));
   rebuild();

};
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 total_remise=parseFloat(savedItem[index]["total_remise"]);
        if (cartItems[article_id]) {
        cartItems[article_id].quantity = quantity;
        cartItems[article_id].total_remise = quantity*remise;
        cartItems[article_id].sous_total = quantity*unitPrice-cartItems[article_id].total_remise;

      } else {
        cartItems[article_id] = {article_id, code, nom, quantity, total_remise,sous_total};
      }
    }

}

function quantity_change(self) {
  const max=parseInt(self.max);
  const value=parseInt(self.value);
 
  const article_id=self.dataset.article;
   const warning = document.getElementById('error_'+article_id);
  if(value>max){
    self.classList.add("is-invalid");
    self.value=0;
    warning.style.display = 'block';
  }else{
    warning.style.display = 'none';
    self.classList.contains('is-invalid') ? self.classList.remove('is-invalid') : null;
  }

}



function selectClient(self){

  let nom=document.getElementById("nom");
  let phone=document.getElementById("phone");
  let address=document.getElementById("address");
  if(self.value==="0"){

    nom.hasAttribute("disabled") ? nom.removeAttribute('disabled') :null;
    phone.hasAttribute("disabled") ? phone.removeAttribute('disabled') :null;
    address.hasAttribute("disabled") ? address.removeAttribute('disabled') :null;
  }else{
    nom.setAttribute("disabled",true);
    phone.setAttribute("disabled",true);
    address.setAttribute("disabled",true);
  }
}
</script>
<script>
  const form = document.getElementById('cartForm');
  const submitBtn = document.getElementById('submitBtn');

    function toggleSubmitButton() {
    submitBtn.disabled = !form.checkValidity(); // Disable if not valid
  }

  // Run once on load (in case browser autofills)
  toggleSubmitButton();

  // Listen for input changes
  form.addEventListener('input', toggleSubmitButton);

  const phone = document.getElementById('phone');

  phone.addEventListener('input', () => {
    phone.value = phone.value.replace(/[^0-9+ /]/g, ''); // allow digits, spaces, plus
  });
</script>

<script src="../static/js/chiffre2lettre.js"></script>
<script>
  const moneyInput = document.getElementById('moneyInput');
  const moneyInWords = document.getElementById('moneyInWords');

  moneyInput.addEventListener('input', () => {
    moneyInput.value = moneyInput.value.replace(/[^0-9+ ]/g, ''); 
    const value = parseInt(moneyInput.value);
    if (!isNaN(value) && value <= 1000000000) {
      moneyInWords.textContent = NumberToLetter(value) + ' Ariary';
    } else {
      moneyInWords.textContent = '';
    }
  });


function detail_client(name,phone) {
   const client_body=document.getElementById("client_body");
   client_body.innerHTML="";
   let tr=document.createElement("tr");
   tr.classList="bg-secondary";
   let td_name=document.createElement("td");
   td_name.textContent="NOM CLIENT";
   let td_name_value=document.createElement("td");
   td_name_value.classList="bg-info";
   td_name_value.textContent=name;
   let td_phone=document.createElement("td");
   td_phone.textContent="TELEPHONE";
   let td_phone_value=document.createElement("td");
   td_phone_value.textContent=phone;
   td_phone_value.classList="bg-info";
   tr.appendChild(td_name);
   tr.appendChild(td_name_value);
   tr.appendChild(td_phone);
   tr.appendChild(td_phone_value);
   client_body.appendChild(tr);
 } 

function panier_livrer() {
   const commande_body=document.getElementById("commande_body")
   commande_body.innerHTML="";
   let livraison=document.getElementsByClassName("livraison");
  Array.from(livraison).forEach((item,index)=>{
    cartItems[item.dataset.article]["livrer"]=parseInt(item.value);
    cartItems[item.dataset.article]["pu"]=parseFloat(item.dataset.pu);
  })
  var sum_remise=0;
  var sum_montant=0;
  for (const key in cartItems) {
      const item = cartItems[key];
      sum_remise+=item["total_remise"];
      sum_montant+=item["sous_total"];
      let tr=document.createElement("tr");
      let ref=document.createElement("td");
      ref.textContent=item["code"];
      let pu=document.createElement("td");
      pu.textContent=item["pu"].toLocaleString("fr-FR", {minimumFractionDigits:2});
      let qty=document.createElement("td");
      qty.textContent=parseInt(item["quantity"]);
      let total_rem=document.createElement("td");
      total_rem.textContent=item["total_remise"].toLocaleString("fr-FR", {minimumFractionDigits:2});
      let montant=document.createElement("td");
      montant.textContent=item["sous_total"].toLocaleString("fr-FR", {minimumFractionDigits:2});
      let liv=document.createElement("td");
      liv.textContent=item["livrer"];
      tr.appendChild(ref);
      tr.appendChild(pu);
      tr.appendChild(qty);
      tr.appendChild(total_rem);
      tr.appendChild(montant);
      tr.appendChild(liv);
      commande_body.appendChild(tr);


    }
    let total_row=document.createElement("tr");
    let label=document.createElement("td");
    label.colSpan=3;
    label.textContent="TOTAL";
    let td_remises=document.createElement("td");
    td_remises.textContent=sum_remise.toLocaleString("fr-FR", {minimumFractionDigits:2});
    let td_montant=document.createElement("td");
    td_montant.textContent=sum_montant.toLocaleString("fr-FR", {minimumFractionDigits:2});
    td_montant.classList='bg-warning';
    total_row.appendChild(label);
    total_row.appendChild(td_remises);
    total_row.appendChild(td_montant);
    commande_body.appendChild(total_row);

}

function detail_reglement(){
  const reglement_body=document.getElementById("reglement_body");
  reglement_body.innerHTML=""
  const mainForm=document.getElementById("cartForm");
  const montant=parseFloat(mainForm.montant.value);
  const mode=mainForm.mode;
  const caisse=mainForm.caisse;
  const select_caisse=caisse.options[caisse.selectedIndex].textContent;
  const select_mode=mode.options[mode.selectedIndex].textContent;
  const reg={"MONTANT REGLE":montant.toLocaleString("fr-FR", {minimumFractionDigits:2}),"MODE DE PAIMENT":select_mode, "CAISSE":select_caisse}
  for(let index in reg){
    let ul=document.createElement("ul");
    ul.classList="list-group"
    let li_montant=document.createElement("li");
    li_montant.classList="list-group-item d-flex justify-content-between";
    let span_montant=document.createElement("span");
    span_montant.textContent=index;
    let strong_montant=document.createElement("strong");
    strong_montant.textContent=reg[index];
    li_montant.appendChild(span_montant);
    li_montant.appendChild(strong_montant);
    ul.appendChild(li_montant);
    reglement_body.appendChild(ul);
  }
  
}


function show_confirmation(){
     const mainForm=document.getElementById("cartForm");
     var client_name;
     var client_phone;

     const client_select=mainForm.client;
     if(client_select.value!=="0"){
        let selected=client_select.options[client_select.selectedIndex];
        client_name=selected.dataset.name;
        client_phone=selected.dataset.phone;
     }else{
      client_name=mainForm.nom.value;
      client_phone=mainForm.phone.value
     }
     detail_client(client_name,client_phone);
     panier_livrer();
     detail_reglement();




}
</script>
{% endblock %}