{% extends './solds.html' %}
{% load static %}
{% block style %}
<style>
  .adders_form{
    cursor: pointer;
  }
  #giveLoveModal{
    z-index:999999 !important; 
}

</style>
{% endblock %}
{% block role_user %}<span>{{role}}</span>{% endblock %}




{% block content %}

<div class="container-fluid">
  <div class="row">
    <div class="col-md-12">
      <div class="" style="padding:0px;">
        <div  class="card-header card-header-success">
          <h4 class="card-title d-flex justify-content-between"> 
          <div> Ventes Realisees par <b> {{actual_institution}}</b><div><small class="text-primary2"> Personnel : {{user.first_name}}&nbsp;{{user.last_name}} </small></div> </div>
          <div class='px-2'> <div><span class="btn btn-primary2" id='loaderMOD' data-toggle="modal" data-target="#giveLoveModal"> + Ajouter </span></div> </div>          
          </h4>
          <form method="POST" action="/stock/search/" class="navbar-form">{% csrf_token %}
					<div class="input-group no-border"> 
						<input type="text" name="search" class="form-control"  placeholder="Rechercher une Facture" >
						<button type="submit" class="btn btn-white btn-round btn-just-icon">
							<i class="material-icons">search</i>
							<div class="ripple-container"></div>
						</button>
					</div>
	  </form>
          
        </div>
        <div class="card-body">
          <div class=" table-responsive">
            <table class="table">
              <thead class=" text-primary2">
                <th>
                 Code
                </th>
                <th>
                  Date
                </th>                
                <th>
                  Montant
                </th>
                <th>
                  Commercial
                </th>
                <th>
                  Client
                </th>
                <th>

                </th>
              </thead>
              <tbody id='containt_body'>
                {% for t in trans %}
                <tr>
                  <td data-id='{{t.id}}' onclick='get_facture(this)' class="text-primary2" data-toggle='modal' data-target='#FactureTModal' style="cursor: pointer;">
                    {{t.m_code}}
                  </td>
                  <td>
                    {{t.m_date}}
                  </td>
                  <td>
                    {{t.montant}} XAF
                  </td>
                  <td>
                    {{t.m_staff}}
                  </td>
                  <td class="text-secondary">
                    {{t.client}}
                  </td>
                  <td data-id="{{t.m_code}}" style="cursor: pointer;" data-toggle='modal' data-target="#articlesTModal" class="articles_laun text-primary2">
                    Articles
                  </td>
                </tr>
                {% empty %}
                <tr>
                  <td colspan="7"> L'Etablissement n'a aencore enregistre aucune Vente </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <!-- ========== Give a Like Modal ======= -->
    <div class="modal  fade" id="giveLoveModal"  role="dialog" > 
      <div class="modal-dialog modal-lg" role="document">
       <div class="modal-content">
        <div class="modal-header bg-white">
          <h6 class="modal-title" style="font-family:Ubuntu;"> Nouvelle Transaction </h6>
          <button type="button" class="text-danger close" data-dismiss="modal" aria-label="Close" id="giLoClose"><span aria-hidden="true">&times;</span></button>

        </div>

        <div class="d-flex pl-3">
          <div>
            <span class="badge btn-primary2 text-white"> Vente </span>
          </div>
          <!--
          <div>
            <span class="badge"> Achat </span>
          </div>
          -->
        </div>
        <div id="connec-text" style="background:none;" class="modal-body">

         <div style="padding-top:2px;display:flex;">
          <div class="input-group mb-3">
            <div style="display: flex;width: 100%;">
              <div style="">
                <input type="checkbox" class="checker_client" name="">
                <label style="color:#999;" class="checker_client"> Client de la Maison</label>
              </div>
            </div>


              <div style="display: none;" id="clientInter" class="py-3">
                <div class="d-flex">
                  <div><label class="text-primary2"> Code du Client </label></div>
                </div>
                <div><input type="text" id="code_client" class="form-control border" name=""></div>
                <div class="d-flex">
                  <div class=""><span class="badge badge-primary codeClientSeer"> Chercher le Code du Client </span></div>
                </div>
                <!-- Client Searching INterface -->
                <div style="display: none;" id="clientCodeSearch">
                  <div class="px-3"><span class="codesrchcls badge badge-danger text-white"> <span class="fa fa-times"> X</span> </span></div>
                  <div class="d-flex">
                    <div class="p-3">
                      <label> Nom du Client </label>
                      <input type="" name="" class="search-client-nom form-control">
                    </div>
                    <div class="p-3">
                      <label> Prenom du Client </label>
                      <input type="" name="" class="search-client-nom form-control">
                    </div>
                    <div class="p-3">
                      <label> Telephone Client </label>
                      <input type="" name="" class="search-client-nom form-control">
                    </div>
                  </div>
                  <div>
                    <span class="btn" onclick="ajax_search_client()"> Obtenir le Code </span>
                  </div>
                  <div>
                    <table style="display:none;max-height:160px;overflow-y: auto;" id="clientCodeTable" class="table">
                      <thead>
                        <tr>
                          <th>
                            <small>Code Client</small>
                          </th>
                          <th>
                            <small>Nom Client</small>
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        
                      </tbody>
                    </table>
                  </div>
                </div>
                <!-- -->

              </div>

            <div style="width:100%;max-height:300px ;overflow: auto;">
              <table style="width:100%;" class="table table-bordered table-responsive table-stripped">
                <thead>
                  <tr>
                    <th style="min-width:50px;width:5% ;">&nbsp;</th>
                    <th style="min-width:90px;width:20% ;"><small>Code</small></th>
                    <th style="min-width:250px;width:45% ;"><small>Produit</small></th>
                    <th style="min-width:50px;width:5% ;"><small>Quantite</small></th>
                    <th style="min-width:90px;width:20% ;"><small>Prix Unitaire</small></th>
                    <th style="min-width:90px;width:20% ;"><small>Montant</small></th>
                    <th style="min-width:90px;width:20% ;"><small>Total</small></th>
                    
                    {% if setings.price_}
                  </tr>
                </thead>
                <tbody>
                  {% for tr in tr_row1 %}
                  <tr class="product_line">
                    <td><small>{{forloop.counter}}</small></td>
                    <td class="code_cell" data-line="{{forloop.counter}}" contenteditable="true"></td>
                    <td style="padding: 0px;" class="value_cell" data-line="{{forloop.counter}}">
                      <div style="padding: 0px;">
                        <select class="form-controls" data-line="{{forloop.counter}}" style="width: 100%;height: 100%;background:none;border: none;margin: 0px;padding: 0px;">
                          <option value=""></option>
                          {% for product in products %}
                          <option value="{{product.m_code}}">{{product.m_name}} </option>
                          {% endfor %}
                        </select>
                      </div>
                    </td>
                    <td class="qte_cell" data-line="{{forloop.counter}}" contenteditable="true"></td>
                    <td class="prix_cell" data-line="{{forloop.counter}}" contenteditable="true"><span class="prix_cell_value"></span></td>

                  </tr>
                  {% endfor %}
                </tbody>
              </table>
            </div>

            <form  action="#" method="POST"> 
            </form>


            <div style="width:100%;">
              <!-- <div class=''>
                <small class="adders_form text-success"><i class="fa fa-plus"></i> Ajouter une Ligne </small>
              </div> -->
              <div style="display: flex;justify-content: space-between;flex-wrap: wrap;">
                <div>
                  <span class="btn btn-white text-primary2"> Montant Perçu</span>
                  <input style="border-radius:0%;border:none;background:#fff;color:#333;" id='koi_per' class="btn" type="number" min=0 >
                </div>
                <div>
                  <span class="btn btn-white text-primary2"> Rembourser </span>
                  <span style="border-radius:0%;border:none;background:#fff;color:#333;" id='koi_remb' class="btn" type="number" min=0 >0 XAF</span>
                </div>
              </div>

              
            </div>
          </div>

        </div>
      </div>
      <div id="form_desc" style="width:100%;display:none;">
        <p style="text-align:center;">
          <span class="btn" style="color:#333;background:#fff;text-align:center;">Enregistrement de La Facture</span>
        </p>
      </div>
      <div style="d">

        <div class="log-description w-100 modal-footer d-flex flex-wrap" style="text-align:center;">
          <div class='' style="width:100%;display:flex;">
            <div class="btn btn-success" style="">Facture</div>
            <div id='rst_fac' style="font-weight:bold;background:#fff;color:#333;" class="btn" data-value="0">0 XAF</div>
          </div>
          <div style='text-align: center;'> <span id='enreg_trans' class="btn btn-primary2"> Enregistrer la Facture </span> </div>
        </div>
      </div>
    </div>
  </div>
</div>
    <!-- ========== Give a Like Modal ======= -->

    <!-- ========== Articles T Modal ======== -->
    <div class="modal fade" id="articlesTModal"  role="dialog" > 
      <div class="modal-dialog modal-lg" role="document">
       <div class="modal-content">
        <div class="modal-header bg-primary text-white">
          <h6 class="modal-title" style="font-family:Ubuntu;"> Articles de la Transaction </h6>
          <button type="button" class="text-danger close" data-dismiss="modal" aria-label="Close" id="giLoClose"><span aria-hidden="true">&times;</span></button>

        </div>

        <div  style="background:none;" class="modal-body">
          <table class="table table-stripped">
            <thead>
              <th><small>Code</small></th>
              <th><small>Libellé</small></th>
              <th><small>Prix</small></th>
              <th><small>Qte</small></th>
            </thead>
            <tbody id="produ_tra_body">
              
            </tbody>
          </table>
        </div>
      </div>
    </div>
    </div>
    <!-- ========== Articles T Modal ======== -->

    <!-- ========== Facture Modal ======== -->
    <div class="modal fade" id="FactureTModal"  role="dialog" > 
      <div class="modal-dialog modal-lg" role="document">
       <div class="modal-content">
        <div class="modal-header">
          <h6 class="modal-title" style="font-family:Ubuntu;"> Aperçu de la facture </h6>
          <button type="button" class="text-danger close" data-dismiss="modal" aria-label="Close" id="giLoClose"><span aria-hidden="true">&times;</span></button>

        </div>

        <div  style="background:none;" class="modal-body">
          <div class="border border-secondar border-radius">
            <div id='facture-ajax'>
              <!-- Entete Facture -->


              <!-- Entete Facture -->
            </div>
          </div>
        </div>
      </div>
    </div>
    </div>
    <!-- ========== Facture Modal ======== -->

</div>

{% endblock %}
{% block script %}
<script>

//articles_

// CLearer =================
$("select").val("")
  $(".articles_laun").click(function(){
   code =$(this).attr("data-id");
      $.ajax({
      url: '/ajax/get_transaction/',
      data: {
        'code':code, 
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        produ_tra_body = document.getElementById("produ_tra_body");
        tmp = "";
        for (var i=0;i<data.products_name.length; i++){
          tmp += "<tr>";

          tmp += "<td>"+data.products_code[i]+"</td>";
          tmp += "<td>"+data.products_name[i]+"</td>";
          tmp += "<td> <span contenteditable='true'>"+data.products_prix[i]+"</span> FCFA </td>";
          tmp += "<td>"+data.products_qte[i]+"</td>";
          tmp += "</tr>"
        }
        produ_tra_body.innerHTML = tmp;
        //$(".prix_cell:eq("+index+")").text(price+ " FCFA");
        //$("#eltA"+elt).html("<span>"+data.name+"</span>");
      }
    });
  })

  $(".code_cell").keyup(function(){
    index =  parseInt($(this).attr("data-line"));
    code = $(this).text()
    //$(".value_cell").text("");
    //$(".value_cell:eq("+index+")").text("Recupération de l'Article");
    getproduct_code(code,index)
  })

  $(".value_cell select").change(function(){
    //alert("sdsds");
    index =  parseInt($(this).attr("data-line"))-1;
    code = $(this).val();
    $(".code_cell:eq("+(index)+")").text(code)
    getproduct_code(code)
  })


  $(".qte_cell").keyup(function(){
    index =  parseInt($(this).attr("data-line")) - 1;
    qte =  parseInt($(this).text())
    updateproduct_price(qte,index)
    totalsomme();
  })

  function updateproduct_price(qte,index)
  {
    price = $(".prix_cell:eq("+index+")").attr("data-price");
    update = qte * parseFloat(price) + " FCFA";
    $(".prix_cell:eq("+index+")").text(update);
  }

  function getproduct_code(code,elt)
  {
    $.ajax({
      url: '/ajax/get_product/',
      data: {
        'code':code, 
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        $(".value_cell:eq("+index+")").find( "select" ).val(data.code);
        price = data.price;
        $(".prix_cell:eq("+index+")").attr("data-price",price);
        //$(".prix_cell:eq("+index+")").text(price+ " FCFA");
        //$("#eltA"+elt).html("<span>"+data.name+"</span>");
      }
    });
  }

    function getproduct_code_by_name(name,elt)
  {
    $.ajax({
      url: '/ajax/get_product/',
      data: {
        'name':name, 
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        $(".value_cell:eq("+index+")").text(data.name);
        price = data.price
        $(".prix_cell:eq("+index+")").attr("data-price",price);
      }
    });
  }

  function getproduct_price(code,elt,num=1)
  {
    $.ajax({
      url: '/ajax/get_product/',
      data: {
        'code':code, 
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        var rst = num*data.price;
        $("#eltB"+elt).attr('data-val',rst);
        $("#eltB"+elt).html("<span>"+rst+" XAF</span>");
        $('#rst_fac').html(totalsomme()+" XAF")
      }
    });
  } 

  function gettransaction_articles(code)
  {
    $.ajax({
      url: '/ajax/get_transaction/',
      data: {
        'code':code, 
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        $(".value_cell:eq("+index+")").text(data.name);
        price = data.price;
        $(".prix_cell:eq("+index+")").attr("data-price",price);
      }
    });    
  }

  function totalsomme(){
    var rst_fac = document.getElementById('rst_fac');
    var product_lines = document.getElementsByClassName("product_line");
    var rst = 0;
    for (var i=0;i<product_lines.length;i++){
      qte_cell = product_lines[i].getElementsByClassName("qte_cell")[0].textContent;
      prix_cell = product_lines[i].getElementsByClassName("prix_cell")[0].getAttribute("data-price");
      //alert(qte_cell)
      //alert(prix_cell)
      if (qte_cell == "" && prix_cell == null){
        value = 0;
      }
      else{
        value = parseInt(qte_cell)*parseInt(prix_cell);  
      }
      
      rst += value;
    }
    rst_fac.textContent = rst + " FCFA" 
    return rst;
  }

  function save_trans(){
    codes_val = document.getElementsByClassName('code_cell');
    nums_val = document.getElementsByClassName('qte_cell');
    nb_pa = codes_val.length;
    str_code ="";
    str_num = "";
    for (i=0; i<nb_pa; i++){
      str_code += codes_val[i].textContent+"#";
      str_num += nums_val[i].textContent+"#";
    }

    // Check if Client saved
    if ( $("#checker_client").attr("checked") == true ){
      client_saved = $("#code_client").val();
    }
    else{
      client_saved = "#";
    }

    $.ajax({
      url: '/ajax/save_trans/',
      data: {
        'nb_pa':nb_pa, 
        'codes':str_code,
        'nums':str_num,
        'client':client_saved,
        'staff':"{{user.username}}"
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        if (data.success){
          $('#form_desc').html("<p style='text-align:center;'><span class='text-success' >La transaction a éte enrégistrée avec succès </span></p><p style='text-align:center;'> <span class='btn text-dark facture_printing' style='background:#fff;' >Impréssion de la Facture ...</span> </p>");
          cont = document.getElementById("containt_body");
          cont.innerHTML = "<tr><td data-id='" +data.id+ "' onclick='get_facture(this)' class='text-primary2' data-toggle='modal' data-target='#FactureTModal' style='cursor: pointer;'>" +data.code+ "</td><td>" +data.date+"</td><td>" +data.montant+ " XAF </td><td>"+data.sens+"</td><td class='text-secondary'>"+data.client+"</td><td class='text-primary2' data-id='"+data.id+ "' style='cursor: pointer;' data-toggle='modal' data-target='#articlesTModal' class='articles_laun text-primary2'>Articles</td></tr>'" + cont.innerHTML;
          clean_form();
        }
      }
    });
  }
  // Launchers
  num_line=1;
  $(".adders_form").click(function(){
    var form_saler = document.getElementById('form_saler');
    var node = document.createElement("div");
    //form_saler.innerHTML
    inputA = "<input list='browsers"+(num_line)+"' id='epa"+(num_line)+"' class='d-block code_val btn btn-outline-success'   data-el="+(num_line)+" min=0 placeholder='Entrez le Code'>"+"<datalist id='browsers"+(num_line)+"'>{% for p in products %}<option value='{{p.m_code}}'>{{p.m_name}}</option>{% endfor %}</datalist>"

    node.innerHTML = "<div style='width:100%; justify-content:center;' class='d-flex'><div class='input-group-append d-flex flex-wrap'>"+inputA+"<input style='border-radius:0%;border:none;background:#fff;color:#333;' id='epb"+(num_line)+"' class='d-block num_val btn' type='number' data-el="+num_line+" data-val=1  min=0 placeholder='Quantité'></div></div><div style='display: flex;justify-content: space-between;'><div id='eltA"+num_line+"' style='font-size:12px;font-weight:bold;' class='elt_add'></div><div id='eltB"+num_line+"' style='font-size:12px;font-weight:bold;' class='somB elt_add'></div></div>";
    form_saler.appendChild(node);
    num_line++;
    update_launchers();

  });
  function clean_form(){
    input = document.getElementById("giveLoveModal").getElementsByTagName("input");
    l1 = input.length;
    elt = document.getElementsByClassName('elt_add');
    l2 = elt.length;
    for (var i=0; i<l1; i++){
      input[i].value = "";
    }
    for (var i=0; i<l2; i++){
      elt[i].textContent = "";
    }
    $("#koi_remb").html("0 XAF ");
    $("#rst_fac").html("0 XAF ");
  }

  function update_launchers(){
    $(".code_val").blur(function(){
      var data_el = $(this).attr('data-el');
      $("#eltA"+data_el).html("Recupération de l'Article");
      getproduct_code($(this).val(),data_el);
    });
    $(".num_val").blur(function(){
      var data_el = $(this).attr('data-el');
      var code = $("#epa"+data_el).val();
      var num = $(this).val();
      getproduct_price(code,data_el,num);
    });
  }
  $("#koi_per").blur(function(){
    var som = totalsomme();
    $("#koi_remb").html(($(this).val()-som)+" XAF");
  });

  $("#enreg_trans").click(function(){
    var product_lines = document.getElementsByClassName("product_line");
    
    // Check if not empty
    to_submit = false;
    for ( line of product_lines ){
    	code_cell = line.getElementsByClassName("code_cell");
    	qte_cell = line.getElementsByClassName("qte_cell"); 
    	if (code_cell[0].textContent.trim() != "" && qte_cell[0].textContent.trim() != ""){
    		to_submit = true;
    		break;
    	}
    }

    
    if (to_submit){
    $("#connec-text").slideUp('slow',function(){
      $("#form_desc").slideDown('slow');
    });
    save_trans();
    }
    else{
    	alertify.error("Renseigner une Ligne");
    }
    
  })


  $("#loaderMOD").click(function(){
    $("#form_desc").slideUp('slow',function(){
      $("#connec-text").slideDown('slow');
    });    
  })

  $(".codesrchcls").click(function(){ $("#clientCodeSearch").hide("slow"); });
  
  update_launchers();
  function update_date(){
    months = ["Janvier","Fvrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre"]
    date = new Date()
    date = date.getDate() + " " +months[date.getMonth()]+ " "+ date.getFullYear() 
    $(".date_valer").text(date)    
  }
  
  function get_facture(id_facture=null){
    if ( id_facture != null ){
        id_facture = id_facture.getAttribute('data-id');
    }
  
    $.ajax({
      url: '/ajax/get_facture/',
      data: {
        'id_facture':id_facture,
      },
      async:true,
      dataType: 'json',
      success: function (data) {
    	facture_ajax = document.getElementById("facture-ajax");
	    facture_ajax.innerHTML = data.facture;
      }
    });
  }
  
  update_date();

  checker_client = document.getElementsByClassName("checker_client");
  checker_client[0].onclick = function(){
    if (this.checked == true){
      $("#clientInter").slideDown('slow')
    }
    else{
      $("#clientInter").slideUp('slow')      
    }
  }

  $(".codeClientSeer").click(function(){
    $("#clientCodeSearch").show("slow")
  });

  function ajax_search_client(){
    nom = document.getElementsByClassName("search-client-nom")[0].value
    prenom =  document.getElementsByClassName("search-client-nom")[1].value
    tel =  document.getElementsByClassName("search-client-nom")[2].value

    $.ajax({
      url: '/ajax/search_client/',
      data: {
        'nom':nom.trim(),
        'prenom':prenom.trim(),
        'tel':tel.trim()
      },
      async:true,
      dataType: 'json',
      success: function (data) {
        console.log(data.result)
        $("#clientCodeTable").show('slow');
        $("#code_client").val(data.result[0]["m_code"]);
        var tablebody = document.getElementById("clientCodeTable").getElementsByTagName("tbody")[0];
        var tmp = "";
        for (var i=0;i<data.result.length;i++){
          tmp += "<tr> <td><small class='text-primary2' onclick=update_code('"+data.result[i]["m_code"]+"')>"+data.result[i]["m_code"]+"</small> </td> <td><small>"+data.result[i]["m_name"]+"</small></td> </tr>";
        }
        tablebody.innerHTML = tmp;
      }
    });

  }

  function update_code(code){
    $("#code_client").val(code);
  }

  //get_facture();
</script>
{% endblock %}
