  
<div class="corps">
    <div class="card">
        <div class="head-main">
            <h2>Edition</h2>
            <a href="/">
                <button class="button-planning">
                    <!--<img src="/images/planning.png" class="svg-icon" alt="">-->
                    <ion-icon name="home-outline"></ion-icon>
                    <span class="label">Accueil</span>
                </button>
            </a>
        </div>
      <div class="card-body">
        <!-- <h4 class="card-title">Formulaire d'edition</h4> -->
        <form method="POST" action="/employee/update" enctype="multipart/form-data" class="form-sample g-3 needs-validation">
          <input type="hidden" name="id" value="<%= employee.id %>">          
          <!-- PROFIL -->
          <div class="row profil-container">  
            <div class="col-md-9">
              <h3>Profil</h3>
            </div>
            <div class="col-md-3">
              <% if(!photo) { %> 
                <label for="inputProfil">Insérer un photo</label>
                <input type="file" name="photo" id="inputProfil" accept=".jpeg, .jpg, .png, .img" >
              <% } else { %>
              <div class="profil">
                <input type="hidden" name="idPhoto" value="<%= photo.id %>">
                <img src="<%= photo.path %>" alt="Photo de profil">
                <div class="dropdown-profil">
                  <span id="toggle-profil"><ion-icon name="ellipsis-vertical-outline"></ion-icon></span>
                  <ul class="menu-profil">
                    <li>
                      <label for="changeProfil">Modifier</label>
                      <input type="file" name="photo" id="changeProfil" accept=".jpeg, .jpg, .png, .img" >
                    </li>
                    <!-- <li>Supprimer</li> -->
                  </ul>
                </div>                
              </div>            
              <% } %>
            </div>          
          </div>
          <div class="row">
            <div class="col-md-2">
              <div class="form-group">
                <label for="matricule">Matricule</label>                
                <input type="text" value="<%= employee.matricule %>" class="form-control form-control-sm" name="matricule"  maxlength="3" maxlength="13" readonly/>                                                
              </div> 
            </div>
            <div class="col-md-5">
              <div class="form-group">
                <label for="idNomEmployer">Nom</label>                
                <input type="text" id="idNomEmployer" value="<%= employee.name_employee %>" name="nameEmployee" placeholder="RAKOTO" class="form-control form-control-sm" required/>
              </div>            
            </div>
            <div class="col-md-5">
              <div class="form-group">
                <label>Prénom(s)</label>                
                <input type="text" value="<%= employee.last_name_employee %>" class="form-control form-control-sm" name="lastNameEmployee" placeholder="Mamiratra"/>               
              </div>
            </div>               
            <div class="col-md-2">
              <div class="form-group">
                <label>Genre</label>                
                <select class="form-control form-control-sm" required name="sexEmployee">
                  <option <% if(employee.sexe_employee === 'M') { %>selected <% } %> value="M">Masculin</option>
                  <option <% if(employee.sexe_employee === 'F') { %>selected <% } %> value="F">Féminin</option>
                </select>
              </div>
            </div>            
            <% if(!cv) { %> 
            <div class="col-md-2">
              <div class="form-group">
                <br>
                <label for="cv">Inser. CV</label>
                <input type="file" class="form-control form-control-sm" id="cv" name="cv"/>
              </div>
            </div>
            <% } else { %>
              <div class="col-md-2">
                <div class="form-group">
                  <br>
                  <a href="/employee/cv/<%= employee.id %>"><div class="btn-view-cv">Voir le CV</div></a>
                </div>
              </div>
            <% } %>
            <div class="col-md-3">
              <div class="form-group">
                <label>Date de naissance</label>                
                <input type="date" class="form-control form-control-sm" value="<%= employee.birth_employee %>"  name="ddnEmployee"/>                
              </div>
            </div>
            <div class="col-md-5">
              <div class="form-group">
                <label for="idLieuDdn">à</label>                
                <input type="text" name="placeDdnEmployee" value="<%= employee.birth_place_employee %>" class="form-control form-control-sm" id="idLieuDdn" placeholder="Ambatolampy" />                
              </div>
            </div>                        
          </div>          
  
          <!-- ADRESSE -->
          <h3>Adresse</h3>
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label>Adresse</label>                
                <input type="text" class="form-control form-control-sm" value="<%= employee.address_employee %>"  name="addrEmployee"/>                
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label>Ville</label>                
                <input type="text" value="<%= employee.ville_employee %>" class="form-control form-control-sm" name="villeEmployee"/>                
              </div>
            </div>
          </div>
  
          <!-- CIN -->
          <h3>CIN</h3>
          <div class="row">
            <div class="col-md-4">
              <div class="form-group">
                <label>Numéro CIN </label>                
                <input 
                    type="text" 
                    class="form-control form-control-sm" 
                    name="CINEmployee" 
                    minlength="12" 
                    maxlength="15"                     
                    placeholder="102 001 123 456 789"
                    value="<%= employee.cinemployee %>"                    
                  />                                  
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label>Date</label>                
                <input type="date" value="<%= employee.date_cinemployee %>" class="form-control form-control-sm"  name="dateCINEmployee"/>                
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label>Lieu</label>                
                <input type="text" class="form-control form-control-sm" value="<%= employee.cinplace_employee %>"  name="placeCINEmployee"/>                
              </div>
            </div>
          </div>
  
          <h3>Situation matrimonial</h3>
          <div class="row">                        
            <div class="col-md-6">
              <div class="form-group ms-4">
                <div class="form-check">
                  <input type="radio" class="form-check-input" <% if(employee.marital_status_employee === 'single') {%> checked <% } %> name="martialStatus" id="optionsRadios1" value="single" >
                  <label class="form-check-label" for="optionsRadios1">Célibataire</label>
                </div>
                <div class="form-check">
                  <input type="radio" class="form-check-input" <% if(employee.marital_status_employee === 'married') {%> checked <% } %>  name="martialStatus" id="optionsRadios2" value="married" >
                  <label for="optionsRadios2" class="form-check-label">Marié(e)</label>
                </div>          
                <div class="form-check">
                  <input type="radio" <% if(employee.marital_status_employee === 'divorced') {%> checked <% } %>  class="form-check-input" name="martialStatus" id="optionsRadios3" value="divorced" >
                  <label for="optionsRadios3" class="form-check-label">Divorcé(e)</label>
                </div>          
              </div>
            </div>

            <div class="col-md-6">

              <div class="form-group">
                <label>Nombre d'enfant(s):</label>                
                <select name="nbrChild" class="form-select" id="nombreEnfants" aria-label="size 3 select example">
                  <option <% if(employee.nbr_child === 0) {%> selected <% } %> value="0">0</option>
                  <option <% if(employee.nbr_child === 1) {%> selected <% } %> value="1">1</option>                                        
                  <option <% if(employee.nbr_child === 2) {%> selected <% } %> value="2">2</option>                                        
                  <option <% if(employee.nbr_child === 3) {%> selected <% } %> value="3">3</option>                                        
                  <option <% if(employee.nbr_child === 4) {%> selected <% } %> value="4">4</option>                                        
                  <option <% if(employee.nbr_child === 5) {%> selected <% } %> value="5">5</option>                                        
                  <option <% if(employee.nbr_child === 6) {%> selected <% } %> value="6">6</option>                                        
                </select>
              </div>                                
            </div>
          </div>
          <div id="formEnfants" class="row">
              <!-- Les formulaires pour les enfants seront générés ici -->
          </div>            
  
            
  
          <h3>Conctact</h3>
          <div class="row">
            <div class="col-md-3">
              <div class="form-group">
                <label>Airtel</label>                
                <input type="tel" class="form-control form-control-sm" value="<%= employee.contact_airtel %>" name="contactAirtel" minlength="9" maxlength="13" placeholder="033 12 345 67"/>                  
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Telma</label>                
                <input type="tel" class="form-control form-control-sm" value="<%= employee.contact_telma %>" name="contactTelma" minlength="9" maxlength="13" placeholder="034 12 345 67">                  
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Orange</label>                
                <input type="tel" class="form-control form-control-sm" value="<%= employee.contact_orange %>" name="contactOrange" minlength="9" maxlength="13" placeholder="032 12 345 67"/>                
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Flotte</label>                
                <input type="tel" value="<%= employee.contact_flotte %>" class="form-control form-control-sm" name="contactFlotte"/>                
              </div>
            </div>                
          </div>                              
          <h3>Congé</h3>
          <div class="row">            
            <% if( employee.post.role == '') { %>
            
              <!-- Pour les sans roles, il a besoin d'un user ou autre demandeur -->
              <input type="hidden" name="role" value="<%= employee.post.role %>">
              <div class="col-md-4">
                <div class="form-group">
                  <label for="applicant">Demandeur</label>                
                  <select name="applicant" id="applicant" class="form-select form-select-sm">
                    <option value="superieur" selected>Tous les supérieurs</option>
                    <% admins.forEach(admin => { %>
                      <% if (admin.role == 'User' || admin.role == 'Admin') { %>
                        <%= employee.admin %>
                        <option value="<%= admin.id %>" <%= employee.admin %> <% if(admin.id == employee.admin) { %> selected <% } %> ><%= admin.firstName %> <%= admin.lastName %></option>
                      <% } %>
                    <% }); %>
                  </select>
                </div>
              </div>          
            <% } else { %>

              <!-- L'user ou admin ou manager ou super admin -->            
              <input type="hidden" name="postId" value="<%= employee.post.id %>">
              <input type="hidden" name="role" value="<%= employee.post.role %>">                          
            <% } %>

            <div class="col-md-4">
              <div class="form-group">
                <label>Nombre d'intérimaire(s):</label>     
                <select name="nbrInterim" class="form-select form-select-sm" id="nombreInterim" aria-label="size 3 select example">
                  <option <% if(employee.nbr_interims === 0) {%> selected <% } %> value="0">0</option>
                  <option <% if(employee.nbr_interims === 1) {%> selected <% } %> value="1">1</option>                                        
                  <option <% if(employee.nbr_interims === 2) {%> selected <% } %> value="2">2</option>                                                          
                  <option <% if(employee.nbr_interims === 3) {%> selected <% } %> value="3">3</option>                                                          
                </select>
              </div>                                
            </div>
          </div>      
          <div id="formInterim" class="row">
             
          </div> 
          
    
          <h3>Autres</h3>
          <div class="row">            
              <div class="col-md-2">
                <div class="form-group">
                  <label  for="numeroCNAPS">Date d'embauche </label>                  
                  <input type="date" id="hiringDate" value="<%= employee.hiring_date %>" class="form-control form-control-sm" name="hiringDate" />                  
                </div>
              </div>    
              <div class="col-md-3">
                <div class="form-group">
                  <label for="fonction">Sélectionnez une fonction</label>
                  <select class="form-select form-select-sm" id="function" name="function" >
                    <option value="0">Sélectionnez une fonction</option>
                    <% fonctions.forEach(function(fonction) { %>                  
                      <option <% if(employee.fonction === fonction.id) {%> selected <% } %> value="<%= fonction.id %>"><%= fonction.nameFunction %></option>
                    <% }); %>
                  </select>
                </div>
              </div>     
              <div class="col-md-2">
                <div class="form-group">
                  <label for="dateFunct">Date de début</label>
                  <input type="date" class="form-control form-control-sm" name="dateFunct" id="dateFunct" value=<%= employee.dateFunct %>>
                </div>
              </div>  
              <div class="col-md-3">
                <!-- <div class="form-group">
                  <label for="fonction">Chef</label>
                  <select class="form-control form-control-sm" id="function" name="boss">
                    <option value="0">Sélectionnez un chef</option>
                    <%// admins.forEach(function(admin) { %>
                      <option value="<%= //admin.id %>"><%= //admin.firstName %> <%= //admin.lastName %></option>
                    <%// }); %>
                  </select>
                </div> -->
                <div class="form-group">              
                  <label for="category">Catégorie</label>
                  <input type="text" name="category" value="<%= employee.category%>" class="form-control form-control-sm" id="category">
                </div>
              </div>            
              <div class="col-md-2">                
                <div class="form-group">
                  <label for="numeroCNAPS">Numéro CNAPS </label>                  
                  <input type="text" id="numeroCNAPS" value="<%= employee.num_cnaps %>" class="form-control form-control-sm" name="numCNAPS"/>                  
                </div>                
              </div>   
          </div>          
          <div class="row">
            <div class="col-md-3">
              <div class="form-group">
                <label >Permis de conduire</label>
                <select name="permisDeConduire" class="form-select form-select-sm" aria-label="size 3 select example">
                  <option <% if(employee.driver_licence === 'Aucun') {%> selected <% } %> >Aucun</option>
                  <option <% if(employee.driver_licence === 'A') {%> selected <% } %> value="A">A</option>                      
                  <option <% if(employee.driver_licence === 'B') {%> selected <% } %>  value="B">B</option>
                  <option <% if(employee.driver_licence === 'A,B') {%> selected <% } %> value="A,B">A,B</option>
                  <option <% if(employee.driver_licence === 'B,C') {%> selected <% } %> value="B,C">B,C</option>
                  <option <% if(employee.driver_licence === 'A,B,C') {%> selected <% } %> value="A,B,C">A,B,C</option>
                  <option <% if(employee.driver_licence === 'B,D') {%> selected <% } %> value="B,D">B,D</option>
                  <option <% if(employee.driver_licence === 'A,B,D') {%> selected <% } %> value="A,B,D">A,B,D</option>
                  <option <% if(employee.driver_licence === 'A,B,C,D') {%> selected <% } %> value="A,B,C,D">A,C,B,D</option>
                  <option <% if(employee.driver_licence === 'B,E') {%> selected <% } %> value="B,E">B,E</option>
                  <option <% if(employee.driver_licence === 'A,B,E') {%> selected <% } %> value="A,B,E">A,B,E</option>
                  <option <% if(employee.driver_licence === 'A,B,C,E') {%> selected <% } %> value="A,B,C,E">A,B,C,E</option>
                  <option <% if(employee.driver_licence === 'B,C,D,E,F') {%> selected <% } %> value="B,C,D,E,F">A,B,C,D,E</option>
                  <option <% if(employee.driver_licence === 'A,B,C,D,E') {%> selected <% } %> value="A,B,C,D,E">A,B,C,D,E</option>
                  <option <% if(employee.driver_licence === 'complet') {%> selected <% } %> value="complet">Complet</option>
                </select>
              </div>
            </div>                    
            <div class="col-md-3">
              <div class="form-group">
                <label >Maladie héréditaire</label>
                <input type="text" value="<%= employee.hereditary_illness %>" class="form-control form-control-sm" name="heredIllness"/>                
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Personne d'urgence</label>                
                <input type="text" value="<%= employee.person_contact_emergency %>" class="form-control form-control-sm" name="personContactEmergency" />                              
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label>Contact</label>                
                  <input type="tel" value="<%= employee.contact_person_emergency %>" class="form-control form-control-sm" name="contactPersonEmergency" minlength="9" maxlength="13" />
              </div>
            </div>                  
          </div>
          <div class="row justify-content-end">
            <div class="col-md-6 text-end">
              <button type="submit" class="btn btn-primary">Enregistrer</button>
              <button class="btn btn-light">Annuler</button>
            </div>
          </div>
          
        </form>
      </div>
    </div>
  </div>  

  <script>
    let employees = [];
    let interims = [];
  </script>

  <% employees.forEach( value=> { %>
    <script>
      employee = {}; 
      employee.id = parseInt("<%= value.id %>");
      employee.matricule = "<%= value.matricule %>";
      employee.nom = "<%= value.name_employee %>";
      employee.prenom = "<%= value.last_name_employee %>";                              
      employees.push(employee);
    </script>
  <% }) %>

  <% employee.interims.forEach( value => {%>
    <script>
      interim = {};
      interim.id = "<%= value.id %>"
      interim.interimId = "<%= value.interimId %>";
      interim.nom = "<%= value.nom %>";      
      interims.push(interim);      
    </script>
  <% }); %>
  
  <script>
    let nbrInterimInput = document.getElementById('nombreInterim');
    let nbrInterim = parseInt(nbrInterimInput.value);
    let formInterim = document.getElementById('formInterim');
    
    for (var i = 1; i <= nbrInterim; i++) {       
      var cardDiv = document.createElement('div');
      cardDiv.className = 'col-md-6 mt-4'; 
    
      var cardHeader = document.createElement('div');
      cardHeader.className = 'card-header';
      cardHeader.textContent = 'Intérimaire ' + i;
  
      var cardBody = document.createElement('div');
      cardBody.className = 'card-body';

      let idInterim = document.createElement('input');
      idInterim.setAttribute('type', 'hidden');
      idInterim.setAttribute('name', 'idInterim');
      idInterim.id = 'idInterim ' + i;
      idInterim.value = interims[i-1].id ?? 0;

      let interimIdInput = document.createElement('input');
      interimIdInput.setAttribute('type', 'hidden');
      interimIdInput.setAttribute('name', 'interimId');
      interimIdInput.id = 'interimId ' + i;
      interimIdInput.value = interims[i-1].interimId;

      let nomInterimLabel = document.createElement('label');
      nomInterimLabel.setAttribute('for', 'name_interim');
      nomInterimLabel.textContent = 'Nom et prénom(s) intérimaire';
                
      let nomInterim = document.createElement('input');
      nomInterim.setAttribute('type', 'text');
      nomInterim.readonly = true;
      nomInterim.className = "form-control form-control-sm";
      nomInterim.id = "name_interim " + i;
      nomInterim.readOnly = true;
      nomInterim.value = interims[i-1].nom;              
  
      cardBody.appendChild(idInterim);
      cardBody.appendChild(interimIdInput);
      cardBody.appendChild(nomInterimLabel);
      cardBody.appendChild(nomInterim);

      //Bouton supprimer    
      var btnSuppr = document.createElement('button');
      btnSuppr.className = "btn btn-reaction ms-auto";
      btnSuppr.id = "btn " + interims[i-1].id;
      btnSuppr.setAttribute('data-title', 'Supprimer');    
      btnSuppr.setAttribute('data-interim-id', interims[i-1].id);  
      var icon = document.createElement('i');
      icon.className = "mdi mdi-delete custom-icon-delete";        
      btnSuppr.appendChild(icon);
      cardHeader.appendChild(btnSuppr);
      
      cardDiv.appendChild(cardHeader);
      cardDiv.appendChild(cardBody);
  
      formInterim.appendChild(cardDiv);

      // Ajoutez un écouteur d'événement sur le clic du bouton
      let btnSupprElt = document.getElementById(`btn ${interims[i-1].id}`);
      console.log(btnSupprElt)
      btnSupprElt.addEventListener('click', (event) => {
        event.preventDefault(); // Empêche la soumission du formulaire        

        //  Demande de confirmation de suppression de cet enfant
        const confirmation = confirm("Vous voulez vraiment supprimer l'intérimaire ?");

        if(confirmation) {
          const interimId = btnSupprElt.dataset.interimId; // Récupère l'ID de l'enfant à supprimer                
          console.log(interimId);
          // Effectuez une requête AJAX pour supprimer l'enfant
          fetch(`/employee/interim/${interimId}`, {
            method: 'DELETE',
          })
            .then(response => {          
              if (response.ok) {
                // La suppression de l'enfant a réussi, vous pouvez effectuer des actions supplémentaires si nécessaire
                console.log('interimaire supprimé avec succès');
                //  Recharger la page
                location.reload();
              } else {
                // Gérez les erreurs lors de la suppression de l'enfant
                console.error('Une erreur est survenue lors de la suppression de l\'intérimaire');
              }
            })
            .catch(error => {
              // Gérez les erreurs lors de la requête AJAX
              console.error('Une erreur est survenue lors de la requête AJAX', error);
            });
        }
      });
    }

    nbrInterimInput.addEventListener('change', () => {
      formInterim.innerHTML = '';
      let nbrInterim = parseInt(nbrInterimInput.value);
      
      for(let i = 1; i <= nbrInterim; i++) {
        if(i <= interims.length) {
          var cardDiv = document.createElement('div');
          cardDiv.className = 'col-md-6 mt-4';
        
          var cardHeader = document.createElement('div');
          cardHeader.className = 'card-header';
          cardHeader.textContent = 'Intérimaire ' + i;
      
          var cardBody = document.createElement('div');
          cardBody.className = 'card-body';

          let idInterim = document.createElement('input');
          idInterim.setAttribute('type', 'hidden');
          idInterim.setAttribute('name', 'idInterim');
          idInterim.id = 'idInterim ' + i;
          idInterim.value = interims[i-1].id ?? 0;

          let interimIdInput = document.createElement('input');
          interimIdInput.setAttribute('type', 'hidden');
          interimIdInput.setAttribute('name', 'interimId');
          interimIdInput.id = 'interimId ' + i;
          interimIdInput.value = interims[i-1].interimId;

          let nomInterimLabel = document.createElement('label');
          nomInterimLabel.setAttribute('for', 'name_interim');
          nomInterimLabel.textContent = 'Nom et prénom(s) intérimaire';
                    
          let nomInterim = document.createElement('input');
          nomInterim.setAttribute('type', 'text');
          nomInterim.className = "form-control form-control-sm";
          nomInterim.id = "name_interim " + i;
          nomInterim.value = interims[i-1].nom;              
          nomInterim.readOnly = true;
      
          cardBody.appendChild(idInterim);
          cardBody.appendChild(interimIdInput);          
          cardBody.appendChild(nomInterimLabel);
          cardBody.appendChild(nomInterim);

          //Bouton supprimer    
          var btnSuppr = document.createElement('button');
          btnSuppr.className = "btn btn-reaction ms-auto";
          btnSuppr.id = "btn " + interims[i-1].id;
          btnSuppr.setAttribute('data-title', 'Supprimer');
          btnSuppr.setAttribute('data-interim-id', interims[i-1].id);
          var icon = document.createElement('i');
          icon.className = "mdi mdi-delete custom-icon-delete";        
          btnSuppr.appendChild(icon);
          cardHeader.appendChild(btnSuppr);
          
          cardDiv.appendChild(cardHeader);
          cardDiv.appendChild(cardBody);
      
          formInterim.appendChild(cardDiv);

          // Ajoutez un écouteur d'événement sur le clic du bouton
          let btnSupprElt = document.getElementById(`btn ${interims[i-1].id}`);      
          btnSupprElt.addEventListener('click', (event) => {
            event.preventDefault(); // Empêche la soumission du formulaire

            //  Demande de confirmation de suppression de cet enfant
            const confirmation = confirm("Vous voulez vraiment supprimer l'intérimaire ?");

            if(confirmation) {
              const interimId = btnSupprElt.dataset.interimId; // Récupère l'ID de l'enfant à supprimer      
              // Effectuez une requête AJAX pour supprimer l'enfant
              fetch(`/employee/interim/${interimId}`, {
                method: 'DELETE',
              })
                .then(response => {          
                  if (response.ok) {
                    // La suppression de l'enfant a réussi, vous pouvez effectuer des actions supplémentaires si nécessaire
                    console.log('interimaire supprimé avec succès');
                    //  Recharger la page
                    location.reload();
                  } else {
                    // Gérez les erreurs lors de la suppression de l'enfant
                    console.error('Une erreur est survenue lors de la suppression de l\'intérimaire');
                  }
                })
                .catch(error => {
                  // Gérez les erreurs lors de la requête AJAX
                  console.error('Une erreur est survenue lors de la requête AJAX', error);
                });
              }
          });
      

        } else {
          var cardDiv = document.createElement('div');
          cardDiv.className = 'col-md-6 mt-4'; 
      
          var cardHeader = document.createElement('div');
          cardHeader.className = 'card-header';
          cardHeader.textContent = 'Intérimaire ' + i;
      
          var cardBody = document.createElement('div');
          cardBody.className = 'card-body';

          let idInterim = document.createElement('input');
          idInterim.setAttribute('type', 'hidden');
          idInterim.setAttribute('name', 'idInterim');
          idInterim.id = 'idInterim ' + i;
          idInterim.value = 0;

          let interimIdInput = document.createElement('input');
          interimIdInput.setAttribute('type', 'hidden');
          interimIdInput.setAttribute('name', 'interimId');
          interimIdInput.id = 'interimId ' + i;
          
          let rechInterimLabel = document.createElement('label');
          rechInterimLabel.setAttribute('for', 'name');
          rechInterimLabel.textContent = 'Rech. intérimaire';

          let rechInterim = document.createElement('input');
          rechInterim.setAttribute('type', 'search');
          rechInterim.className = "form-control form-control-sm";
          rechInterim.id = "nom_matricule_interim " + i;

          let nomInterimLabel = document.createElement('label');
          nomInterimLabel.setAttribute('for', 'name_interim');
          nomInterimLabel.textContent = 'Nom et prénom(s) intérimaire';
                    
          let nomInterim = document.createElement('input');
          nombreInterim.setAttribute('type', 'search');
          nomInterim.readonly = true;
          nomInterim.className = "form-control form-control-sm";
          nomInterim.id = "name_interim " + i;              
      
          cardBody.appendChild(idInterim);
          cardBody.appendChild(interimIdInput);
          cardBody.appendChild(rechInterimLabel);
          cardBody.appendChild(rechInterim);
          cardBody.appendChild(nomInterimLabel);
          cardBody.appendChild(nomInterim);
      
          cardDiv.appendChild(cardHeader);
          cardDiv.appendChild(cardBody);
      
          formInterim.appendChild(cardDiv);
          let interimId = document.getElementById(`interimId ${i}`);        
          let name_interim = document.getElementById(`name_interim ${i}`);
          // // let fonction_interim = document.getElementById('fonction_interim');            
          let nom_matricule_interim = document.getElementById(`nom_matricule_interim ${i}`);
      
          // //  Valeur pour le demande avec id et valeur initial pour le demande sans id
          // info_custom.style.display = 'flex';        
      
          nom_matricule_interim.addEventListener('input', () => {
            let value = nom_matricule_interim.value.toLowerCase();          
            for(const employee of employees) {
              const nom = employee.nom.toLowerCase();
              const prenom = employee.prenom.toLowerCase();
              const n_matricule = employee.matricule;
              
              if ((nom.includes(value) || prenom.includes(value) || n_matricule.includes(value))) {        
                interimId.value = employee.id;        
                name_interim.value = employee.nom + ' ' + employee.prenom;                            
              }                    
            }
          });
        }        
      }
    })
  </script>
  



  <script>
    //  Script pour l'import pdp

    // <label for="inputProfil"></label>
    // <input type="file" id="inputProfil" accept=".jpeg, .jpg, .png, .img" >
    const fileInput = document.getElementById('inputProfil');
    const label = document.querySelector('label[for="inputProfil"]');

    if(fileInput) {
      fileInput.addEventListener('change', function() {
      if (fileInput.files.length > 0) {
          //  Changer 'Sélectionnez un fichier Excel ' en nom du fichier
          label.textContent = fileInput.files[0].name;
      } else {
          label.textContent = 'Insérer un photo';
      }
      });
    }

    const cvInput = document.getElementById('cv');
    const labelCv = document.querySelector('label[for="cv"]');
    if(cvInput) {
      cvInput.addEventListener('change', () => {
        if(cvInput.files.length > 0) {
          labelCv.textContent = cvInput.files[0].name;
        }
        else {
          labelCv.textContent = 'Insér. CV'
        }
      });
    }

    const toggleProfil = document.getElementById("toggle-profil");
    const menuProfil = document.querySelector(".menu-profil");    
    toggleProfil.addEventListener('click', (event) => {      
      menuProfil.classList.toggle('show-menu-profil');
    })

    document.addEventListener('click', (event) => {      
      if(!toggleProfil.contains(event.target)) {
        menuProfil.classList.remove('show-menu-profil');
      }
    })
  </script>  

<script>
  var childId = [];
  var ddnChild = [];
  var sexeChild = [];
</script>

<% employee.childs.forEach((child) => {%>
  <script>
      childId.push("<%= child.id %>")
      ddnChild.push("<%= child.birthChild %>");
      sexeChild.push("<%= child.sexe %>");
  </script>
<% }) %>
<!-- nombre enfants  -->
<script>    
    document.addEventListener('DOMContentLoaded', function() {
    var nombreEnfantsInput = document.getElementById('nombreEnfants');
    var formEnfants = document.getElementById('formEnfants');
    var nombreEnfants = parseInt(nombreEnfantsInput.value);
    
    for (var i = 1; i <= nombreEnfants; i++) {       
      var cardDiv = document.createElement('div');
      cardDiv.className = 'col-md-4 mt-4';

      var cardHeader = document.createElement('div');
      cardHeader.className = 'card-header';
      cardHeader.textContent = 'Enfant ' + i; 

      //Bouton supprimer    
      var btnSuppr = document.createElement('button');
      btnSuppr.className = "btn btn-reaction ms-auto";
      btnSuppr.id = "btn " + childId[i-1];
      btnSuppr.setAttribute('data-title', 'Supprimer');
      btnSuppr.setAttribute('data-enfant-id', childId[i-1]);
      var icon = document.createElement('i');
      icon.className = "mdi mdi-delete custom-icon-delete";        
      btnSuppr.appendChild(icon);      

      var cardBody = document.createElement('div');
      cardBody.className = 'card-body';

      var childIdInput = document.createElement('input');
      childIdInput.setAttribute('type', 'hidden');
      childIdInput.setAttribute('name', 'idChild');
      childIdInput.value = childId[i-1] ?? 0;

      var dateNaissanceLabel = document.createElement('label');
      dateNaissanceLabel.setAttribute('for', 'dateNaissanceEnfant' + i);
      dateNaissanceLabel.textContent = 'Date de naissance :';
      
      var dateNaissanceInput = document.createElement('input');
      dateNaissanceInput.setAttribute('type', 'date');
      dateNaissanceInput.className = 'form-control form-control-sm';
      dateNaissanceInput.setAttribute('id', 'dateNaissanceEnfant' + i);
      dateNaissanceInput.setAttribute('name', 'ddnChild');
      dateNaissanceInput.value =  ddnChild[i-1];
      // dateNaissanceInput.required = true;
      var sexeLabel = document.createElement('label');
      sexeLabel.setAttribute('for', 'sexeEnfant' + i);
      sexeLabel.textContent = 'Sexe :';

      var sexeSelect = document.createElement('select');
      sexeSelect.className = 'form-control form-control-sm';
      sexeSelect.setAttribute('id', 'sexeEnfant' + i);
      sexeSelect.setAttribute('name', 'sexeChild');
      // sexeSelect.required = true;

      var optionMasculin = document.createElement('option');
      optionMasculin.value = 'M';
      optionMasculin.textContent = 'Masculin';
      optionMasculin.selected = sexeChild[i-1] === 'M';
      
      var optionFeminin = document.createElement('option');
      optionFeminin.value =  'F';
      optionFeminin.textContent = 'Féminin';
      optionFeminin.selected =  sexeChild[i-1] === "F";

      sexeSelect.appendChild(optionMasculin);
      sexeSelect.appendChild(optionFeminin);

      cardHeader.appendChild(btnSuppr);
      cardBody.appendChild(childIdInput);
      cardBody.appendChild(dateNaissanceLabel);
      cardBody.appendChild(dateNaissanceInput);
      cardBody.appendChild(sexeLabel);
      cardBody.appendChild(sexeSelect);

      cardDiv.appendChild(cardHeader);
      cardDiv.appendChild(cardBody);

      formEnfants.appendChild(cardDiv);

      // Ajoutez un écouteur d'événement sur le clic du bouton
      let btnSupprElt = document.getElementById(`btn ${childId[i-1]}`);
      console.log(childId[i-1])
      btnSupprElt.addEventListener('click', (event) => {
        event.preventDefault(); // Empêche la soumission du formulaire

        //  Demande de confirmation de suppression de cet enfant
        const confirmation = confirm("Vous voulez vraiment supprimer cet enfant ?");

        if(confirmation) {
          const enfantId = btnSupprElt.dataset.enfantId; // Récupère l'ID de l'enfant à supprimer      
          // Effectuez une requête AJAX pour supprimer l'enfant
          fetch(`/employee/child/${enfantId}`, {
            method: 'DELETE',
          })
            .then(response => {          
              if (response.ok) {
                // La suppression de l'enfant a réussi, vous pouvez effectuer des actions supplémentaires si nécessaire
                console.log('Enfant supprimé avec succès');
                //  Recharger la page
                location.reload();
              } else {
                // Gérez les erreurs lors de la suppression de l'enfant
                console.error('Une erreur est survenue lors de la suppression de l\'enfant');
              }
            })
            .catch(error => {
              // Gérez les erreurs lors de la requête AJAX
              console.error('Une erreur est survenue lors de la requête AJAX', error);
            });
          }
      });
    }
    
    
    nombreEnfantsInput.addEventListener('change', function() {
      var nombreEnfants = parseInt(nombreEnfantsInput.value);
      
      // Vide le contenu précédent du formulaire
      formEnfants.innerHTML = '';
      
      for (var i = 1; i <= nombreEnfants; i++) {
        
        //  Pour les enfants deja enregistrer
        if(i <= childId.length) {
          var cardDiv = document.createElement('div');
          cardDiv.className = 'col-md-4 mt-4'; 
      
          var cardHeader = document.createElement('div');
          cardHeader.className = 'card-header';
          cardHeader.textContent = 'Enfant ' + i;
      
          var cardBody = document.createElement('div');
          cardBody.className = 'card-body';

          //  Seulement pour le modification a envoyer l'id de l'enfant existant
          var childIdInput = document.createElement('input');
          childIdInput.setAttribute('type', 'hidden');
          childIdInput.setAttribute('name', 'idChild');
          childIdInput.value = childId[i-1] ?? 0;          
      
          var dateNaissanceLabel = document.createElement('label');
          dateNaissanceLabel.setAttribute('for', 'dateNaissanceEnfant' + i);
          dateNaissanceLabel.textContent = 'Date de naissance :';
          
          var dateNaissanceInput = document.createElement('input');
          dateNaissanceInput.setAttribute('type', 'date');
          dateNaissanceInput.className = 'form-control form-control-sm';
          dateNaissanceInput.setAttribute('id', 'dateNaissanceEnfant' + i);
          dateNaissanceInput.setAttribute('name', 'ddnChild');
          dateNaissanceInput.value =  ddnChild[i-1];
          // dateNaissanceInput.required = true;
          var sexeLabel = document.createElement('label');
          sexeLabel.setAttribute('for', 'sexeEnfant' + i);
          sexeLabel.textContent = 'Sexe :';
      
          var sexeSelect = document.createElement('select');
          sexeSelect.className = 'form-control form-control-sm';
          sexeSelect.setAttribute('id', 'sexeEnfant' + i);
          sexeSelect.setAttribute('name', 'sexeChild');
          // sexeSelect.required = true;
      
          var optionMasculin = document.createElement('option');
          optionMasculin.value = 'M';
          optionMasculin.textContent = 'Masculin';
          optionMasculin.selected = sexeChild[i-1] === 'M';
          
          var optionFeminin = document.createElement('option');
          optionFeminin.value =  'F';
          optionFeminin.textContent = 'Féminin';
          optionFeminin.selected =  sexeChild[i-1] === "F";
      
          sexeSelect.appendChild(optionMasculin);
          sexeSelect.appendChild(optionFeminin);
      
          cardBody.appendChild(childIdInput);
          cardBody.appendChild(dateNaissanceLabel);
          cardBody.appendChild(dateNaissanceInput);
          cardBody.appendChild(sexeLabel);
          cardBody.appendChild(sexeSelect);
      
          cardDiv.appendChild(cardHeader);
          cardDiv.appendChild(cardBody);
      
          formEnfants.appendChild(cardDiv);
        }

        //  Nouveaux enfants
        else {

          var cardDiv = document.createElement('div');
          cardDiv.className = 'col-md-4 mt-4';
  
          var cardHeader = document.createElement('div');
          cardHeader.className = 'card-header';
          cardHeader.textContent = 'Enfant ' + i;
  
          var cardBody = document.createElement('div');
          cardBody.className = 'card-body';

          var childIdInput = document.createElement('input');
          childIdInput.setAttribute('type', 'hidden');
          childIdInput.setAttribute('name', 'idChild');
          childIdInput.value = 0;
  
          var dateNaissanceLabel = document.createElement('label');
          dateNaissanceLabel.setAttribute('for', 'dateNaissanceEnfant' + i);
          dateNaissanceLabel.textContent = 'Date de naissance :';
  
          var dateNaissanceInput = document.createElement('input');
          dateNaissanceInput.setAttribute('type', 'date');
          dateNaissanceInput.className = 'form-control form-control-sm';
          dateNaissanceInput.setAttribute('id', 'dateNaissanceEnfant' + i);
          dateNaissanceInput.setAttribute('name', 'ddnChild');
          // dateNaissanceInput.required = true;
  
          var sexeLabel = document.createElement('label');
          sexeLabel.setAttribute('for', 'sexeEnfant' + i);
          sexeLabel.textContent = 'Sexe :';
  
          var sexeSelect = document.createElement('select');
          sexeSelect.className = 'form-control';
          sexeSelect.setAttribute('id', 'sexeEnfant' + i);
          sexeSelect.setAttribute('name', 'sexeChild');
          // sexeSelect.required = true;
  
          var optionMasculin = document.createElement('option');
          optionMasculin.value = 'M';
          optionMasculin.textContent = 'Masculin';
  
          var optionFeminin = document.createElement('option');
          optionFeminin.value = 'F';
          optionFeminin.textContent = 'Féminin';
  
          sexeSelect.appendChild(optionMasculin);
          sexeSelect.appendChild(optionFeminin);
  
          cardBody.appendChild(childIdInput);
          cardBody.appendChild(dateNaissanceLabel);
          cardBody.appendChild(dateNaissanceInput);
          cardBody.appendChild(sexeLabel);
          cardBody.appendChild(sexeSelect);
  
          cardDiv.appendChild(cardHeader);
          cardDiv.appendChild(cardBody);
  
          formEnfants.appendChild(cardDiv);
        }
      }
    });
  });
  
</script>



