{% extends "base_frontoffice.html" %}

{% block content %}



<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center">
        <h4>Liste des commandes clients</h4>
    </div>
    <input type="text " id="tableSearch" class="form-control mb-3 w-50" placeholder="Rechercher un article..." >
    <!-- Article Table -->
    <div class="table-responsive mt-4">
        <table class="table table-sm align-items-center justify-content-center mb-0" id="commandeTable">
            <thead class="table-light">
                <tr>
                    <th>Numéro</th>
                    <th>Date Comm</th>
                    <th>Client code</th>
                    <th>Client nom</th>
                    <th>Net à payer</th>
                    <th>Status</th>
                    <th>Livraison</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                {% for commande in all_commande %}
                <tr data-id="{{commande.id}}">
                    <td>{{ commande.numero }}</td>
                    <td>{{ commande.date_str }}</td>
                    <td>{{ commande.client.code }}</td>
                    <td>{{ commande.client.nom }}</td>
                    <td class="money">{{ commande.net_payer_str }}</td>
                    <td >{{ commande.montant_paye[2] }}</td>
                    <td>{{ commande.taux_livraison() }}</td>
                    <td>
                        <span class="d-flex">
                        <button class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#detailModal" onclick="show_detail('{{commande.id}}')">Detail</button>
                        {% if commande.montant_paye[2]!="REGLEE" %}
                        <button class="btn btn-warning btn-sm mx-1" data-bs-toggle="modal" data-bs-target="#reglerModal" onclick="reglement('{{commande.id}}')" >Régler</button>
                        {% endif %}
                        {% if commande.taux_livraison()!="100% LIVRE" %}
                        <button class="btn btn-primary btn-sm mx-1" data-bs-toggle="modal" data-bs-target="#livrerModal" onclick="livraison('{{commande.id}}')">Livrer</button>
                        {% endif %}
                        <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#impressionModal" onclick="impression('{{commande.id}}')">IMPRESSION</button>
                    </span>
                    </td>
                </tr>
              
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
<!-- Modal Form -->
<div class="modal fade" id="detailModal" tabindex="-1" aria-labelledby="cancelLabel" >
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="cancelLabel">DETAIL COMMANDE</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>

      <div class="modal-body" >
        <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-white" >DATE COMMANDE</span>
            <input type="date"  class="form-control px-2"  id="detail_date"  disabled />
        </div>
        <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-white" >NUMERO</span>
            <input type="text"  class="form-control px-2"  id="detail_numero"  disabled />
        </div>
        <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-white" >CLIENT</span>
            <input type="text"  class="form-control px-2 w-50"  id="detail_client_nom" disabled  />
            <input type="text"  class="form-control px-2"  id="detail_client_code" disabled  />
        </div>
        
        <div class="table-responsive mt-1">
        <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>Livré</th>
                </tr>
            </thead>
            <tbody id="body_detail">
             </tbody>
        </table> 
        </div> 
        <ul class="list-group mb-3" id="cart-items">
            <li class="list-group-item d-flex justify-content-between">
              <span >TOTAL REMISE</span>
              <strong id="remise">0</strong>
            </li>
            <li class="list-group-item d-flex justify-content-between">
              <span >NET A PAYER</span>
              <strong id="net_payer">0</strong>
            </li>
        </ul>
        <hr>
        <h5 class="modal-title" >REGLEMENT</h5>
        <ul class="list-group mb-3" id="reg_item">
            
        </ul>
        <hr>
        <li class="list-group-item d-flex justify-content-between bg-warning p-1">
            <span>RESTE A PAYER</span><strong id="reste"></strong></li>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">FERMER</button>
      </div>
    </div>
  </div>
</div>
</div>

<div class="modal fade" id="reglerModal" tabindex="-1" aria-labelledby="cancelLabel" >
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="cancelLabel">REGLEMENT COMMANDE</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <form method="POST" action="#" id='regForm'>
      <div class="modal-body" >
        <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-white" >DATE REGLEMENT</span>
            <input type="date"  class="form-control px-2" name="date" required />
        </div>
        <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-white" >MONTANT</span>
            <input type="number" min="0" step='0.01' id="moneyInput" class="form-control px-2" name="montant" required autocomplete="off" />
        </div>
        <div id="moneyInWords" class="form-text mt-2"></div>
        <div class="input-group mb-1">
            <span class="input-group-text bg-secondary text-white" >MODE DE PAIEMENT</span>
            <input type="text"  class="form-control px-2" name="mode"  required/>
        </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>
        
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">FERMER</button>
        <button type="submit" class="btn btn-danger">ENREGISTRER</button>
      </div>
    </div>
    </form>
  </div>
</div>
</div>
<div class="modal fade" id="impressionModal" tabindex="-1" aria-labelledby="cancelLabel" >
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="cancelLabel">IMPRESSION DOCUMENT</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>

      <div class="modal-body" >
        <h5 class="modal-title" >FACTURE</h5>
        <ul class="list-group mb-3" id="facture-items">
            <li class="list-group-item d-flex justify-content-between">
              <span >N°FACTURE</span>
              <a class="btn btn-outline-primary btn-sm" href="#" onclick="ajax_print('/rawbt-receipt?id=1', this)">IMPRIMER</a>
            </li>
        </ul>
        <hr>
        <h5 class="modal-title" >RECU DE PAIEMENT</h5>
        <ul class="list-group mb-3" id="recu-items">
            <li class="list-group-item d-flex justify-content-between">
              <span >TOTAL REMISE</span>
              <strong id="remise">0</strong>
            </li>
        </ul>
        <hr>
        <h5 class="modal-title" >LIVRAISON</h5>
        <ul class="list-group mb-3" id="livraison-items">
            <li class="list-group-item d-flex justify-content-between">
              <span >TOTAL REMISE</span>
              <strong id="remise">0</strong>
            </li>
        </ul>
        <hr>
        
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">FERMER</button>
      </div>
    </div>

  </div>
</div>
</div>
<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 = '';
    }
  });




document.getElementById("tableSearch").addEventListener("keyup", function () {
  const input = this.value.toLowerCase();
  const rows = document.querySelectorAll("#commandeTable tbody tr");

  rows.forEach(row => {
    const rowText = row.innerText.toLowerCase();
    row.style.display = rowText.includes(input) ? "" : "none";
  });
});
</script>
<script>
  window.onload=function(){
    var all_number =$(".money");
    for (let number of all_number){
      number.textContent=parseFloat(number.textContent).toLocaleString("fr-FR", {minimumFractionDigits:2});
    };
};

function reglement(id){
    let regForm=document.getElementById("regForm");
    regForm.action='/reglement/add?id='+id;
}

function show_detail(id) {
    let detail_date=document.getElementById("detail_date");
    detail_date.value="";
    let detail_client_nom=document.getElementById("detail_client_nom");
    detail_client_nom.value="";
    let detail_client_code=document.getElementById("detail_client_code");
    detail_client_code.value="";
    let detail_numero=document.getElementById("detail_numero");
    detail_numero.value="";
    let remise=document.getElementById("remise");
    remise.textContent="";
    let net_payer=document.getElementById("net_payer");
    net_payer.textContent="";
    let body_detail=document.getElementById("body_detail");
    body_detail.innerHTML="";
    let reg_item=document.getElementById("reg_item");
    reg_item.innerHTML='';
    let reste=document.getElementById("reste");
    reste.textContent='';
    fetch("/json/commande?id="+id, {
      method: "GET",
    })
    .then(res => res.json())
    .then(data => {
      detail_client_code.value=data["client_code"];
      detail_client_nom.value=data["client_nom"];
      detail_numero.value=data["numero"];
      detail_date.value=data["date"];
      remise.textContent=parseFloat(data["total_remise"]).toLocaleString("fr-FR",{minimumFractionDigits:2});
      net_payer.textContent=parseFloat(data["net_payer"]).toLocaleString("fr-FR",{minimumFractionDigits:2});
      reste.textContent=parseFloat(data["reste"]).toLocaleString("fr-FR",{minimumFractionDigits:2});
      for(let detail of data["detail"]){
          let tr_row=document.createElement("tr");
          let ref_td=document.createElement("td");
          ref_td.textContent=detail["article_code"];
          let prix_td=document.createElement("td");
          prix_td.textContent=parseFloat(detail["pu"]).toLocaleString("fr-FR", {minimumFractionDigits:2});
          let qty_td=document.createElement("td");
          qty_td.textContent=detail["quantite"];
          let livre_td=document.createElement("td");
          livre_td.textContent=detail["livre"];
          let rem_td=document.createElement("td");
          rem_td.textContent=detail["remise"];
          let montant_td=document.createElement("td");
          montant_td.textContent=parseFloat(detail["sous_total"]).toLocaleString("fr-FR", {minimumFractionDigits:2});
          tr_row.appendChild(ref_td);
          tr_row.appendChild(prix_td);
          tr_row.appendChild(qty_td);
          tr_row.appendChild(rem_td);
          tr_row.appendChild(montant_td);
          tr_row.appendChild(livre_td);
          body_detail.appendChild(tr_row);
      }

      for(let reg of data["reglement"]){
        let li=document.createElement("li");
        li.classList="list-group-item d-flex justify-content-between";
        let span=document.createElement("span");
        span.textContent=reg["date"]+" ("+reg["mode"]+")";
        li.appendChild(span);
        let strong=document.createElement("strong");
        strong.textContent=parseFloat(reg["montant"]).toLocaleString("fr-FR", {minimumFractionDigits:2});
        li.appendChild(strong);
        reg_item.appendChild(li);
     }


    })
    .catch(err => {
      console.error(" failed:", err);
    });
}


function impression(id) {
    let facture=document.getElementById("facture-items");
    facture.innerHTML="";
    let livraison=document.getElementById("livraison-items");
    livraison.innerHTML="";
    let recu=document.getElementById("recu-items");
    recu.innerHTML="";

    fetch("/json/impression?id="+id, {
      method: "GET",
    })
    .then(res => res.json())
    .then(data => {
      detail_client_code.value=data["client_code"];
      let f_li=document.createElement("li");
      f_li.classList="list-group-item d-flex justify-content-between";
      f_span=document.createElement("span");
      f_span.textContent=data["numero"];
      f_a=document.createElement("a");
      f_a.classList="btn btn-outline-primary btn-sm";
      f_a.addEventListener('click', function() {
    ajax_print('/rawbt-receipt?id='+id, this);
});
      f_a.textContent="IMPRIMER";
      f_li.appendChild(f_span);
      f_li.appendChild(f_a);
      facture.appendChild(f_li);

      let list_liv=data["livraison"];
      for(let key of list_liv){
        let l_li=document.createElement("li");
          l_li.classList="list-group-item d-flex justify-content-between";
          l_span=document.createElement("span");
          l_span.textContent=key;
          l_a=document.createElement("a");
          l_a.classList="btn btn-outline-primary btn-sm";
          l_a.addEventListener('click', function() {
        ajax_print('/rawbt-livraison?id='+id, this);});
          l_a.textContent="IMPRIMER";
          l_li.appendChild(l_span);
          l_li.appendChild(l_a);
          livraison.appendChild(l_li);
      };
      let list_reg=data["reglement"];
      for(let key of list_reg){
        for(let index in key){
             let l_li=document.createElement("li");
              l_li.classList="list-group-item d-flex justify-content-between";
              l_span=document.createElement("span");
              l_span.textContent=index;
              l_a=document.createElement("a");
              l_a.classList="btn btn-outline-primary btn-sm";
              l_a.addEventListener('click', function() {
            ajax_print('/rawbt-reglement?id='+key[index], this);});
              l_a.textContent="IMPRIMER";
              l_li.appendChild(l_span);
              l_li.appendChild(l_a);
              recu.appendChild(l_li);
        }
      };


    })
    .catch(err => {
      console.error(" failed:", err);
    });
}
</script>



<script>
function pc_print(data){
alert("ONLY ON A BLUETOOTH ANDROID PRINTER");
}       


function android_print(data){
            window.location.href = data; 
        }

// for php demo call
function ajax_print(url, btn) {
    console.log(btn);
    b = $(btn);
    b.attr('data-old', b.text());
    b.text('wait');
    $.get(url, function (data) {
    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
    if(isAndroid) {
        android_print(data);
    }else{
        pc_print(data);
    }
        }).fail(function () {
            alert("ajax error");
        }).always(function () {
            b.text(b.attr('data-old'));
        })
    }


</script>
{% endblock %}