
<div class="corps">
    <section class="card">
        <div class="head-main">
            <h2>Planning de congé</h2>
        
            <% if((req.session && req.session.admin && req.session.admin.role == 'Super admin') || timeToPlanning) { %>
                <button class="btn btn-primary" id="active-modal" >
                    <ion-icon name="add-circle-outline"></ion-icon>
                    Nouveau
                </button>      
            <% } %>      
            <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">
            <div id="calendrier"></div>
        </div>
    </section>
</div>
<script src="/calendar/lib/main.js"></script>
<script>
    let allPlanning = [];
</script>
<% for(let i = 0; i < plannings.length; i++) { %>
    <script>
        event = {};        
        event.nom = "<%= plannings[i].name_employee %>";
        event.prenom = "<%= (plannings[i].last_name_employee) ? plannings[i].last_name_employee : '' %>";
        event.fonction = "<%= (plannings[i].fonction) ? plannings[i].fonction.nameFunction : ''%>";        
        event.start = "<%= plannings[i].planning.startDate %>";
        event.startHour = "<%= plannings[i].planning.startHour ?? 'MT' %>";
        event.end = "<%= plannings[i].planning.endDate %>";
        event.endHour = "<%= plannings[i].planning.endHour ?? 'SR' %>";        
        event.applicant = "<%= (plannings[i].planning.applicant) ? plannings[i].planning.applicant.firstName : '' %> <%=  (plannings[i].planning.applicant) ?  plannings[i].planning.applicant.lastName : ''%>";
        event.planningId = 'PLG' + "<%= plannings[i].planning.id %>";
        allPlanning.push(event);        
    </script>
<% } %>
<script>    
    const sortToLong = {
        "MT": " Matin",
        "MD": " Midi",
        "SR": " Soir",
        "": "",
    }
    const planningColor = 'rgba(35, 247, 255)';
    const textColor = 'rgba(33,33,33,.9)';
    let events = allPlanning.map((value, i) => {
        return {
            id: value.planningId,
            title: 'Planning - ' +
                value.nom + ' ' +
                value.prenom + ' - ' +
                value.fonction + " " +
                value.start + sortToLong[value.startHour] + ' au ' +
                value.end + sortToLong[value.endHour],
            start: new Date(value.start),
            end: new Date(value.end),
            backgroundColor: planningColor,
            borderColor: planningColor,
            textColor: textColor,

            // allDay: false,
            // className: 'event-planning',
            // url: '/planning/' + value.planningId.replace('PLG',''),
        }
    });  
    document.addEventListener('DOMContentLoaded', function () {
        var calendarEl = document.getElementById('calendrier');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            headerToolbar: {
                start: 'prev today next', // will normally be on the left. if RTL, will be on the right
                center: 'title',
                right: ''
            },
            titleFormat: {
                year: 'numeric',
                month: 'long',
            },
            buttonText: {
                today: 'Aujourd\'hui',
                month: 'Mois',
                week: 'Semaine',
                day: 'Jour',
                list: 'Liste'
            },
            events: events,
            locale: 'fr',            
            displayEventTime: false,
            eventDidMount: function (info) {
                info.el.style.border = 'none';
                info.el.style.height = '40px';
                info.el.style.display = 'flex';
                info.el.style.alignItems = 'center';                
                info.el.style.overflow = 'hidden';                
            },
            eventClick: function (info) {
                // Récupérer les détails de l'événement cliqué
                let id = info.event.id;
                let evenement = allPlanning.filter(value => value.planningId === id)
                
                console.log(evenement);
                // // Afficher les détails de l'événement dans le modal
                let title = document.getElementById('title-form');
                title.textContent = "Editer un planning";

                let form = document.getElementById('form-planning');
                let rech = document.getElementById('nom_matricule');                
                let debut = document.getElementById('start_date');
                let h_debut = document.getElementById('start_hour');
                let fin = document.getElementById('end_date');
                let h_fin = document.getElementById('end_hour');    
                
                form.action = `/vacation/planning/edit/${evenement[0].planningId.replace('PLG', '')}`;

                rech.value = evenement[0].nom;
                rech.readOnly = true;

                //  Créer un evenement input pour le form recherche afin de lancer l'algorithme de recherche
                let inputEvent = new Event('input');
                rech.dispatchEvent(inputEvent);                
                
                debut.value = evenement[0].start;
                h_debut.value = evenement[0].startHour;            
                fin.value = evenement[0].end;          
                h_fin.value = evenement[0].endHour;      

                // // Afficher le modal
                // let lien = document.getElementById('link-modal');
                // lien.href = '/vacation/' + evenement[0].vacationId;
                var modal = document.getElementById('modal');
                var eventModal = document.getElementById('eventModal');
                modal.classList.add('show-modal');
                eventModal.classList.add('show-event-modal');
            },
        });
        calendar.render();
        calendar.setOption('height', '80vh');
        
    });
</script>

<form method="post" id="form-planning">
    <div class="modal" id="modal">
        <div id="eventModal" class="eventModal">
            <div id="eventTitle">
                <h1 id="title-form"></h1>                
            </div>
            <div id="eventBody">
                <input type="hidden" name="demandeur" value="<%= req.session ? req.session.admin.id : 0 %>"> 
                <div class="row">
                    <div class="col-md-8 form-group">
                        <label for="name">Recherche</label>
                        <input type="search" class="form-control form-control-sm" id="nom_matricule" placeholder="RAKOTO 001">
                    </div>
                    <input type="hidden" name="idEmployee" id="id" required>
                    <div class="col-md-4 form-group">
                        <label for="matricule">Matricule</label>
                        <input type="text" class="form-control form-control-sm" id="matricule" name="matricule" readonly required>
                    </div>
                </div>                               
                <div class="row">
                    <div class="col-md-12 form-group">
                        <label for="name">Nom et prénom(s)</label>
                        <input type="text" class="form-control form-control-sm" id="name" name="name" readonly required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3 form-group">
                        <label for="start_date">Date de début</label>
                        <input type="date" class="form-control form-control-sm" id="start_date" name="start" required
                        <%= ((req.session && req.session.admin && req.session.admin.role == 'Super admin') || timeToPlanning ) ? ""
                            : "readonly"
                        %>>
                    </div>
                    <div class="col-md-3 form-group">
                        <label for="start_hour">Heure de début</label>
                        <select name="start_hour" class="form-select form-select-sm" id="start_hour"
                        <%= ((req.session && req.session.admin && req.session.admin.role == 'Super admin') || timeToPlanning ) ? ""
                            : "disabled"
                        %>
                        >
                            <option value="MT" selected>Matin</option>
                            <option value="MD">Midi</option>
                        </select>
                    </div>
                    <div class="col-md-3 form-group">
                        <label for="end_date">Date de fin</label>
                        <input type="date" class="form-control form-control-sm" id="end_date" name="end" required
                        <%= ((req.session && req.session.admin && req.session.admin.role == 'Super admin') || timeToPlanning ) ? ""
                            : "readonly"
                        %>
                        >
                    </div>
                    <div class="col-md-3 form-group">
                        <label for="end_hour">Heure de fin</label>
                        <select name="end_hour" class="form-select form-select-sm" id="end_hour"
                        <%= ((req.session && req.session.admin && req.session.admin.role == 'Super admin') || timeToPlanning ) ? ""
                            : "disabled"
                        %>>
                        >
                            <option value="MD">Midi</option>
                            <option value="SR" selected>Soir</option>
                        </select>
                    </div>                             
                </div>                                
            </div>
            <div id="eventFoot">
                <a id="link-modal">
                    <button type="submit" class="btn btn-primary">Enregistrer</button>
                </a>
                <button type="reset" class="btn btn-primary" id="close-modal">Fermer</button>
            </div>
        </div>
    </div>
</form>

<!-- script modal -->
<script>
    var form = document.getElementById('form-planning');
    let nom_matricule_search = document.getElementById("nom_matricule");
    var activeModal = document.getElementById('active-modal');
    var modal = document.getElementById('modal');
    var eventModal = document.getElementById('eventModal');
    var closeModal = document.getElementById('close-modal');

    closeModal.addEventListener('click', () => {
            eventModal.classList.toggle('show-event-modal');
            modal.classList.toggle('show-modal');
        })    

    activeModal.addEventListener('click', () => {        
        nom_matricule_search.readOnly = false;
        form.action = '/vacation/planning/add';
        let title = document.getElementById('title-form');
        title.textContent = "Ajouter un planning";        
        modal.classList.add('show-modal');        
        eventModal.classList.add('show-event-modal');
    })
    
</script>

<script>
    var employees = [];
    var matriculeAdminLogged = "<%= req.session.admin.matriculeEmployee %>";
    
</script>

<% if(employees && employees.length > 0) { %>
    <% employees.forEach(employee=> { %>
        <script>
            employee = {};
            employee.id = "<%= employee.id %>";
            employee.matricule = "<%= employee.matricule %>";
            employee.name = "<%= employee.name_employee + ' ' + employee.last_name_employee %>";                    
            employees.push(employee);      
        </script>
    <% }) %>
<% } %>

<script>    
    let id = document.getElementById('id');
    let matricule = document.getElementById('matricule');
    let name = document.getElementById('name');    

    //  Valeur pour le demande avec id et valeur initial pour le demande sans id 
    console.log(matriculeAdminLogged);
    for (const employee of employees) {        
        console.log(employee.matricule);
        if (employee.matricule === matriculeAdminLogged) {            
            id.value = employee.id;
            matricule.value = employee.matricule;
            name.value = employee.name;                        
        }
    }

    //  La valeur dans nom_matricule change
    nom_matricule_search.addEventListener('input', () => {
        let value = nom_matricule_search.value.toLowerCase();
        let empl_found = false;
        for (const employee of employees) {
            const nom = employee.name.toLowerCase();
            const n_matricule = employee.matricule;

            if (nom.includes(value) || n_matricule.includes(value)) {                
                id.value = employee.id;
                matricule.value = employee.matricule;
                name.value = employee.name;                
                empl_found = true;
            }

            // Non trouver ou il n'y a rien dans le formulaire nom_matricule
            if (!empl_found || value == '') {
                //  Vider les formulaires et ne pas afficher                
                id.value = '';
                matricule.value = '';
                name.value = '';                
                found = false;
            }
        }
    });

</script>


