<?php include_once PUBLIC_PATH. '/files_to_include/header_content.php'; ?>
<div class="main-content-wrap sidenav-open d-flex flex-column">
            <!-- ============ Body content start ============= -->
            <div class="main-content">
                
                <div class="modal fade see-modal-lg" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalCenterTitle">CONSOMMABLE/REACTIFS</h5>
                                <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            </div>
                            
                            <div class="modal-body">
                               <div class="form-group col-lg-12 col-md-12 col-xs-12">
                                            <label>EMPLACEMENT</label><label style="color : red;">&nbsp; * &nbsp;</label>
                                            <input  type="text" id="empVue" placeholder="EMPLACEMENTS" class="form-control " readonly="" />
                                </div>
                                    <div id="tableFourniture">
                                        <table class="table table-bordered">
                                            <thead >
                                                <tr>
                                                    <th>Consommable</th>
                                                    <th>Quantite</th>
                                                    <th class="action">Date Approvisionnement</th>
                                                </tr>
                                            </thead>
                                            <tbody id="seeFourniture">
                                                
                                               
                                            </tbody>

                                            <tfoot >
                                                 <tr>
                                                    <th>Consommable</th>
                                                    <th>Quantite</th>
                                                    <th class="action">Date Approvisionnement</th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                   
                                    <br/>

                            </div>
                           
                        </div>
                    </div>
                </div>
                
                 <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalCenterTitle">CONSOMMABLE/REACTIFS</h5>
                                <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            </div>
                            
                            <div class="modal-body">
                              
                                    
                                    <div class="row" id="partieMouvement">
                                        <div class="form-group col-lg-12 col-md-12 col-xs-12">
                                            <label>EMPLACEMENT</label><label style="color : red;">&nbsp; * &nbsp;</label>
                                            <input  type="text" id="emplacement" placeholder="EMPLACEMENTS" class="form-control " />
                                            <input type="hidden" value="" id="idemp"/>
                                        </div>
                                       
                                         <div class="form-group col-lg-7 col-md-7 col-xs-7">
                                            <label>Consommables</label><label style="color : red;">&nbsp; * &nbsp;</label>
                                            <input  type="text" id="consommable" placeholder="Consommables/Reactifs" class="form-control " />
                                            <input type="hidden" value="" id="idconso"/>
                                            <input type="hidden" value="" id="sujetEdition"/>
                                        </div>
                                        <div class="form-group col-lg-3 col-md-3 col-xs-3">
                                            <label>Quantite</label><label style="color : red;">&nbsp; * &nbsp;</label>
                                            <input type="number" id="quantite" placeholder="Quantite" class="form-control" />
                                            
                                        </div>
                                        
                                        <div class="form-group col-lg-2 col-md-2 col-xs-2">
                                            <br>
                                             <div id="plus-purposeProduit">
                                            <button id="ajoutLigne" class=" float i-Add " type="button" >
                                                     <span class="ul-btn__icon"></span>
                                              </button>
                                              </div>
                                            <div id="edit-purposeProduit" style="display: none;">
                                                <button  id="editerLigne" class=" float i-Pen-2 " type="button" >
                                                         <span class="ul-btn__icon"></span>
                                                  </button>
                                                
                                              </div>
                                           
                                        </div>
                                    </div>
                                    <div id="tableLogement">
                                        <table class="table table-bordered">
                                            <thead >
                                                <tr>
                                                    <th>Consommable</th>
                                                    <th>Quantite</th>
                                                    <th class="action">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody id="partieFourniture">
                                                <tr id="vide"  style="background-color: #eef;"><td> <td>Aucune donnée disponible</td><td></td></tr>
                                            </tbody>

                                            <tfoot >
                                                 <tr>
                                                    <th>Consommable</th>
                                                    <th>Quantite</th>
                                                    <th class="action">Actions</th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                   
                                    <br/>

                            </div>
                            <div class="modal-footer">
                                <button id="close"  class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
                                <button id="save" class="btn btn-primary ml-2" type="button">Save</button>
                                 <button id="edit" class="btn btn-primary ml-2" type="button">Edit</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-11">
                       
                    </div>
                    <div class="col-md-1">
                        
                        <button id="addConsommable" class=" float i-Add " type="button" data-toggle="modal" data-target=".bd-example-modal-lg">
                             
                    <span class="ul-btn__icon"></span>
                </button>
                    </div>
                </div>
                &nbsp;
                 
                <div class="table-responsive">
                                    <table class="display table table-striped table-bordered" id="hidden_column_table" style="width:100%">
                                        <thead>
                                            <tr>
                                           <th>Id</th>
                                           <th>Nom</th>
                                            <th>Date fourniture</th>
                                            <th>Emplacement</th>
                                            <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                               
                                        </tbody>
                                        <tfoot>
                                             <tr>
                                           <th>Id</th>
                                           <th>Nom</th>
                                            <th>Date fourniture</th>
                                            <th>Emplacement</th>
                                            <th>Actions</th>
                                            </tr>
                                        </tfoot>
                                    </table>
                </div>
            </div><!-- Footer Start -->
            <div class="flex-grow-1"></div>
            <div class="app-footer">
                <div class="footer-bottom border-top pt-3 d-flex flex-column flex-sm-row align-items-center">
                    <span class="flex-grow-1"></span>
                    <div class="d-flex align-items-center">
                        <img class="logo" src="<?php echo $this->baseUrl('images/logo.png');?>" alt="">
                        <div>
                            <p class="m-0">&copy; 2021 ASLM</p>
                            <p class="m-0">All rights reserved</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- fotter end -->
        </div>
    </div><!-- ============ Search UI Start ============= -->
    
    <!-- ============ Search UI End ============= -->
    <script src="<?php echo $this->baseUrl('js/plugins/jquery-3.3.1.min.js');?>"></script>
     <script src="<?php echo $this->baseUrl('js/plugins/bootstrap.bundle.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('js/plugins/perfect-scrollbar.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('js/scripts/script.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('js/scripts/sidebar.large.script.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('js/plugins/datatables.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('js/plugins/loadingoverlay.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('js/plugins/sweetalert2.min.js');?>"></script>
    <script src="<?php echo $this->baseUrl('script/jquery.toast.min.js');?>"></script>
     <script  src="<?php echo $this->baseUrl('script/jquery.autocomplete.js'); ?>"></script>
     <script src="<?php echo $this->baseUrl("script/jquery-confirm.min.js"); ?>"></script>
    <script type="text/javascript">
          $(document).ajaxSend(function(event, jqxhr, settings){
            $.LoadingOverlay("show");
        });
        
        $(document).ajaxComplete(function(event, jqxhr, settings){
            $.LoadingOverlay("hide");
        });
        var contenuFourniture = {};
        contenuFourniture.total = 0;
        $('#edit').hide();
        actions = JSON.parse($('#listRole').val());
        console.log(actions)
        var valeur = false;
        actionUser = actions.filter((auth) => auth.controller === 'Consommable')
        $.each( actionUser, function( key, value ) {
            if(value.action.includes("add")){
                 valeur = value.action.includes("add");
                 return valeur
            }
            
        });
        if(valeur==false){
                $('#addConsommable').remove();
         }
       
   var sujetEdition='';
       
       
        
     var myTable =    $('#hidden_column_table').DataTable({
                    responsive: true,
                     "language": {
                                    "zeroRecords": " aucune donnée disponible ",
                                    "infoEmpty": "Aucune donnée disponible",
                                    "search": "recherche",
                                    "infoFiltered": ""
                                },
                    "processing" : true,
                    "serverSide" : true,
                    
                    "ajax" : {
                                         url : "<?php echo $this->url(array('controller' => 'Fourniture', 'action' => 'datatable')); ?>",
                                         type : "POST"
                             },
                             columnDefs: [
        { targets: [1,2,3,4], visible: true},
        { targets: '_all', visible: false }
    ],
                    columns : [
                                                    null,
                                                    null,
                                                     null,
                                                     null,
                                                   { render : function(data, type, row, meta) {
                                                            chaine = "";
                                                           $.each( actionUser, function( key, value ) {
                                                                if(value.action.includes("edit")){
                                                                     chaine+='<a class="myedit" href="#" code="' + row[0] +'" data-toggle="modal" data-target=".see-modal-lg"><i title="Edit" class="text-20 i-Eye"></i></a>  ';
                                                                }
                                                                
                                                             });
                                                          
                                                          
                                                            
                                                         return chaine;
                                                     }
                                                   }, 
                                                  
                                                    
                                              ],
                   
                });
       
 
   $('#consommable').keyup(function () {
        var params = {consommable: $('#consommable').val()};
        $.ajax({
            url: "<?php echo $this->url(array('controller' => 'Consommable', 'action' => 'find')); ?>",
            dataType: "json",
            type: "POST",
            data: params,
            beforeSend: function () {
                //$("#inputParent").LoadingOverlay("show");
            },
            success: function (response) {

                $('#consommable').autocomplete({
                    selectFirst: true,
                    autoFocus: true,
                    lookup: response.data,
                    onSearchComplete: function (suggestions) {
                        console.log(suggestions);
                    },
                    onSelect: function (suggestion) {
                        var info = {id: suggestion.id, type: suggestion.value};
                        $('#idconso').val(JSON.stringify(info.id));

                    },
                    showNoSuggestionNotice: true,
                    noSuggestionNotice: 'Aucun résultat trouvé'
                });
            },
            complete: function () {
                //$("#inputParent").LoadingOverlay("hide");
                $('#consommable').focus();
            },
            error: function () {

            }
        });

    });
    
     $('#emplacement').keyup(function () {
        var params = {emplacement: $('#emplacement').val()};
        $.ajax({
            url: "<?php echo $this->url(array('controller' => 'Emplacement', 'action' => 'find')); ?>",
            dataType: "json",
            type: "POST",
            data: params,
            beforeSend: function () {
                //$("#inputParent").LoadingOverlay("show");
            },
            success: function (response) {

                $('#emplacement').autocomplete({
                    selectFirst: true,
                    autoFocus: true,
                    lookup: response.data,
                    onSearchComplete: function (suggestions) {
                        console.log(suggestions);
                    },
                    onSelect: function (suggestion) {
                        var info = {id: suggestion.id, type: suggestion.value};
                        $('#idemp').val(JSON.stringify(info.id));

                    },
                    showNoSuggestionNotice: true,
                    noSuggestionNotice: 'Aucun résultat trouvé'
                });
            },
            complete: function () {
                //$("#inputParent").LoadingOverlay("hide");
                $('#emplacement').focus();
            },
            error: function () {

            }
        });

    });
    
   $("body").on( "click",".myedit",function(){
            var tab =[]
            
            code=$(this).attr('code')
           var params = {fourniture: code};
        $.ajax({
            url: "<?php echo $this->url(array('controller' => 'Fourniture', 'action' => 'find')); ?>",
            dataType: "json",
            type: "POST",
            data: params,
            beforeSend: function () {
               
            },
            success: function (response) {
                console.log(response)
                if(response.status==200){
                   $("#seeFourniture").empty();
                    var $htmlLigne='';
                     $.each( response.data, function( key, value ) {
                         
                          $htmlLigne += "<tr style='background-color:#dff0d8;'>" + "<td>" +value['consommable'] + "</td><td class='quantite'>" +value['quantite'] + "</td>" + "<td>"+value['date']+"</td></tr>";
                                                                
                    });
                   $('#empVue').val(response.emplacement)
                     $("#seeFourniture").append($htmlLigne);
                }else{
                     $.toast({
                        heading: "Erreur",
                        text: "Apprivisionement introuvable",
                        icon: "error",
                        hideAfter: false,
                        stack: false,
                        position: {top: top, left: left}
                     });
                }
            },
            complete: function () {
                
            },
            error: function () {

            }
        });
      })
      
      
      $("body").on("click", "#ajoutLigne", function (e) {
        e.preventDefault();
      

       

        if ($("#consommable").val() === "" || $("#idconso").val() == "") {
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $.toast({
                heading: "Info manquante",
                text: "Veuillez indiquer le consommable",
                icon: "error",
                hideAfter: false,
                stack: false,
                position: {top: top, left: left}
            });
            return false;
        }
         if ($("#quantite").val() === "") {
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $.toast({
                heading: "Info manquante",
                text: "Veuillez indiquer la quantite",
                icon: "error",
                hideAfter: false,
                stack: false,
                position: {top: top, left: left}
            });
            return false;
        }
       var $id = $("#idconso").val();
       var consommable = $("#consommable").val();
       var quantite = $("#quantite").val();
        if (contenuFourniture[$id] === undefined) {
            var objet = {};
            objet["id"] = $id;
             objet["consommable"] =consommable;
            objet["quantite"] = quantite;
           
            contenuFourniture[$id] = objet;

            var $htmlLigne = $("<tr style='background-color:#dff0d8;' id='" + $id + "'>" + "<td id='" + $id + "'  class='consommable'>" + consommable + "</td><td id='" + $id + "' class='quantite'>" +quantite + "</td>" + "<td> <a href='' class='editPurpose'><i class='text-20 i-Pen-2'></i></a><a href='' class='deletePurpose'><i class='text-20 i-Remove'></i></a></td></tr>");

            if ($("#partieFourniture").children().length === 0) {
                $("#vide").show()
            }
            $("#vide").hide();

            $("#partieFourniture").append($htmlLigne);
            $("#consommable").val("");
            $("#quantite").val("");

            //$("#total").text(contenuFacture.total);
        } else {
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $.toast({
                heading: "Doublon",
                text: "Le consommable " + consommable + " est déjà présent dans la fourniture courante",
                icon: "error",
                hideAfter: false,
                stack: false,
                position: {top: top, left: left}
            });
        }

    });
    
     $("body").on("click", ".deletePurpose", function (e) {
        e.preventDefault();
        var consommable = $(this).parent().parent().find(".consommable").html();
        
        var codeCourant = $(this).parent().parent().attr("id");
        var $parent = $(this).parent().parent();
        var codeHtml = $parent.children().first().html();
        $.confirm({
            title: 'suppression',
            content: "Voulez-vous vraiment supprimer ce consommable (" + consommable + ") de cette fourniture",
            theme: 'white',
            animationBounce: 2.5,
            confirmButton: 'supprimer',
            cancelButton: 'annuler',
            autoClose: "cancel|15000",
            confirm: function () {
                contenuFourniture[codeCourant] = undefined;

                $parent.remove();
                if ($("#partieFourniture").children().length === 1) {
                    $("#vide").show();
                    $("#plus-purposeProduit").hide();
                    $("#edit-purposeProduit").show();
                }
            }
        });
    });
    $("body").on("click", '.editPurpose', function (e) {
        e.preventDefault();
        var id = $(this).parent().parent().attr("id");
        var consommable = $(this).parent().parent().find(".consommable").html();
        sujetEdition = id;
        $("#consommable").val(consommable);
        $("#quantite").val(contenuFourniture[id]["quantite"]);
         $("#sujetEdition").val(id);
      
        $("#plus-purposeProduit").hide();
        $("#edit-purposeProduit").show();
    });
    
     $("body").on("click", "#editerLigne", function (e) {
        e.preventDefault();
       //Cas c est un produit
              var code = $("#sujetEdition").val();
       
        if (code == sujetEdition) {
            if ($("#quantite").val() === "") {
                var top = $(this).offset().top;
                var left = $(this).offset().left;
                $.toast({
                    heading: "Info manquante",
                    text: "Veuillez indiquer la quantite",
                    icon: "error",
                    hideAfter: false,
                    stack: false,
                    position: {top: top, left: left}
                });
                return false;
            }
            if ($("#consommable").val() === "" || $("#idconso").val() == "") {
                var top = $(this).offset().top;
                var left = $(this).offset().left;
                $.toast({
                    heading: "Info manquante",
                    text: "Veuillez  indiquer le consommable",
                    icon: "error",
                    hideAfter: false,
                    stack: false,
                    position: {top: top, left: left}
                });
                return false;
            }

            
            var objet = {};
             objet["id"] = sujetEdition;
             objet["consommable"] =$("#consommable").val();
            objet["quantite"] = parseInt($("#quantite").val());
            
            $(".quantite[id='" + sujetEdition + "']").html(objet["quantite"]);
            $(".consommable[id='" + sujetEdition + "']").html(objet["consommable"]);
            contenuFourniture[sujetEdition] = objet;
            $("#edit-purposeProduit").hide();
            $("#plus-purposeProduit").show();
            $("#consommable").val("");
             $("#quantite").val("");
            
        } else {
            
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $.toast({
                heading: "Incohérence",
                text: "Le consommable actuellement séléctionné ne correspond pas à l'émetteur d'édition",
                hideAfter: false,
                stack: false,
                icon: "error",
                position: {top: top, left: left}
            });
            return false;
        }
       
    });


   $("#save").on("click", function (e) {
        e.preventDefault();
        if ($("#partieFourniture").children().length === 1) {
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $.toast({
                heading: "Incohérence",
                text: "Votre fourniture est vide",
                hideAfter: false,
                stack: false,
                icon: "error",
                position: {top: top, left: left}
            });
            return false;
        }
        
         if ($("#idemp").val() ==="") {
            var top = $(this).offset().top;
            var left = $(this).offset().left;
            $.toast({
                heading: "Incohérence",
                text: "L'emplacement ou fournisseur doit etre precise",
                hideAfter: false,
                stack: false,
                icon: "error",
                position: {top: top, left: left}
            });
            return false;
        }
        
        
        var params = {
            details: [],
            
        };
      
        
        var $listeDetails = [];
        var nombreCoherent = 0;
        $.each(contenuFourniture, function (cle, valeur) {
            if (valeur !== undefined) {
                nombreCoherent++;
                var objetDetail = {
                    consommable: valeur["consommable"],
                    quantite: valeur["quantite"],
                    id:valeur["id"]
                    
                };


                $listeDetails.push(objetDetail);
            }
        });
        
      
        if (nombreCoherent === 0) {
            $.toast({
                heading: "Fourniture vide",
                text: "La fourniture que vous essayez d'enrégistrer est vide!",
                hideAfter: false,
                stack: false,
                icon: "error",
                position: "mid-center"
            });
            return false;
        }
        params.details = $listeDetails;
        params.idemplacement = $("#idemp").val();

        $.ajax({
            url: "<?php echo $this->url(array('controller' => 'Fourniture', 'action' => 'enregistrer')); ?>",
            data: params,
            dataType: "json",
            type: "POST",
            beforeSend:function(){
                 $("#save").LoadingOverlay("show");
            },
            complete:function(){
                $("#save").LoadingOverlay("hide");
            },
            error: function () {
                $.toast({
                    heading: "serveut inactif",
                    text: "GESMANAGER n'arrive pas à accéder au serveur , si cela persiste veuillez contacter l'administrateur ",
                    icon: "error",
                    hideAfter: false,
                    stack: false,
                    position: 'mid-center'
                });
            },
            success: function (data) {
               
                if (data.status === 200) {
                   
                    $.toast({
                        heading: "Succès",
                        text: "la reservation a été enrégistré avec succès",
                        icon: "success",
                        hideAfter: false,
                        stack: false,
                        position: "mid-center"
                    });
                    //var chemin = $("#chemin").val();

                   
                    var html = '<tr id="vide"  style="background-color: #eef;"><td> <td>Aucune donnée disponible</td><td></td></tr>';
                   

                    //Fin appel
                   
                    contenuFourniture = {};
                    contenuFourniture.total = 0;
                    
                    $("#partieFourniture").empty();
                    $("#partieFourniture").append(html);
                    if(myTable != null) myTable.destroy();
                 myTable =     $('#hidden_column_table').DataTable({
                    responsive: true,
                     "language": {
                                    "zeroRecords": " aucune donnée disponible ",
                                    "infoEmpty": "Aucune donnée disponible",
                                    "search": "recherche",
                                    "infoFiltered": ""
                                },
                    "processing" : true,
                    "serverSide" : true,
                    "ajax" : {
                                         url : "<?php echo $this->url(array('controller' => 'Fourniture', 'action' => 'datatable')); ?>",
                                         type : "POST"
                             },
                             columnDefs: [
        { targets: [1,2,3,4], visible: true},
        { targets: '_all', visible: false }
    ],
                    columns : [
                                                    null,
                                                    null,
                                                     null,
                                                     null,
                                                   { render : function(data, type, row, meta) {
                                                            chaine = "";
                                                           $.each( actionUser, function( key, value ) {
                                                                if(value.action.includes("edit")){
                                                                      chaine+='<a class="myedit" href="#" code="' + row[0] +'" data-toggle="modal" data-target=".see-modal-lg"><i title="Edit" class="text-20 i-Eye"></i></a>  ';
                                                                }
                                                                
                                                             });
                                                          
                                                          
                                                            
                                                         return chaine;
                                                     }
                                                   }, 
                                                  
                                                    
                                              ],
                   
                });
                      $("#close").click();

                } else {
                    $.toast({
                        heading: "erreur",
                        text: data.msg,
                        icon: "error",
                        hideAfter: false,
                        stack: false,
                        position: 'mid-center'
                    });
                }
            }
        });


    });
        
    </script>
</body>

</html>