
<div class="corps">
    <div class="card">
        <div class="head-main">
            <h2>Historique des congés de <%= employee.name_employee %> <%= employee.last_name_employee%></h2>
                
            <a href="/employee/">
                <button class="button-planning">
                    <!--<img src="/images/planning.png" class="svg-icon" alt="">-->
                    <ion-icon name="home-outline"></ion-icon>
                    <span class="label">Liste</span>
                </button>
            </a>
        </div>             
        <div class="card-body">
            <div class="container-custom-search mb-3">                        
                <% if(req.session && req.session.admin && req.session.admin.role == 'Super admin') { %>                            
                    <a href="/vacation/saisi/<%= vacations[0].employeeId %>">
                        <button class="btn btn-primary">
                            <ion-icon name="add-circle-outline"></ion-icon>
                            Nouveau
                        </button>
                    </a>                    
                <% } %>                
                
            </div>
            <div class="table table-responsive align-content-center" id="employeeTableBody">                                             
            </div>
        </div>            
    </div>
      
</div>

<script>
    function deleteVacation(id) {
        //  Demande de confirmation de suppression de cet enfant
        const confirmation = confirm("Vous voulez vraiment supprimer le congé ?");
    
        if(confirmation) {        
            // Effectuez une requête AJAX pour supprimer l'enfant
            fetch(`/vacation/${id}`, {
                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('Congé 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 ');
                }
                })
                .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);
                });
        }
    }   
</script>

<script>    
    var vacations = [];
</script>

<% vacations.forEach(( value ) => { %>
    <script>        
        vacation = {}; 
        vacation.id = "<%= value.id %>";
        vacation.sold = parseFloat("<%= value.totalVacation %>");
        vacation.start = "<%= value.startDate %>";
        vacation.h_start = "<%= value.startHour %>";
        vacation.end = "<%= value.endDate %>";
        vacation.h_end = "<%= value.endHour %>";        
        vacation.employee = "<%= value.employeeId %>";
        vacation.admin = "<%= value.AdmnistratorId %>";                        
        
        vacations.push(vacation);          
        // console.log(vacation);
    </script>
<% })%>
   
<script>    
   // Récupérer les éléments du DOM   
   const vacationTable = document.getElementById('employeeTableBody');

   
   // Fonction pour générer les lignes du tableau
   function generateTableRows(readOnly, idVacation) {
     let tableRows = `<div class="row">
                    <div class="col">Solde</div>
                    <div class="col">Début</div>
                    <div class="col">Heure</div>
                    <div class="col">Fin</div>
                    <div class="col">Heure</div>                                                                                    
                    <div class="col">Etat</div>                                                        
                    <% if( req.session && req.session.admin && req.session.admin.role === 'Super admin') {%>
                        <div class="col">Actions</div>                
                    <% } %>
                </div>`;
   
     for (const vacation of vacations) {  

        // Etat de congé
        state = "";
        adminId = vacation.admin;
        if(!adminId) state = "En attente";
        else if(adminId > 0) state = "Validé"
        else if(adminId < 0) state = "Rejeté"

        //  Heures
        h_start = "";
        h_end = "";
        switch (vacation.h_start) {
            case "MT" : 
                h_start = "Matin";
                break;
            case "MD" :
                h_start = "Midi";
                break;
            default :
                h_start = " ";
        }               

        switch (vacation.h_end) {
            case "SR" : 
                h_end = "Soir";
                break;
            case "MD" :
                h_end = "Midi";
                break;
            default :
                h_end = " ";
        }
        
        let buttonEdit = `<button class="btn btn-reaction" data-title="Editer" onclick="generateTableRows(${!readOnly}, ${vacation.id})">
                            <i class="mdi mdi mdi-pencil-box-outline custom-icon-info"></i></a>
                        </button>`;
        let buttonValidate = `<button type="submit" class="btn btn-reaction" data-title="Valider">                            
                                <ion-icon name="checkmark-done-outline"></ion-icon>                            
                            </button>
                            <button type="reset" class="btn btn-reaction" data-title="Annuler" onclick="generateTableRows(${false}, ${0})">                            
                                <ion-icon name="close-outline"></ion-icon>
                            </button>`;
        let variableButton = buttonEdit;

        let readValue = "readonly";
        let disable = "disabled";               

        //  En cours d'edition
        if (readOnly && vacation.id == idVacation) {
            readValue = "";
            disable = "";
            variableButton = buttonValidate;
        }            
        
        tableRows += `<form method="POST" action="/vacation/edit/${vacation.employee}" >
                <div class="row">                    
                    <div class="col" style="margin-left: 10px;">                        
                        <input type="hidden" name="id" value="${vacation.id}" />
                        <input type="text" name="totalVacation" value="${vacation.sold}" class="form-control form-control-sm" ${readValue}/>                    
                    </div>
                    <div class="col">
                        <input type="date" name="startDate" value="${vacation.start}" class="form-control form-control-sm" ${readValue}/>                                        
                    </div>
                    <div class="col">
                        <select name="startHour" ${disable}>
                            <option value="MT" ${ vacation.h_start == "MT" ? "selected" : " "}>Matin</option>
                            <option value="MD" ${ vacation.h_start == "MD" ? "selected" : " "}>Midi</option>
                        </select>                    
                    </div>
                    <div class="col">                    
                        <input type="date" name="endDate" value="${vacation.end}" class="form-control form-control-sm" ${readValue}/>                                            
                    </div>
                    <div class="col">
                        <select name="endHour" ${disable}>
                            <option value="MT" ${ vacation.h_end == "SR" ? "selected" : " "}>Soir</option>
                            <option value="MD" ${ vacation.h_end == "MD" ? "selected" : " "}>Midi</option>
                        </select>                    
                    </div>
                    <div class="col">${ state } </div>                            
                    <div class="col">                            
                        <div class="reaction-icons" id="reactionIcons">                                                                        
                            ${ variableButton }
                            <button class="btn btn-reaction" data-title="Supprimer" onclick="deleteVacation(${vacation.id})" ><i class="mdi mdi-delete custom-icon-delete"></i></button>                     
                        </div>                            
                    </div>                    
                </div>
                </form>`;
                    
     }     
   
     vacationTable.innerHTML = tableRows;
   }
   
   // Générer les lignes du tableau initialement
   generateTableRows(false, 0);
      
</script>

  
