<?php
session_start();
if(!isset($_SESSION["FirstName"],$_SESSION["LastName"],$_SESSION["PWD"])){ 
   header("Location: Login.php");
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <title>Form Layout - Mazer Admin Dashboard</title> -->

    <link rel="stylesheet" href="assets/css/main/app.css">
    <link rel="stylesheet" href="assets/css/main/app-dark.css">
    <link rel="shortcut icon" href="assets/images/logo/favicon.svg" type="image/x-icon">
    <link rel="shortcut icon" href="assets/images/logo/favicon.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/extensions/datatables.net-bs5/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="assets/css/pages/datatables.css">
<style>
    .card-body{
        position: relative;
    }
        .table{
       
      margin-top: 26px;
      width:100%;
      border-collapse: collapse;
        }
        .table th{
            background-color: #435ebe;
            color: white;
            border: 1px solid black;
            
        }
     
        .table td,.table th{
            padding: 10px 10px;
            border: 1px solid  #3965a8;
            text-align: center;
        }
        .table tr{
            color: black; 
        }
        .icon_edit {
            display: flex;
            justify-content: space-around;
        }
        .icon_edit a{
            text-decoration: none;
        }
        .icon_edit .delete i{
            color: red;
            transition: .5s;
            font-size: 20px;
        }
        .icon_edit .update i:hover{
            transform: scale(1.1);
        }
        .icon_edit .delete i:hover{
            transform: scale(1.1);
        }
        tbody input{
          height:30px;
          width:100%;
          outline:none;
          text-align:center;
        }
        thead tr th{
            text-align:center;
        }
        .inputsEnt{
            display:flex;
        }
        .inputsEnt input{
            margin:0 15px;
            height:30px;
            margin-top:10px;
        }
        .inputsEnt label{
            margin-top:15px;
        }
        .btn_add{
            font-size:15px;
        }
        /* #table_articleSELECT{
            display: flex;
        } */
        #table_articleSELECT input{
            /* width:130px; */
        }
        .inputdateEx{
            display:flex;
        }
        .table_articleSELECT{
            position: relative;
        }
        #table_articleSELECT i{
            color:white;
            font-size:20px;
            padding:5px 5px;
            cursor:pointer;
            transition:.3s;
            margin-top:2.5px;
            border:1px solid red;
            margin-left:5px;
            border-radius:2px;
            background-color:red;
        }
         #table_articleSELECT i:hover{
            transform:scale(1.1);
            color:red;
            background-color:white;
         }
         .inputentree{
            width:150px;
         }
         .first-input{
            width:150px;

         }
        .dateEdit{
            border-radius:5px;
        }
        #main{
           margin-left:276px;
         }
        
       .inputgri{
        pointer-events:none;
        background:#e9ecef;
        color:#a6afb2;
       }
       .button{
        margin-top:15px;
       }
       .loader{
        display:none;
        padding:0;
        margin:0;
        position:fixed;
        right:0;
        top:0;
        width:100%;
        height:100%;
        opacity:0.8;
        z-index: 30001;
        background-color:white;
       }
       .loader-img{
        position:absolute;
        right:0;
        left:0;
        bottom:0;
        top:0;
        margin:auto;
       }
       .row{
        /* display:flex;
        justify-content:space-around; */
       }
       .btn-Add-Article{
        margin-left:15px;
       }
       .dateDo{
        padding-top:9px;
       }
       .dateDocum{
        height:35px;
       }
       .buttonEnd button{
        margin:0 5px;
       }

        /*  */
        /* ressponsive 1192 */
        @media screen and (max-width: 1325px){
            .first-input{
            width:130px;
         }
        }
        @media screen and (max-width: 1192px){
            .first-input{
            width:110px;
         }
        }
        @media screen and (max-width:1146px){
            #main{
           margin-left:0px;
         }
        }
        @media screen and (max-width: 900px){
           #table_articleSELECT{
            display:block;
           }
            .inputdateEx{
                display:block;
                margin:20px 0;
                border:solid 1px #435ebe;
                border-radius:10px;
                padding: 5px 5px;
                box-shadow:5px 5px 5px 5px #435ebe;
            }
            .first-input,.remarque{
                width:100%;
            }
            .dateInput{
                margin:10px 0;
            }
            .delete_art{
                display:flex;
                justify-content:center;
            }
            .deleteDiv{
            padding: 5px 0;
            }
            .tableSortieM, .table tbody, .table tr, .table td{
                width: 100%;
            }
            .divInputUser{
                flex-direction:column;
            }
        }
        @media screen and (max-width: 900px){
            .tableSortieM{
                box-shadow:5px 5px 5px 5px #435ebe;
                border:solid 1px #435ebe;
                border-radius:10px;
            }
        .table thead{
      display: none;
      
      }

  .table, .table tbody, .table tr, .table td{
      display: block;
      width: 100%;
  }
  .table tr{
      margin-bottom: 15px;
      position: relative;
  }
  .table td{
      text-align: right;
      padding-left: 50%;
      position: relative;
  }
  .table td::before{
      content: attr(data-label);
      position: absolute;
      left: 0;
      width: 50%;
      padding-left: 15px;
      font-size: 15px;
      font-weight: bold;
      text-align: left;
  }
  tbody input{
          height:30px;
          width:130px;
    }
  .icon_edit {
    display: flex;
    justify-content: flex-end;
  }
  .icon_edit a{
      margin: 0 10px;
  }
  .email_edit{
      font-size: 9px;
  }
   .remarque textarea{
    width:100%;
   }
}
        /* ress */
    
</style>
</head>

<body>
    <!-- ServiceLayer/CreateSortieMarchandise.php -->
    <form id="formCreateM" action="ServiceLayer/CreateSortieMarchandise.php" method="POST">
        <div class="loader">
            <img class="loader-img" src="img/loadingNi.gif" alt="" srcset="" style="height:190px">
        </div>
    <div id="app">
        <div id="sidebar" class="active">
            <div class="sidebar-wrapper active" style='width:270px'>
                <?php include 'parts/sidebar.php';?>
            </div>
        </div>
        <div id="main" style='padding: 2px 1rem;'>
            <header class="mb-3">
                <a href="#" class="burger-btn d-block d-xl-none">
                    <i class="bi bi-justify fs-3"></i>
                </a>
            </header>

            <div class="page-heading">
                <form id="add_name" action="" method="post">

                <!-- // Basic multiple Column Form section start -->
                <section id="multiple-column-form ">
                    <div class="row match-height">
                        <div class="col-12">
                            <div class="card">
                               
                                <div class="card-content">
                                    <div class="card-body">
                                            <div class="row">
                                                <!-- )))))))))))) -->
                                                    <?php 
                                                        if(isset($_SESSION['MessageSortie'])) {
                                                        echo '<div id="messageAlertS" class="alert alert-success" role="alert" style="text-align:center">
                                                                '.$_SESSION["MessageSortie"].'
                                                            </div>'; 
                                                        //  echo '<script>alert("'.$_SESSION['Message'].'  DocEntry=> '.$_SESSION['DocEntry'].'");</script>';
                                                            unset($_SESSION['MessageSortie']);
                                                        }
                                                        if(isset($_SESSION['MessageSortiedanger'])) {
                                                            echo '<div id="messageAlert" class="alert alert-danger " role="alert" style="text-align:center;">
                                                                    '.$_SESSION['MessageSortiedanger'].'
                                                                </div>';
                                                            //echo '<script>alert("'.$_SESSION['Message'].'  DocEntry=> '.$_SESSION['DocEntry'].'");</script>';
                                                                unset($_SESSION['MessageSortiedanger']);
                                                                
                                                        }
                                                    ?>
                                            <div class="d-flex justify-content-between divInputUser">
                                                         <div class="form-group inputsEnt" >
                                                           <label for="PCode">Client</label>
                                                           <input type="text" id="PCode" class="form-control inputentree inputgri" readonly='readonly' name="codeClient" />
                                                           <button  type="button" id= "ClientButton" class=" btn btn-primary mb-3 btn_add_client" data-bs-toggle="modal" data-bs-target="#staticBackdrop" style="margin-top:5px">+</button> 
                                                        </div>

                                                        <div class="form-group inputsEnt">
                                                            <label for="Type">Projet</label>
                                                            <input type="text" id="projectvalue" class="form-control inputentree inputgri" readonly='readonly'  name="typeProject" >
                                                            <button type="button" id= "ProjectButton" class=" btn btn-primary mb-3 btn_add" data-bs-toggle="modal" data-bs-target="#staticBackdrop_project" style="margin-top:5px">+</button> 
                                                        </div>

                                                        <div class="form-group dateDo" style='display:flex; '>
                                                            <label style='padding-right:15px;line-height:40px;' for="PName">Date document</label>
                                                            <input type="date" id="PName" class="form-control inputentree dateDocum" name="dateDocument"  value="<?php echo date('Y-m-d');?>">   
                                                        </div>          
                                            </div>
                                          
                                                
                                            </div>

                                            <div style="border-top: 1px solid#457b9d; padding-top:15px; font-size:85%" >  </div> 
                                               <!-- Pills Tabs -->
                                                    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist" data-aos="zoom-in-up">
                                                        <li class="btn-Add-Article">
                                                            <button type="button" id="consultation" class=" btn btn-primary mb-3 btn_add_article" data-bs-toggle="modal" data-bs-target="#staticBackdrop_">+</button>
                                                        </li>
                                                      
                                                    </ul>
                                     <div class="tab-content pt-2" id="myTabContent">
                                            <!-- Pills Tabs -->   
                                            <!-- Consultation -->
                                     <div class="tab-pane fade show active"  id="pills-Consultation" role="tabpanel" aria-labelledby="Consultation-tab">                                                     
    </table>
                                                  <!-- table -->
<div class="tab-pane fade show active" id="pills-Consultation" role="tabpanel" aria-labelledby="Consultation-tab">
            <table id="id_tabe_Article" class="table tableSortieM" >
                <thead>         
                    <th>Code Article </th>
                    <th>Description</th>
                    <th>Numéro De Lot</th>
                    <th>Quantité</th>
                    <th>Nombre De Palétte</th>
                    <th>Code Projet</th>
                    <th>Magasin</th>
                    <th>Supprime</th>
                </thead>
                <tbody id="Tbody">
                <!-- <tr>
                        <td data-label="numero D'article"><input class='inputgri' type="text"> </td>
                        <td data-label="Description"><input class='inputgri' type="text" ></td>
                        <td data-label="lot">
                             <select class="form-select" aria-label="Default select example" >
                                    <option id="320" value="C001023TEST2001">C001023TEST2001</option>
                                    <option id="200" value="C001023TEST2002">C001023TEST2002</option>
                                    <option id="400" value="C001023TEST2003">C001023TEST2003</option>
                             </select>
                        </td>
                        <td data-label="quantite"><input type="number" value=""></td>
                        <td data-label="date d'expiration"><input class='inputgri' type="text" ></td>
                        <td data-label="edit">
                        <div class="icon_edit">
                            <a class="delete" href="#"><i class="fa-solid fa-trash"></i></a> 
                        </div>
                       </td>
                    </tr>    -->
                <tbody>            
         </table>
    <div class="remarque" >
        <div>
        <label for="remarque">Remarque :</label>
        </div> 
        <textarea name="remarque" id="" cols="50" rows="3"></textarea>
    </div>
        </div>
                    <!-- Modal Article -->
        <div class="modal fade " id="staticBackdrop_" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel_" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
            <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel_">List Article</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- table -->
            <table class="table" id="tableArticleModel">
                <thead>
                    <tr>
                        <th>Code Article</th>
                        <th>Nom Article</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
            <!-- end table -->
                </div>
                </div>
            </div>
            </div>
        <!-- end Modal -->
    <!--end  Consultation --> 
    <!-- Modal -->
     <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
        <div class="modal-content">
        <div class="modal-header">
            <h1 class="modal-title fs-5" id="staticBackdropLabel_">Liste Client</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <!-- table -->
            <table class="table_Client" id="table_Client">
                <thead>
                    <tr>
                        <th>Code Client</th>
                        <th>Nom Client</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
           </table>                                   
          <!-- end table -->
            </div>                                                  
            </div>
        </div>                                                
        </div>
     <!-- end Modal -->
    <!-- end Médicament -->
    <!--  Radio -->                                         
     <!-- end Modal -->
        <!--  Modal projet-->
        <div class="modal fade" id="staticBackdrop_project" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
         <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
          <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- table -->
            <table class="table" id="table_project">
                    <thead>
                        <tr>
                            <th>Id Project</th>
                            <th>description</th>   
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
            </table>
          <!-- end table -->
            </div>
          </div>
        </div>  
    </div>
     <!-- table Lot -->
     <div class="modal fade" id="staticBackdrop_Lot" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
         <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
          <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- table -->
            <table class="table" id="table_lot">
                    <thead>
                        <tr>
                            <th>Numéro De Lot</th>
                            <th>Quantité Disponible</th>   
                            <th>Magasin</th>   
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
            </table>
          <!-- end table -->
            </div>
          </div>
        </div>  
    </div>

      <!-- table Magasin -->
      <div class="modal fade" id="staticBackdrop_Whs" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
         <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
          <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="staticBackdropLabel">List Magasin</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- table -->
            <table class="table_Whs" id="table_Whs">
                    <thead>
                        <tr>
                            <th>Code Magasin</th>
                            <th>Nom Magasin</th>   
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
            </table>
          <!-- end table -->
            </div>
          </div>
        </div>  
    </div>

    <div class="d-flex justify-content-end buttonEnd">
        <button  type="submit" name="creer"  class="btn btn-primary mb-3 button submitSortie">Creer</button>
        <button  type="submit" name="submit" class="btn btn-primary mb-3 button ">Interrompre</button>
    </div>
                                            
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    </form>
                </section>
                <!-- // Basic multiple Column Form section end -->
                </form>    
            </div>
        </div>
    </div>
    <script>

    </script>
    <script src="assets/js/delay.js"></script>
    <script defer src="assets/js/NavActive.js"></script>
    <script src="assets/js/bootstrap.js"></script>
    <script src="assets/js/app.js"></script>
    <script src="assets/extensions/jquery/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/v/bs5/dt-1.12.1/datatables.min.js"></script>
    <script src="assets/js/pages/datatables.js"></script>
    <!-- <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
      AOS.init();
    </script> -->

<script>
    var numClient;
    var numProject;
    var item = 0;
    var item1 = 0;
    var item2 = 0;
    var lotInfo;
    var codeClient;
    var codeProject;
    var rowIndex;
    
    $(document).ready(function() {
        
        var wrapper   		= $(".input-group1");
        var add_button      = $(".add_field_button");
        var add_more        =$(".add_more");      
        var x = -1; 
        $(add_button).click(function(e){ 
        e.preventDefault();
                x++;         
                $(wrapper).append('<div class="input-group mb-3"> <div class="col-xs-2"><input readonly type="text" class="form-control mb-3 first-input " id="article_'+x+'" name="Medicament[ItemCode][]" placeholder="Médicament "> </div><button type="button" id= '+x+' onclick="add(this)" class=" btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#staticBackdrop">+</button><input type="text" id="Description_'+x+'" name="Medicament[ItemName][]" class="form-control mb-3 " placeholder="Description" /><div class="col-xs-1"><input id="articleQte_'+x+'" type="number" id="typeNumber" value="1" min="1" name="Medicament[Quantity][]" class="form-control mb-3 " placeholder="Quantity" /> </div><input id="articleInstruction_'+x+'" type="text" class="form-control mb-3" name="Medicament[Instruction][]" placeholder="Instructions "> <div class="input-group-append"><button class="btn btn-outline-danger remove_field" type="button"><i class="bi bi-trash"></i></button></div></div>'); //add input box
        });
        $(wrapper).on("click",".remove_field", function(e){ 
            e.preventDefault(); $(this).parent('div').parent('div').remove(); x--;
        })

    });
    
   

    $(document).ready(function () {
       
        var clientIn = $("#PCode").val();
             var projectIn = $("#projectvalue").val();
            if(clientIn==="" && projectIn===""){
                $('#staticBackdrop_').modal('hide');
          
               
            }else{
                $('#staticBackdrop_').modal('show');
            }

        var i=0;
        var p=0;
            
              // delete article
              var divDelete = $("#table_articleSELECT");
              $(divDelete).on("click",".delete_art", function(e){ 
                e.preventDefault(); $(this).parent('div').parent('div').remove();
                 i--;p--;$check=true;
                 $(divDelete).load(location.href + divDelete);
                 console.log('data refresh');
              });
              if(p<=0){
                    p=0;
                }
    });


   // get client
   $(document).ready(function () {
        var table = $('#table_Client').DataTable({  
            ajax: {                
                url: 'ServiceLayer/GetClient.php',  
                dataSrc: "",
                data: {
                    "Groupe": "" 
                }
            },
            "autoWidth": false,
            "bDestroy": true,
                columns: 
                [   
                    // liste client 
                    { data: 'CardCode' },
                    { data: 'CardName' }
                ],
        });
    
        $('#table_Client tbody').on('dblclick', 'tr', function () {    
            var data = table.row(this).data();
            $('#staticBackdrop').modal('hide');
            $('body').removeClass('modal-open');alert
            $('.modal-backdrop').remove();
            $('#staticBackdrop').on('hidden.bs.modal', function() {
            $(this).removeData('bs.modal');
            $('#PCode').val(data["CardCode"]+'-'+data["CardName"]);
            codeClient=data["CardCode"];
            numClient=data["CardCode"];       
            });     
        });    
        // end les client    
    })

    
    // get project
    $(document).ready(function () {
        $('#ProjectButton').click(function(){
       // location.replace('ServiceLayer/getProject.php');
       
         var dataTableProject = $('#table_project').DataTable();
         $.ajax({
                url: 'ServiceLayer/getProject.php',
                type: 'POST',
                data: { codeClientGet:codeClient},
                success: function(response) {
                  
                    dataTableProject.clear();
                    var data = JSON.parse(response); // Parse the JSON response
                    for (var i = 0; i < data.length; i++) {
                        var code = data[i].Code;
                        var name = data[i].Name;
                        var itemHtml = '<tr>';
                         itemHtml += '<td>'+ code +'</td>';
                         itemHtml += '<td>'+ name + '</td>';
                         itemHtml += '</tr>';
                            // resultContainer.append(itemHtml);
                            dataTableProject.row.add($(itemHtml));
                    }
                    dataTableProject.draw();
                },
                error: function(xhr, status, error) {
                    console.log(error);
                }
            });
        
        });


        $('#table_project tbody').on('dblclick', 'tr', function () {
            var dataTableProject = $('#table_project').DataTable(); 
            var data = dataTableProject.row(this).data();
            //var data = table.row(this).data();
            console.log(data[0]);
            projectCheck=data[0];
            // $('#orm').val(data[1]); 
            console.log(data[0]);
            $('#staticBackdrop_project').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            $('#staticBackdrop_project').on('hidden.bs.modal', function() {
            $(this).removeData('bs.modal');
            $('#projectvalue').val(data[0]);
            codeProject=data[0];
            });            
        });    // end les project

       

            //Delete row Attach click event handler to delete buttons
            $('#id_tabe_Article').on('click', '.delete', function() {
                var row = $(this).closest('tr');
                row.remove();
            });
    });
    // getline des articles
    

    $(document).ready(function () {
        $('.submitSortie').click(function(event) {
    // Code to execute when the button is clicked
            var client = $('#PCode').val();
            var projet = $('#projectvalue').val();
            var dateDocument = $('#PName').val(); 
                if(client==="" || projet==="" || dateDocument===""){
                    event.preventDefault();
                    alert("Vous devez remplir tous les champs");
                }else{
                    $('#formCreateM').submit();
                } 
        });

       
        $('#consultation').on('click', function () {   
             var tableArticleModel = $('#tableArticleModel').DataTable(); 
            console.log("code client "+codeClient+" code projet "+codeProject);
                var client=numClient;
                var project =numProject;
                // if(client.length===0 && project.length===0 || client===undefined || project===undefined){
                //     alert('Chose Client(1) + Projet(2)');
                // }
                // else
                // {
                    $('.loader').show();
                    console.log('N projet :'+project+'<====> N client :'+client);
                    // var table = $('#id_tabe_Article').DataTable({
                    //             searching: false
                    // });
               
                   var flag=0;
                    $.ajax({
                        url: "ServiceLayer/getItemCheckout.php",
                        data: { 
                            ClientS: client, 
                            ProjectS: document.getElementById("projectvalue").value  
                        },
                        cache: false,
                        type: "POST",
                        success: function(response) {
                                var parsedData = response;
                                 tableArticleModel.clear();
                                 //resultContainer.empty();//delete data 
                                 //var dataTableValues = tableArticleModel.rows().data().toArray();
                                   // console.log('This Is=:'+dataTableValues);
                                parsedData.value.forEach(function(dataObject) {
                            // console.log('data=>'+dataObject.dscription); // Output: Each object in the array
                                        var itemHtml = '<tr>';
                                            itemHtml += '<td data-label="Code Article">'+ dataObject.itemcode +'</td>';
                                            itemHtml += '<td data-label="Description">'+ dataObject.dscription + '</td>';
                                            itemHtml += '</tr>';
                                        // resultContainer.append(itemHtml);
                                        tableArticleModel.row.add($(itemHtml));
                                            flag++;
                                });     
                                tableArticleModel.draw();
                                 if(flag!==0){
                                    $('.loader').hide();     
                                 }else{
                                    alert('Aucune donnee trouve');
                                    location.reload();
                                 }                 
                        },
                        error: function(xhr) {
                            console.log('Error in AJAX response');
                            console.log('Status:', status);
                            console.log('Error:', error);
                            console.log('Response:', xhr.responseText);
                            $('.loader').hide();
                        } 
                   });
                  // location.replace('ServiceLayer/getItemCheckout.php');
                // }               
        });    

        // $(document).on('click', '#plusLot', function() {
        //     var row = $(this).closest('tr');
        //     var Index = row.index();
        //     var codeArticle = Index.find('.code-article').val();
            
        // });

        // get article 
        $('#tableArticleModel tbody').on('dblclick', 'tr', function () {      
            var tableArticleModel = $('#tableArticleModel').DataTable(); 
            var data = tableArticleModel.row(this).data();
        // 
        console.log("prject : "+document.getElementById("projectvalue").value)
       

        var flag=0; 
            $.ajax({
                        url: "ServiceLayer/GetLineSortie.php",
                        data: { 
                            ClientS: numClient, 
                            ProjectS: document.getElementById("projectvalue").value,
                            ItemCode:data[0]
                        },
                        cache: false,
                        type: "POST",
                        success: function(response) {
                          
                            var dataTable = $('#table_lot').DataTable();
                            dataTable.clear();
                            var responseData = JSON.parse(response); // Parse the JSON response
                                var itemcode = responseData[0].itemcode; // Access the 'itemcode' property
                                var description=responseData[0].dscription;
                                //var nuLot=responseData[0].itemcode;
                                var quantite=responseData[0].Quantity;
                                var codeProject=responseData[0].u_codeproject;        
                                // Use the 'itemcode' value as needed
                             //   console.log(itemcode);

                               //  console.log( numClient+'=>'+document.getElementById("projectvalue").value+'=>'+data[0]);
                                 var resultContainer = $('#Tbody');
                                 var itemHtml = '<tr>';
                                 itemHtml += '<td data-label="Code Article"><input type="text" class="form-control inputgri code-article" name="listArticle[idArticle][]" value="'+ itemcode +'"></td>';
                                 itemHtml += '<td data-label="Description"><input type="text" class="form-control inputgri description" name="listArticle[description][]" value="'+ description + '"></td>';
                                // itemHtml += '<td data-label="Numéro De Lot"> <select class="form-select" aria-label="Default select example" ><option id="320" value="C001023TEST2001">C001023TEST2001</option><option id="200" value="C001023TEST2002">C001023TEST2002</option><option id="400" value="C001023TEST2003">C001023TEST2003</option></select></td>';
                                //  itemHtml += '<td data-label="Numéro De Lot"><select name="listArticle[lot_p][]" class="form-select" aria-label="Default select example">';
                                //  for (var i = 0; i < responseData.length; i++) {
                                //           itemHtml += '<option id="' + responseData[i].Quantity + '" value="' + responseData[i].DistNumber + '">' + responseData[i].DistNumber + '</option>';
                                //     };
                                //  itemHtml +='</select></td>';
                                itemHtml += '<td class="btn_add_lot" data-label="Numéro De Lot" style="display:flex;justify-content:center"><input id="numeroLot" style="margin-top:10px;margin-right:5px;" class="form-control inputgri numero-de-lot" type="text" name="listArticle[lot_p][]" value=""> <button style="" type="button" id="plusLot" class="btn btn-primary mb-3 btn_add_lot" data-bs-toggle="modal" data-bs-target="#staticBackdrop_Lot">+</button>';
                                // for (var i = 0; i < responseData.length; i++) {                                    
                                //         //   itemHtml +=  responseData[i].Quantity + responseData[i].DistNumber  + responseData[i].DistNumber ;
                                //              var ligne='<tr>';
                                //              ligne+='<td>'+responseData[i].DistNumber+'</td>';
                                //              ligne+='<td>'+responseData[i].Quantity+'</td>';
                                //              ligne+='</tr>';
                                //              dataTable.row.add($(ligne));     
                                // }; 
                                 itemHtml +='</td>';
                                 itemHtml +='<td data-label="Quantité"><input type="number" id="quantite" class="form-control quantite" name="listArticle[quantite][]" value=""></td>';
                                 itemHtml +='<td data-label=" Nombre De Palétte"><input type="number" id="nbr_palette" class="form-control nbr_palette" name="listArticle[NbrPallette][]" value=""></td>';
                                 itemHtml +='<td data-label="Code Projet"><input class="form-control inputgri" type="text" value="' +codeProject+'"></td>';
                                 itemHtml += '<td data-label="Magasin" ><input id="selectMagasin"  class="form-control inputgri"  type="text" name="listArticle[selectMagasin][]" value=""> ';
                        
                                 itemHtml +='<td data-label="edit"><div class="icon_edit"><a class="delete"><i class="fa-solid fa-trash"></i></a></div></td>';
                                 itemHtml +='</tr>';
                                 dataTable.draw();
                                 resultContainer.append(itemHtml); 
                                 flag++; 
                                 if(flag!==0){
                                     $('.loader').hide();     
                                  }else{
                                     alert('Aucune donnee trouve');
                                     location.reload();
                                 }                 
                        },
                        error: function(xhr) {
                            console.log('Error in AJAX response');
                            console.log('Status:', status);
                            console.log('Error:', error);
                            console.log('Response:', xhr.responseText);
                            $('.loader').hide();
                        } 
                   });   
    //location.replace("ServiceLayer/GetLineSortie.php");
            console.log("itemcode : "+data[0]);
            $('#staticBackdrop_').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            $('#staticBackdrop_').on('hidden.bs.modal', function() {
                 $(this).removeData('bs.modal');
            });            
        });  
        // $(document).on('change', 'select', function() {
        //     var selectedOption = $(this).find('option:selected');
        //     var id = selectedOption.attr('id');
        //     var inputField = $(this).closest('tr').find('#quantite');
        //     //inputField.val(id);
        // }); 

        $(document).on('click', '#plusWhs', function() {
            var flag=0;
            var row = $(this).closest('tr');
            rowIndex = row.index();
            $('.loader').show();
            //AJAX
            $.ajax({
                        url: "ServiceLayer/getWareHouse.php",
                        success: function(response) {
                            var dataTable = $('#table_Whs').DataTable();
                            dataTable.clear();
                            var responseData = JSON.parse(response); // Parse the JSON response
                                var itemcode = responseData[0].itemcode; // Access the 'itemcode' property
                                var description=responseData[0].dscription;
                                //var nuLot=responseData[0].itemcode;
                                var quantite=responseData[0].Quantity;
                                var codeProject=responseData[0].u_codeproject;        

                                for (var i = 0; i < responseData.length; i++) {                                    
                                        //   itemHtml +=  responseData[i].Quantity + responseData[i].DistNumber  + responseData[i].DistNumber ;
                                             var ligne='<tr>';
                                             ligne+='<td>'+responseData[i].WarehouseCode+'</td>';
                                             ligne+='<td>'+responseData[i].WarehouseName+'</td>';
                                             ligne+='</tr>';
                                             dataTable.row.add($(ligne));     
                                }
                                 dataTable.draw();
                                // resultContainer.append(itemHtml); 
                                 flag++; 
                                 if(flag!==0){
                                     $('.loader').hide();     
                                  }else{
                                     alert('Aucune donnee trouve');
                                     location.reload();
                                 }                 
                        },
                        error: function(xhr) {
                            console.log('Error in AJAX response');
                            console.log('Status:', status);
                            console.log('Error:', error);
                            console.log('Response:', xhr.responseText);
                            $('.loader').hide();
                        } 
                   });  
         });

        $('#table_Whs tbody').on('dblclick', 'tr', function () {
            var row = $('#id_tabe_Article tbody tr').eq(rowIndex);
            //rowIndex
            var dataTableProject = $('#table_Whs').DataTable(); 
            var data = dataTableProject.row(this).data();
            $('#staticBackdrop_Whs').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            // console.log('check:'+row.find('.code-article').val());
            $('#staticBackdrop_Whs').on('hidden.bs.modal', function() {
            $(this).removeData('bs.modal');
            row.find('#selectMagasin').val(data[0]);
            // row.find('.quantite').val(data[1]);
            });            
        });
        
        $(document).on('click', '#plusLot', function() {
            var flag=0;
            var row = $(this).closest('tr');
            rowIndex = row.index();
            var codeArticle = row.find('.code-article').val();
            $('.loader').show();
            //AJAX
            console.log('data ajax response='+numClient+'/'+document.getElementById("projectvalue").value+'/'+codeArticle)
            $.ajax({
                        url: "ServiceLayer/GetLineSortie.php",
                        data: { 
                            ClientS: numClient, 
                            ProjectS: document.getElementById("projectvalue").value,
                            ItemCode:codeArticle
                        },
                        cache: false,
                        type: "POST",
                        success: function(response) {
                            var dataTable = $('#table_lot').DataTable();
                            dataTable.clear();
                            var responseData = JSON.parse(response); // Parse the JSON response
                                var itemcode = responseData[0].itemcode; // Access the 'itemcode' property
                                var description=responseData[0].dscription;
                                //var nuLot=responseData[0].itemcode;
                                var quantite=responseData[0].Quantity;
                                var codeProject=responseData[0].u_codeproject;        

                                 console.log( numClient+'=>'+document.getElementById("projectvalue").value+'=>'+codeArticle);
                                for (var i = 0; i < responseData.length; i++) {                                    
                                        //   itemHtml +=  responseData[i].Quantity + responseData[i].DistNumber  + responseData[i].DistNumber ;
                                             var ligne='<tr>';
                                             ligne+='<td>'+responseData[i].DistNumber+'</td>';
                                             ligne+='<td>'+responseData[i].Quantity+'</td>';
                                             ligne+='<td>'+responseData[i].WhsCode+'</td>';
                                             ligne+='</tr>';
                                             dataTable.row.add($(ligne));     
                                }
                                 dataTable.draw();
                                // resultContainer.append(itemHtml); 
                                 flag++; 
                                 if(flag!==0){
                                     $('.loader').hide();     
                                  }else{
                                     alert('Aucune donnee trouve');
                                     location.reload();
                                 }                 
                        },
                        error: function(xhr) {
                            console.log('Error in AJAX response');
                            console.log('Status:', status);
                            console.log('Error:', error);
                            console.log('Response:', xhr.responseText);
                            $('.loader').hide();
                        } 
                   });  
         });

        $('#table_lot tbody').on('dblclick', 'tr', function () {
            var row = $('#id_tabe_Article tbody tr').eq(rowIndex);
            //rowIndex
            var dataTableProject = $('#table_lot').DataTable(); 
            var data = dataTableProject.row(this).data();
            $('#staticBackdrop_Lot').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            // console.log('check:'+row.find('.code-article').val());
            $('#staticBackdrop_Lot').on('hidden.bs.modal', function() {
            $(this).removeData('bs.modal');
            row.find('#numeroLot').val(data[0]);
            row.find('.quantite').val(data[1]);
            row.find('#selectMagasin').val(data[2]);
            });            
        });    // end les project
    });
   
    $(document).ready(function () {
        var clientIn=document.getElementById("PCode");
        var projectIn=document.getElementById("projectvalue");
            $("#Consultation").addClass("active");
            // if(clientIn!='' AND projectIn!=''){
                $("#Dashboard").removeClass("active");
        // ---------------
        const queryString = window.location.search;
        const DocEntry = new URLSearchParams(queryString).get('DocEntry');
        // side bar edit
        // $(".sidebar-item a").on( "click", function() {
        //     $(this).addClass('active').siblings().removeClass('active');
        // });
        // $("#SortieStock").on( "click", function() {
        //     $("#SortieStock").add("active");
        //     $("#EntreeStock").removeClass("active");
        // });
    });
    // function add1(raa){
    //     item1 =  $(raa).attr('id');
    // }

    // function add2(anal){
    //     item2 =  $(anal).attr('id');
    // }
    // function add(or){
    //     item =  $(or).attr('id');
    // } 
</script>
</body>
</html>