
<div class="contenu clearfix" id="ListeModeles">

    <div>

        <h2 style="margin-bottom: 1em">
            <span id="titleSpan">{{ 'Liste des déclenchements pour terme de paiement' | trad }}</span>
            
            <button class="button principal" type="button" id="ajoutDeclenchements">{{'Ajouter le(s) déclenchement(s)' | trad}}</button>
            <button class="button secondaire" id="annuler" type="button">{{'Annuler' | trad}}</button>
        </h2>

        <form method="POST" id="formulaireListeTypeEvt" name="formulaireListeTypeEvt">

            {% set refreshPath = path('TermeDePaiement.TermeDePaiement.ajoutDeclenchementsModele', {MODULE, id, numtp }) %}

            <table class="table" id="tableau">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col" width="">{{ triTable('CODE_EVT', infoPagination.filter.tri_CODE_EVT, 'Code' | trad, 'formulaireListeTypeEvt', refreshPath, 'formulaireListeTypeEvt') }}</th>
                        <th scope="col" width="">{{ triTable('LIB_EVT', infoPagination.filter.tri_LIB_EVT, 'Libellé' | trad, 'formulaireListeTypeEvt', refreshPath, 'formulaireListeTypeEvt') }}</th>
                        <th scope="col" width="">{{ triTable('HAPLUS', infoPagination.filter.tri_HAPLUS, 'Automatique' | trad, 'formulaireListeTypeEvt', refreshPath, 'formulaireListeTypeEvt') }}</th>
                        <th scope="col" width="">{{ triTable('PRO_POSTE', infoPagination.filter.tri_PRO_POSTE, 'Avec postes ?' | trad, 'formulaireListeTypeEvt', refreshPath, 'formulaireListeTypeEvt') }}</th>
                        <th scope="col" width=""></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>                        
                        <td>{{ filterTable('CODE_EVT', infoPagination.filter.filter_CODE_EVT, '', 'formulaireListeTypeEvt', refreshPath, 'formulaireListeTypeEvt') }}</th>
                        <td>{{ filterTable('LIB_EVT', infoPagination.filter.filter_LIB_EVT, '', 'formulaireListeTypeEvt', refreshPath, 'formulaireListeTypeEvt') }}</th>
                        <td>{{ filterSelect('HAPLUS', infoPagination.filter.filter_HAPLUS, {'': '', 'T': 'Oui' | trad, 'F': 'Non' | trad }, 'formulaireListeTypeEvt', '', 'formulaireListeTypeEvt', refreshPath, '') }}</th>
                        <td>{{ filterSelect('PRO_POSTE', infoPagination.filter.filter_PRO_POSTE, {'': '', 'T': 'Oui' | trad, 'F': 'Non' | trad }, 'formulaireListeTypeEvt', '', 'formulaireListeTypeEvt', refreshPath, '') }}</th>
                        <td class="text-right" class="white-tooltip">
                            <input name="selectAll" type="checkbox"
                                data-checkall-input="table-main" 
                                class="form-control checkbox"
                            >
                            <span class='infos_tooltip left'>{{ 'Tout sélectionner' | trad }}</span>
                        </td>
                    </tr>
                    {% set listEvtDisplayed = [] %}
                    {% for evt in tyevtstp %}
                        {% set codeEvt = evt.CODE_EVT | convert_encoding('UTF-8', 'ISO-8859-1') %}
                        <tr id="evement{{loop.index}}">
                            <td> 
                                {{ codeEvt }} 
                                <input type="hidden" name="code-{{codeEvt}}" value="{{codeEvt}}" />
                            </td>
                            <td>
                                {{ evt.LIB_EVT | convert_encoding('UTF-8', 'ISO-8859-1') | trad }}
                                <input type="hidden" name="lib-{{codeEvt}}" value="{{evt.LIB_EVT}}" />
                            </td>
                            <td>
                                {{ evt.HAPLUS | boolTrad }}
                                <input type="hidden" name="haplus-{{codeEvt}}" value="{{evt.HAPLUS | boolTrad }}" />
                            </td>
                            <td>
                                {{ evt.PRO_POSTE | boolTrad }}
                                <input type="hidden" name="proposte-{{codeEvt}}" value="{{evt.PRO_POSTE | boolTrad }}" />
                            </td>
                            <td class="text-right">
                                <input type="checkbox" 
                                    class="form-control checkbox selected_evt" 
                                    data-id="{{ codeEvt }}" 
                                    data-checkall="table-main"
                                    id="input_selected_evt_{{ codeEvt }}" 
                                    name="selected_evt[]"
                                    value="{{ codeEvt }}"
                                    {{ codeEvt in (post.selected_evt ?? []) ? 'checked' }}
                                    />
                                {% set listEvtDisplayed = listEvtDisplayed | merge([codeEvt]) %}
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination"></ul>
            </nav>
            <script>
                ajaxPagination("#pagination", "#formulaireListeTypeEvt", {
                    pageCount: {{ infoPagination.nombreDePage }},
                    page: {{ infoPagination.page }},
                    path: {{ path('TermeDePaiement.TermeDePaiement.ajoutDeclenchementsModele', {MODULE, id, numtp }) | json }},
                    postKey: 'page',
                }, function() {
                    activeLoader();
                    return new FormData(document.getElementById('formulaireListeTypeEvt'));
                });
            </script>

            <div id="addedInputsEvt">
                {% for codeEvt in (post.selected_evt ?? []) | filter((v) => v not in listEvtDisplayed ) %}
                    <input type="hidden" name="selected_evt[]" value="{{ codeEvt }}" />
                    <input type="hidden" name="code-{{codeEvt}}" value="{{ codeEvt }}">
                    <input type="hidden" name="lib-{{codeEvt}}" value="{{ post.selected_evt_detail[codeEvt].LIB_EVT }}">
                    <input type="hidden" name="haplus-{{codeEvt}}" value="{{ post.selected_evt_detail[codeEvt].HAPLUS | boolTrad }}">
                    <input type="hidden" name="proposte-{{codeEvt}}" value="{{ post.selected_evt_detail[codeEvt].PRO_POSTE | boolTrad }}">
                {% endfor %}
            </div> 
        </form>
    </div>
    <script>
        document.getElementById('annuler').addEventListener('click', () => {
            desactiveHiddenDiv();
        });

        function clearAllLines() {
            const $tbody = $(document).find('#table-{{numtp}} tbody');
            $tbody.each(function() {
                $body = $(this);
                const $targetRows = $body.find('tr');
                $targetRows.each(function() {
                    $(this).remove();
                });
            });
        }

        function getSeuils() {
            const inputs = document.querySelectorAll(
                '[id^="input_termeDePaiement[{{ numtp }}][seuils_evt]"]'
            );

            const values = [];

            inputs.forEach(input => {
                const match = input.id.match(/\[seuils_evt]\[(.+)]$/);
                console.log(match);
                if (match) {
                    const inputName = match[1]; // on récupère le nom de l'input via une regex
                    const [code, lib, haplus, proposte] = inputName.split('@'); // on récupère le code une fois le split effectué
                    values[code] = input.value;
                }
            });

            return values;
        }

        function deleteRow(element) {
            const row = element.closest('tr');
            const codeEvtCell = row.querySelector('td:first-child');
            const codeEvt = codeEvtCell ? codeEvtCell.textContent.trim() : null;
    
            if (codeEvt) {
                const hiddenInputs = document.querySelectorAll('input[name="selected_evt[]"]');
                hiddenInputs.forEach(input => {
                    if (input.value.startsWith(codeEvt)) {
                        input.parentElement.removeChild(input);
                    }
                });
                row.parentElement.removeChild(row);
            }
        }

        function addLine(infos) {
            const $tbody = $(document).find('#table-{{numtp}} tbody');
            // créer une nouvelle ligne vide
            const $newTr = $('<tr id="table-{{numtp}}-ligne-'+infos.code+'"></tr>');
            const evt_name = infos.code+'@'+infos.lib+'@'+infos.haplus+'@'+infos.proposte;
            const hiddenInput1 = '<input type="hidden" name="termeDePaiement[{{ numtp }}][selected_evt][]" value="'+evt_name+'">';
            const td1 = '<td>'+htmlEncode(infos.code)+hiddenInput1+'</td>';
            const td2 = '<td>'+htmlEncode(infos.lib)+'</td>';
            const td3 = '<td>'+infos.haplus+'</td>';
            const td4 = '<td>'+infos.proposte+'</td>';
            let td5 = '<td></td>';
            if(infos.proposte == '{{ 1 | boolTrad }}') {
                td5 = `<td class="montant">
                                {{ inputAdvance('DEVISE', {
                                    'name': 'termeDePaiement[' ~ numtp ~ '][seuils_evt][__EVT_NAME__]',
                                    'value': 100,
                                    'devise': '%',
                                    'pathValidator': path('Ajax.validator.float'),
                                    'paramsValidator': {'min': 0, 'max': 100, 'nomChamp': 'Seuil' | trad},
                                    'addCss': 'min-width: 3em; text-align: right; padding-right: 50px',
                                    'obligatoire': true,
                                }) }}
                            </td>`;
                td5 = td5.replaceAll('__EVT_NAME__', evt_name);
                td5 = td5.replaceAll('value="100"', 'value="' + parseFloat(infos.seuil ?? 0).toFixed(2) + '"');
            }
            const td6 = `<td style="text-align: right;">
                            <span class="Supprimer_v2" data-container-contextuel="table-{{numtp}}-ligne-${infos.code}" style="opacity: 0; " onclick="deleteRow(this)" title="{{'Supprimer la ligne' | trad}}">
                            </span>
                        </td>`;
            $newTr.append(td1, td2, td3, td4, td5, td6);
            $tbody.find('tr:last').hasClass('odd_table_V2') ? $newTr.addClass('even_table_V2') : $newTr.addClass('odd_table_V2');

            // ajouter la nouvelle ligne après la tr cible (ou à la fin du tbody)
            $tbody.append($newTr);
        }

        $('#ajoutDeclenchements').on('click', function() {
            const seuilsExistants = getSeuils();
            clearAllLines();
            const formData = new FormData(document.querySelector('#formulaireListeTypeEvt'));
            var tableau = $('#table-{{ numtp }}');
            for([key, value] of formData.entries()) {
                if (key === 'selected_evt[]') {
                    let infos = {};
                    infos.code = formData.get('code-'+value);
                    infos.lib = formData.get('lib-'+value);
                    infos.haplus = formData.get('haplus-'+value);
                    infos.proposte = formData.get('proposte-'+value);
                    infos.seuil = seuilsExistants[infos.code] ?? 0;
                    addLine(infos);
                }
            }
            desactiveHiddenDiv();
        })

        $(function() {
            {% if post.libelle %}
                $('#titleSpan').text($('#titleSpan').text() + "{{colon() ~ post.libelle | e('js')}}");
            {% else %}
                $('#titleSpan').text($('#titleSpan').text() + '{{(" " ~ "n°" | trad ) ~ colon() ~ numtp }}');
            {% endif %}
            const formData = new FormData(document.querySelector('{{update ? "#form_update_ModeleTp" : "#form_new_ModeleTp" }}'));
            for([key, value] of formData.entries()) {
                if (key === 'termeDePaiement[{{ numtp }}][selected_evt][]') {
                    const [code, lib, haplus, proposte] = value.split('@');
                    let inputId = "input_selected_evt_"+code;
                    if($('[id="'+inputId+'"]').length > 0) {
                        $('[id="'+inputId+'"]').prop('checked', true);
                    } else {
                        const selectedEvtToAdd  = $('<input type="hidden" name="selected_evt[]" value="'+code+'">');
                        const codeToAdd         = $('<input type="hidden" name="code-'+code+'" value="'+code+'">');
                        const libToAdd          = $('<input type="hidden" name="lib-'+code+'" value="'+lib+'">');
                        const haplusToAdd       = $('<input type="hidden" name="haplus-'+code+'" value="'+haplus+'">');
                        const proposteToAdd     = $('<input type="hidden" name="proposte-'+code+'" value="'+proposte+'">');
                        $('#addedInputsEvt').after(selectedEvtToAdd, codeToAdd, libToAdd, haplusToAdd, proposteToAdd);
                    }
                }
            }
        });
    </script>

