<?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 #435ebe;
            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:22px;
          width:110px;
          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 input{
            /* width:130px; */
            width:100%;
        }
        .inputdateEx{
            display:flex;
            width:85%
        }
        .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;
        }
        .mb-3{
            margin-bottom:0;
        }
        #main{
           margin-left:276px;
         }
        
       .inputgri{
        pointer-events:none;
        background:#e9ecef;
        color:#a6afb2;
        text-align:center;
       }
       .inputgriTable{
        pointer-events:none;
        background:#435ebe;
        color:white;
        text-align:center;
       }
       .button{
        margin-top:15px;
       }
       .dateInput{
        display:flex;
        justify-content:flex-end;
       }
       .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;
       }
       .delete_art{
        display: flex;
        justify-content: center;
       }
       /* .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;
       }
       #Tbody input{
        width:100%;
        line-height:15px;
        height:30px;
       }
    @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;
  }
  /* .inputGod{
    margin-top:10px;
  } */
  .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;
    }
   .dateInput{
    
   }
}
        /*  */
        /* 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){
           .tableEntreMar{
            display:block;
           }
           .contenuArticle{
            width:100%;
           }
            .inputdateEx{
                display:block;
                margin:20px 0;
                border:solid 1px #435ebe;
                border-radius:10px;
                padding: 5px 5px;
                box-shadow:5px 5px 5px 5px #435ebe;
                /* min-width:700px; */
                width:100%;
            }
            .first-input,.remarque{
                width:100%;
            }
            .dateInput{
                margin:10px 0;
            }
            .delete_art{
                display:flex;
                justify-content:center;
            }
            .deleteDiv{
            padding: 5px 0;
            }
            .divInputUser{
                flex-direction:column;
            }
            .inputdateEx{
                width: 100%;
            }
            
        }
        @media screen and (max-width: 900px){
            #NameColumnTable{
                display:none;
            }
        .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:22px;
          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>
    <form id="formCreateM" action="ServiceLayer/mefentreemar.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['Message']))
                                                     {
                                                        echo '<div id="messageAlert" class="alert alert-success " role="alert" style="text-align:center;">
                                                                '.$_SESSION['Message'].'
                                                            </div>';
                                                        //echo '<script>alert("'.$_SESSION['Message'].'  DocEntry=> '.$_SESSION['DocEntry'].'");</script>';
                                                            unset($_SESSION['Message']);
                                                            unset($_SESSION['DocEntry']);
                                                    }

                                                    if(isset($_SESSION['Messagedanger'])) 
                                                    {
                                                        echo '<div id="messageAlert" class="alert alert-danger " role="alert" style="text-align:center;">
                                                                '.$_SESSION['Messagedanger'].'
                                                            </div>';
                                                        //echo '<script>alert("'.$_SESSION['Message'].'  DocEntry=> '.$_SESSION['DocEntry'].'");</script>';
                                                            unset($_SESSION['Messagedanger']);
                                                            
                                                    }
                                                ?>
                                            <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="Pname">Client nom</label>
                                                           <input type="text" id="Pname" class="form-control inputentree inputgri" readonly='readonly' name="nomclient" />
                                                   
                                                        </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 style="border-top: 1px solid#457b9d; padding-top:15px; font-size:85%">  </div>  
                                               
                                            </div>
                                     <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">
                                                    <div class="form-outline"> <label class="form-label" for="typeNumber" ></label> </div>
                                                        <div class="col-md-4"></div>
                                                        <div class="input-group">                                            
                                                            <div class="input-group"> </div>
                                                        </div>
                                                    <div class="col-md-4"></div>
                                                    <div class="col-xs-2" style="display: flex ;justify-content: space-between;">
                                                     <button type="button" id= "consultation" class=" btn btn-primary mb-3 btn_add_article" data-bs-toggle="modal" data-bs-target="#staticBackdrop_">+</button>
                                                     <!-- <select name="magasin" class="form-select" id="selectMagasin" style="height:40px;width:130px"> -->
                                                        <!-- <option id="01" value="MAGASIN 1">MAGASIN 1</option>
                                                        <option id="02" value="MAGASIN 2">MAGASIN 2</option>
                                                        <option id="03" value="MAGASIN 3">MAGASIN 3</option> -->
                                                    <!-- </select> -->
                                                </div>                                      
    </table>
                                                  <!-- table -->
<div class="tab-pane fade show active" id="pills-Consultation" role="tabpanel" aria-labelledby="Consultation-tab" style="position:relative;">
<!--  -->
<table id="id_tabe_Article" class="table " >
                <thead>         
                    <th>Code Article </th>
                    <th>Description</th>
                    <th>Numéro De Lot</th>
                    <th>Quantité</th>
                    <th>Nombre De Palétte</th>
                    <th>Date D'expiration</th>
                    <th>Date D'autorisation</th>
                    <th>Magasin</th>
                    <th>Supprime</th>
                </thead>
                <tbody id="Tbody">
                <!-- <tr>
</div><div class='col-lg-2 '></div><div class='col-lg-2 '> <a id='"+i+"' class='delete_art deleteDiv'> <i id='"+i+"' class='fa-solid fa-trash delete_art'></i></a></div></div>")
                        <td data-label="Code Article"><input type='text' class='form-control mb-3 first-input input_id' id='article_Consultation' name='listArticle[idArticle][]' value='"+data["ItemCode"]+"'></td>
                        <td data-label="Description"><input type='text' id='article_ConDescription' name='listArticle[description][]' class='form-control mb-3 first-input' value='"+data["ItemName"]+"'></td>
                        <td data-label="Numéro De Lot"><input type='text' id='article_lot' readonly='readonly' name='listArticle[lot_p][]' class='form-control mb-3 first-input inputgri' value='"+lotInfo.toString()+"' ></td>
                        <td data-label="Quantité"><input type='text' class='form-control mb-3 first-input ' id='article_quantite' name='listArticle[quantite][]' value='1'></td>
                        <td data-label="Date D'expiration"><input type='date' id='article_d_EX' class='form-control first-input dateInput' name='listArticle[dateDEX][]' value='<?php echo date('Y-m-d'); ?>'></td>
                        <td data-label="Date D'autorisation"><input type='date' id='article_d_OT' class='form-control inputentree first-input dateInput' name='listArticle[dateDOT][]' value='<?php echo date('Y-m-d'); ?>'></td>
                        <td data-label="Magasin"><input class='inputgri' type="text" ></td>
                        <td data-label='Magasin'><select name='magasin' id='selectMagasin'></select></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>

                                                  <!-- end table -->

                                                  <!-- 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="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="table">
                                                        <thead>
                                                            <tr>
                                                                <th>Code Article</th>
                                                                <th>Nom Article</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                        </tbody>
                                                    </table>
                                                    <!-- end table -->
                                                        </div>
                                                        </div>
                                                    </div>
                                                    </div>
                                                <!-- end Modal -->
                                            <!-- 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 -->
                                            <!--  Radio -->
                                             <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="profile-tab">
                                                    <div class="form-outline"> <label class="form-label" for="typeNumber" ></label> </div>
                                                    <div class="col-md-4"></div>
                                                    <div class="input-group2"> <div class="input-group"> </div> </div>
                                                    <div class="col-md-4"></div></div>                                          
                                                <!--  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>Code Project</th>
                                                                    <th>Description</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                            </tbody>
                                                    </table>
                                                  <!-- end table -->
                                                    </div>
                                                    </div>
                                                </div>
                                            </div>
                                                <!-- end Modal projet-->
                                            <!-- end Radio -->
                                            <!-- End Historique -->
                                            <div class="d-flex justify-content-end buttonEnd">
                                                <button  type="submit" name="creer" id="creer"  class="btn btn-primary mb-3 button createMar">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>
  function enableDisabledInput() {
    var disabledInput = document.querySelector('input[name="codeClient"]');
    disabledInput.disabled = false;
    }
    </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>
    var item = 0;
    var item1 = 0;
    var item2 = 0;  
    var codeClient;
    var nomclient;
    var codeProject;
    var codeArticle;
    var incrementCode;
    $(document).ready(function() {
            $('.createMar').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();
                                // $('messageAlert').delay(1500).fadeOut();
                         }
                        });
            });
    $(document).ready(function() {
        // var date=$('.dateDoc').val(new Date().toDateInputValue());
        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 wrapper   		= $(".input-group2");
        var add_button2      = $(".add_field_button2");
        var Y = -1;
        $(add_button2).click(function(e){ 
        e.preventDefault();
                Y++;
                $(wrapper).append('<div class="input-group mb-3"><div class="col-xs-2"><input readonly type="text" class="form-control mb-3" id="radio_'+Y+'" name="Radio[ItemCode][]" placeholder="Radiographie "> </div><button type="button" id='+Y+' onclick="add1(this)" class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#staticBackdrop1">+</button><input type="text" id="RadioDescription_'+Y+'" name="Radio[ItemName][]" class="form-control mb-3 " placeholder="Description" /><input id="RadioInstruction_'+Y+'" type="text" class="form-control mb-3" name="Radio[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(); Y--;
        });
    });
    $(document).ready(function() {
            var wrapper = $(".input-group3");
            var add_button3 = $(".add_field_button3");
            var z = -1;
            $(add_button3).click(function(e) {
                e.preventDefault();
                z++;
                $(wrapper).append('<div class="input-group mb-3">  <div class="col-xs-2"><input readonly type="text" class="form-control mb-3 " id="analyse_'+z+'" name="Analyse[ItemCode][]" placeholder="Analyse "> </div><button type="button" id='+z+' onclick="add2(this)" class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#staticBackdrop2">+</button><input type="text" id="AnalyseDescription_'+z+'" name="Analyse[ItemName][]" class="form-control mb-3 " placeholder="Description" /><input id="AnalyseInstruction_'+z+'" type="text" class="form-control mb-3" name="Analyse[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(); z--;
            });
             
            // var dataArray = []; // Declare the array outside the success callback
// ---------------------------------
// $.ajax({
//   url: 'ServiceLayer/getWareHouse.php',
//   dataType: 'json',
//   success: function(response) {
//     $.each(response.value, function(index, item) {
//       var warehouseCode = item.WarehouseCode;
//       var warehouseName = item.WarehouseName;

//       var data = {
//         warehouseCode: warehouseCode,
//         warehouseName: warehouseName
//       };

//       dataArray.push(data);
//     });

//     // You can access the dataArray here or perform any other operations
//     console.log(dataArray);
//     doSomethingWithData(dataArray);
//   },
//   error: function() {
//     console.log('Error loading data');
//   }
// });

// console.log('dataArray=>'+dataArray);
// -------------------------------------------
    });
        $('#consultation').click(function(){
            var clientIn = $("#PCode").val();
             var projectIn = $("#projectvalue").val();
            if(clientIn==="" && projectIn===""){
                $('#staticBackdrop_').modal('hide');
            }else{
                $('#staticBackdrop_').modal('show');
            }
        });
    //load combobox magasin using ajax
  
    $(document).ready(function () {     
             var clientIn = $("#PCode").val();
             var projectIn = $("#projectvalue").val();
            if(clientIn==="" && projectIn===""){
                $('#staticBackdrop_').modal('hide');
            }else{
                $('#staticBackdrop_').modal('show');
            }

        var table = $('#table').DataTable({  
            ajax: {                
                url: 'ServiceLayer/GetItems.php',  
                dataSrc: "",
                data: {
                    "Groupe": "Consultation"
                }
            },
            "autoWidth": false,
            "bDestroy": true,
                columns: 
                [   
                    // liste d'article 
                    { data: 'ItemCode' },
                    { data: 'ItemName' },
                    { data: 'ManageBatchNumbers' } 
                ],
        });
        var i=0;
        var p=0;
        var cmpt=0;
        var check=false;
        var incrementCode=0; 
        var code;
        var globalDataResponse;
        var selectedDate = $("#PName").val();
        var dateComponents = selectedDate.split('-');
        var dayMonth = dateComponents[2] + '-' + dateComponents[1];
        var year = dateComponents[0].slice(-2);
        var formattedDate = dayMonth +''+ year;
        var dateDoc=formattedDate.replace("-", "");
                //console.log('format date=>'+datFixLot);
         //this page EntreeStock
        //  function magasin(){
        //                 var selectElement = $('#selectMagasin');
        //                 $.ajax({
        //                     url: 'ServiceLayer/getWareHouse.php', 
        //                     dataType: 'json', 
        //                     success: function(response) {
        //                         //console.log(response);
        //                         selectElement.empty();
        //                         response.forEach(function(item) {
        //                             var warehouseCode = item.WarehouseCode;
        //                             var warehouseName = item.WarehouseName;
        //                             var option="<option id='"+warehouseCode+"' value='"+warehouseName+"'>"+warehouseName+"</option>";
        //                                 selectElement.append(option);
        //                                 console.log('the warehouseCode is->'+warehouseCode+'the warehouseName is->'+warehouseName);
        //                         });
        //                     },
        //                     error: function() {
        //                     console.log('Error loading data in select magasin');
        //                     }
        //                 });
        //         }; 
         $('#table tbody').on('dblclick', 'tr', function () {
             var  data= table.row(this).data();
                 codeArticle=data['ItemCode'];
                 //console.log("code client "+codeClient+" code projet "+codeProject+')))'+data['ItemCode']);
                $('.loader').show();
              //send data to get response
              $.ajax({
                    url: 'ServiceLayer/GetIncrim.php',
                    method: 'POST',
                    data: {
                       // article:data['ItemCode'],
                        dated:dateDoc,
                        client:codeClient,
                        projet:codeProject
                    },
                    success: getResponse
                }); 
                //location.replace('ServiceLayer/GetIncrim.php');
            //   date for lot
                var selectedDate = $("#PName").val();
                var dateComponents = selectedDate.split('-');
                var dayMonth = dateComponents[2] + '-' + dateComponents[1];
                var year = dateComponents[0].slice(-2);
                var formattedDate = dayMonth +''+ year;
                var datFixLot=formattedDate.replace("-", "");
                console.log('format date=>'+datFixLot);
                var lotInfo=0;
                var result;
                var clientCheck;
                var projetCheck;

                //console.log(datDoc);
                function getResponse(response) {
                        result = response;                   
                        console.log(response);
                        if(codeClient.length===0 && codeProject.length===0){
                            $('.loader').hide();
                            alert('Client/Projet=>VIDE');
                        }
                        if (result && result.value && result.value.length === 0) {
                            console.log('Value is empty');
                            //p++;
                            cmpt=0;
                        }
                        else {
                            console.log('firs code incrementation from response=>'+JSON.stringify(Number(result.value[0].incr)));
                            p=JSON.stringify(Number(result.value[0].incr));
                            console.log("p is response ="+p);
                            // 
                            // console.log('1=>'+response.value.incr);
                            // console.log('2=>'+Number(response.value[0].incr));
                        }                 
                    var managerIncrement=data['ManageBatchNumbers'];                     
                          if(managerIncrement==='tYES'){   
                            // initialisation array
                                            p++;  
                                            p=p+cmpt;
                                            cmpt++;
                                            console.log(' n:=>'+p);
                                          if(p<10){
                                          var nextValue= (parseInt(p, 10) ).toString().padStart(p.length, "0");
                                          // console.log('increment code=>00'+nextValue); // Output: "001"
                                          lotInfo=codeClient.toString()+'-'+codeProject.toString()+'-'+datFixLot+'-'+'00'+nextValue.toString();
                                          console.log('p{10}=>'+lotInfo);
                                          }
                                         if(p>=10  && p<100){
                                          var nextValue= (parseInt(p, 10)).toString().padStart(p.length, "0");
                                          lotInfo=codeClient.toString()+'-'+codeProject.toString()+'-'+datFixLot+'-'+'0'+nextValue.toString();
                                          console.log('10}p{100=>'+lotInfo);
                                          }
                                          if(p>=100 && p<1000){
                                              console.log('This Code =>>>'+p);
                                              var nextValue= (parseInt(p, 10)).toString().padStart(p.length, "0");
                                              lotInfo=codeClient.toString()+'-'+codeProject.toString()+'-'+datFixLot+'-'+nextValue.toString();
                                              console.log('100}p{1000=>'+lotInfo);
                                          }
                          } 
                          else { //tNO                             
                              if (p==0)
                              {
                                  console.log("p = " +p);
                                  p=1;
                              }                
                                if(p<10){
                                          var nextValue= (parseInt(p, 10) ).toString().padStart(p.length, "0");
                                          lotInfo=codeClient.toString()+'-'+codeProject.toString()+'-'+datFixLot+'-'+'00'+nextValue.toString();
                                          console.log('p{10}=>'+lotInfo);
                                          }
                                          if(p>=10  && p<100){
                                          var nextValue= (parseInt(p, 10)).toString().padStart(p.length, "0");
                                          lotInfo=codeClient.toString()+'-'+codeProject.toString()+'-'+datFixLot+'-'+'0'+nextValue.toString();
                                          console.log('10}p{100=>'+lotInfo);
                                          }
                                          if(p>=100 && p<1000){
                                              console.log('This Code =>>>'+p);
                                              var nextValue= (parseInt(p, 10)).toString().padStart(p.length, "0");
                                              lotInfo=codeClient.toString()+'-'+codeProject.toString()+'-'+datFixLot+'-'+nextValue.toString();
                                              console.log('100}p{1000=>'+lotInfo);
                                          }            
                          }
                         
                          $('.loader').hide();
                          i++;
                          //console.log(lotInfo);
                          $('#staticBackdrop_').modal('hide');
                          $('body').removeClass('modal-open');
                          $('.modal-backdrop_').remove();
                          console.log('this is the LOT:'+lotInfo);
                       
                        //   -----------------------------------
                        var ligne='<tr>';
                        ligne+="<td data-label='Code Article'><input type='text' class='form-control  first-input input_id inputGod' id='article_Consultation' name='listArticle[idArticle][]' value='"+data["ItemCode"]+"'></td>";
                        ligne+="<td data-label='Description'><input type='text' id='article_ConDescription' name='listArticle[description][]' class='form-control  first-input inputGod' value='"+data["ItemName"]+"'></td>";
                        ligne+="<td data-label='Numéro De Lot'><input type='text' style='width:300px' id='article_lot' readonly='readonly' name='listArticle[lot_p][]' class='form-control  first-input inputgri inputGod' value='"+lotInfo+"' ></td>";
                        ligne+="<td data-label='Quantité'><input type='text' style='width:100px' class='form-control  first-input ' id='article_quantite inputGod' name='listArticle[quantite][]' value='1'></td>";
                        ligne+='<td data-label=" Nombre De Palétte"><input type="number" id="nbr_palette" class="form-control nbr_palette" name="listArticle[NbrPallette][]" value=""></td>';
                        ligne+="<td data-label='Date D'expiration'><input type='date' id='article_d_EX' class='form-control first-input dateInput' name='listArticle[dateDEX][]' value='<?php echo date('Y-m-d'); ?>'></td>";
                        ligne+="<td data-label='Date D'autorisation'><input type='date' id='article_d_OT' class='form-control inputentree first-input dateInput' name='listArticle[dateDOT][]' value='<?php echo date('Y-m-d'); ?>'></td>";
                                              

                        ligne += '<td class="btn_add_selectMagasin" data-label="Magasin" style="display:flex;justify-content:center"><input id="selectMagasin" style="margin-top:10px;margin-right:5px;" class="form-control inputgri numero-de-lot" type="text" name="listArticle[selectMagasin][]" value=""> <button style="" type="button" id="plusWhs" class="btn btn-primary mb-3 btn_add_Whs" data-bs-toggle="modal" data-bs-target="#staticBackdrop_Whs">+</button>';
                                 
                        ligne+="<td data-label='edit'>";
                        ligne+="<div class='icon_edit'>";
                        ligne+="<a class='delete'><i class='fa-solid fa-trash'></i></a>"; 
                        ligne+="</div>";
                        ligne+="</td>";
                        // -------------------------------------
                          //$("#contenuArticle").append("<div id='"+i+"' class='contenuInput inputdateEx'><div class='col-lg-2 '><input type='text' class='form-control mb-3 first-input input_id' id='article_Consultation' name='listArticle[idArticle][]' value='"+data["ItemCode"]+"'></div><div class='col-lg-2 '><input type='text' id='article_ConDescription' name='listArticle[description][]' class='form-control mb-3 first-input' value='"+data["ItemName"]+"'></div><div class='col-lg-2 '><input type='text' class='form-control mb-3 first-input ' id='article_quantite' name='listArticle[quantite][]' value='1'> </div><div class='col-lg-2 '><input type='text' id='article_lot' readonly='readonly' name='listArticle[lot_p][]' class='form-control mb-3 first-input inputgri' value='"+lotInfo.toString()+"' > </div><div class='col-lg-2 '><input type='date' id='article_d_OT' class='form-control inputentree first-input dateInput' name='listArticle[dateDOT][]' value='<?php echo date('Y-m-d'); ?>'></div><div class='col-lg-2 '><input type='date' id='article_d_EX' class='form-control first-input dateInput' name='listArticle[dateDEX][]' value='<?php echo date('Y-m-d'); ?>'></div><div class='col-lg-2 '> <a id='"+i+"' class='delete_art deleteDiv'> <i id='"+i+"' class='fa-solid fa-trash delete_art'></i></a></div></div>");    
                          $("#Tbody").append(ligne);
                         // magasin();
                        }   
                       
            });       
            

             // delete article
              var divDelete = $("#contenuArticle");
              $(divDelete).on("click",".delete_art", function(e){ 
                e.preventDefault(); $(this).parent('div').parent('div').remove();
                 i--;//$check=true;
              });         
               //Delete row Attach click event handler to delete buttons
            $('#id_tabe_Article').on('click', '.delete', function() {
                var row = $(this).closest('tr');
                row.remove();i--;
            });  
    });
    
    $(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]);
            });            
        });


    // get client
    $(document).ready(function () {
        var table = $('#table_Client').DataTable({  
            ajax: {                
                url: 'ServiceLayer/GetClient.php',  
                dataSrc: "",
                data: {
                    "Groupe": "" //Consultation
                }
            },
            "autoWidth": false,
            "bDestroy": true,
                columns: 
                [   
                    // liste Client
                    { data: 'CardCode' },
                    { data: 'CardName' }
                ],
        });
        $('#table_Client tbody').on('dblclick', 'tr', function () {    
            var data = table.row(this).data();
            // $('#orm').val(data[1]); 
           // console.log(data["CardCode"]);
            $('#staticBackdrop').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            $('#staticBackdrop').on('hidden.bs.modal', function() {
            $(this).removeData('bs.modal');
            $('#PCode').val(data["CardCode"]+'-'+data["CardName"]);
            console.log( $('#PCode').val());
            nomclient=data["CardName"];
            codeClient=data["CardCode"];
            
        //  $_SESSION['client']=data["CardCode"];
            // $.ajax({
            //     url: 'ServiceLayer/getProject.php',
            //     type: 'POST',
            //     data: { codeClientGet:codeClient },
            //     success: function(response) {
            //         console.log(response);
            //     },
            //     error: function(xhr, status, error) {
            //         console.log(error);
            //     }
            // });
      //     location.replace('ServiceLayer/getProject.php');
            });     
        });    
        // 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
      
    })
    // get article
    $(document).ready(function () {
        var table = $('#table2').DataTable({  
            ajax: {                
                url: 'ServiceLayer/GetItems.php',  
                dataSrc: "",
                data: {
                    "Groupe": "Radio"
                }
            },
            "autoWidth": false,
            "bDestroy": true,
                columns: 
                [
                    { data: 'ItemCode' },
                    { data: 'ItemName' }
                ],
        });
        
    });

    $(document).ready(function () {
        var clientIn=document.getElementById("PCode");
        var projectIn=document.getElementById("projectvalue");             
            $("#Consultation").addClass("active");
            // if(clientIn!='' AND projectIn!=''){
                $("#Dashboard").removeClass("active");
            var table = $('#table3').DataTable({  
                ajax: {                
                    url: 'ServiceLayer/GetItems.php',  
                    dataSrc: "",
                    data: {
                        "Groupe": "Analyse"
                    }
                },
                "autoWidth": false,
                "bDestroy": true,
                    columns: 
                    [
                        { data: 'ItemCode' },
                        { data: 'ItemName' }
                    ],     
              });
              $('#table3 tbody').on('dblclick', 'tr', function () {
            
            var data = table.row(this).data();
            //$('#an').val(data[1]); 
            $('#staticBackdrop2').modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
            $('#staticBackdrop2').on('hidden.bs.modal', function() {
                $(this).removeData('bs.modal');
                $('#analyse_'+item2).val(data["ItemCode"]);
                $('#AnalyseDescription_'+item2).val(data["ItemName"]);
            });            
        });

        // load select using ajax 
       
        // ---------------
        const queryString = window.location.search;
        const DocEntry = new URLSearchParams(queryString).get('DocEntry'); 
        
    });
    

    function add1(raa){
        item1 =  $(raa).attr('id');
    }

    function add2(anal){
        item2 =  $(anal).attr('id');
    }
    
    function add(or){
        item =  $(or).attr('id');
    } 


   

        $('#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]);
            });            
        });

</script>
</body>
</html>