{% extends 'layout.twig' %}

{% block body %}
<section class="contenu">
    <h1>{{ 'Commandes' | trad }}</h1>
    {{ ariane() }}

    
    <form 
        method="POST"
        action="{{ path('Commande.Imputation.update',{commandeId: caEntet.NO_CDE}) }}"  
        onsubmit="return ajaxSubmit(event);"
        data-onsuccess="impMassUpdateSuccess"
        data-onerror="impMassUpdateError"
    >
        <div class="bs-row flex-y-center mb-base">
            <h2>
                {{- strBuild(
                    'Modification des imputations de la commande @1@ du fournisseur @2@ (@3@)' | trad,
                    [ caEntet.NO_CDE, caEntet.Fourniss.CODE, caEntet.Fourniss.RS ]
                ) -}}
            </h2>
            <div class="bs-col text-right">
                <a href="javascript:void(0)" 
                    onclick="{{ arianePrevRouteJsFunc() | e('html_attr') }}"
                    class="button secondaire mr-base"
                >{{ 'Annuler' | trad }}</a>
                <button type="submit" class="button principal">
                    {{- 'Modifier' | trad -}}
                </button>
                
            </div>
        </div>
        

        <div class="box-form mb-base">
            <div class="bs-row gutter-x-base gutter-y-tiny">
                {% if config.SectImp.isActive and canUpdateSectImp %}
                <div class="bs-col-half row">
                    <input type="hidden" name="MODIF_SECTIMP" value="0" />
                    {{ inputSectImp(
                        caEntet.CODE_STE,
                        'SECTIMP_ENTETE',
                        post.SECTIMP_ENTETE | default(caEntet.SECTIMP),
                        caEntet.SectImput.SICODG | boolSql,
                        'Section d\'imputation' | trad
                    ) }}							
                </div>
                {% endif %}
                
                {% if config.CodeCompl.isActive and canUpdateCodeComp %}
                <div class="bs-col-half row">
                    <input type="hidden" name="MODIF_CODE_COMP" value="0" />
                    {{ inputAdvance('ZOOMADVANCE', {
                        titre: 'Code complémentaire' | trad,
                        name: 'CODE_COMP_ENTETE',
                        pahtZoom: path('Ajax.liste.cdc'),
                        paramZoom: {
                            filter_egal_CODE_STE: caEntet.CODE_STE,
                            cdc_valide: 1
                        } | json_encode,
                        entity: 'Codecomp',
                        widthPopup: 'modal_large',
                        titleZoom: 'Liste des codes complémentaires' | trad,
                        pathConvert: path('Ajax.outil.convertLibelle'),
                        convertLibelle: 'convertLibelleGlobal',
                        pathValidator: path('Ajax.validator.codeComplementaire'),
                        paramsValidator: {
                            nomChamp: 'Code complémentaire' | trad, 
                            null: true,
                            filter_egal_CODE_STE: caEntet.CODE_STE
                        } | json_encode,
                        value: caEntet.CODECOMP,
                        option: config.LOCK_CDC ? 'readOnly':'',
                        iconeLabel: 'Inactif2.png',
                        idIconeLabel: 'icone_CODE_COMP'
                    }) }}
                </div>
                {% endif %}
                {% if config.SectImp.isActive and canUpdateSectImp %}
                <div class="bs-col-half row">
                    {{ inputAdvance('TREEVIEW', {
                        titre: 'Code gestion' | trad,
                        name: 'CODGES_ENTETE',
                        pathTreeview: path('Ajax.Treeview.codeGestion'),
                        paramsTreeview: 'getCodeGestTreeviewParam()',
                        titleTreeview: 'Code gestion' | trad,
                        value: caEntet.ID_CG,
                        valueTexteTreeview: caEntet.CodeGestion is defined ? 
                            caEntet.CodeGestion.LIB_GES ~ ' (' ~ caEntet.CodeGestion.CODE_AFF ~ ')' : '',
                        pathValidator: path('Ajax.validator.codeGestion'),
                        paramsValidator: 'getCodeGestValidatorParam()',
                        pathConvert: path('Ajax.outil.convertLibelle'),
							
                        entity: 'Codgest',
                        codeBDD: 'CODE_GES',
                        libelleBDD: 'CODE_AFF',
                    }) }}
                    
                    <script>
                    function getCodeGestTreeviewParam() {
                        return {
                            CODE_SI: $("#input_SECTIMP_ENTETE").val(),
                            inputCG: 'CODGES_ENTETE',
                            CODE_STE: {{ caEntet.CODE_STE | json}},
                            affichageLibelle: 1,
                            cg_valide: 1,
                            CODE_GESTION_PAR_ID: 1,
                        };
                    }
                    function getCodeGestValidatorParam() {
                        return {
                            nomChamp: {{ 'Code gestion' | trad | json }}, 
                            null: true,
                            CODE_SI: $("#input_SECTIMP_ENTETE").val(),
                            CODE_STE: {{ caEntet.CODE_STE | json}},
                        };
                    }
                    </script>
                </div>
                {% endif %}
                {% if config.SousCompteAna.isActive and canUpdateSousComptAna %}
                <div class="bs-col-half row">
                    <input type="hidden" name="MODIF_SSCPTEANA" value="0" />
                    {{ inputAdvance('ZOOMADVANCE', {
                        titre: 'Sous compte d\'analyse' | trad,
                        name: 'SSCPTEANA_ENTETE',
                        pahtZoom: path('Ajax.liste.sca'),
                        paramZoom: {
                            CODE_STE: caEntet.CODE_STE, 
                            sca_valide: 1,
                        } | json_encode,
                        entity: 'Sscptana',
                        titleZoom: 'Liste des sous comptes d\'analyse' | trad,
                        pathConvert: path('Ajax.outil.convertLibelle'),
                        convertLibelle: 'convertLibelleGlobal',
                        pathValidator: path('Ajax.validator.sousCompteAnalyse'),
                        paramsValidator: {
                            nomChamp: 'Sous compte d\'analyse' | trad,
                            null: true,
                            CODE_STE: caEntet.CODE_STE
                        } | json_encode,
                        value: caEntet.SSCPTEANA,
                        iconeLabel: 'Inactif2.png',
                        idIconeLabel: 'icone_SSCPTEANA',
                    }) }}
                </div>	
                {% endif %}
            </div>
        </div>
        <script>
            // TODO : improve
            $('[id^=icone_]').click(function(){
                id = $(this).attr('id').replace("icone_", "");
                $input = $('[name=MODIF_'+id+']');
                if($input.val()==0){
                    $(this).find('img').attr({'src' : '{{ baseUrl('IconeV2/Misc/Actif2.png') }}'})
                    $input.val(1)
                } else{
                    $(this).find('img').attr({'src' : '{{ baseUrl('IconeV2/Misc/Inactif2.png') }}'})
                    $input.val(0)
                }
            });
        </script>

        {% include '@Commande/Imputation/imputationFormTable.twig' with {
            config: config,
            listCaLigne: listCaLigne,
            caEntet: caEntet,
        } only %}
    </form>
</section>

<script>
function updateCodeGestInput() {
    let wraSectImp = document.querySelector('[name="SECTIMP_ENTETE"]');
    let inputCodeGest = document.querySelector('[name="CODGES_ENTETE"]');

    // Case : sectimp disabled
    if (inputCodeGest == null) return;

    let wraCodeGest = inputCodeGest.closest('.input-wrapper');
    let textCodeGest = document.querySelector('[name="text_CODGES_ENTETE"]');

    if( wraSectImp.getAttribute('data-sectimp-hascodgest') == 1 ) {
        wraCodeGest.style.visibility = 'visible';
    } else {
        wraCodeGest.style.visibility = 'hidden';
    }

    // reset value code gestion
    inputCodeGest.value = '';
    textCodeGest.value = '';
}

// On SectImput changes -> hide/show input CodeGest
document.addEventListener('change',(event) => {
    if (event.target.name != 'SECTIMP_ENTETE') return;

    updateCodeGestInput();
});
updateCodeGestInput();
</script>
<script>
window.action.impMassUpdateSuccess = function (data) {
    let table = document.querySelector('[data-main-table]');
    table.outerHTML = data;
    desactiveLoader();
};

window.action.impMassUpdateError = function (xhr, form) {
    
    desactiveLoader();

    
    if (xhr.getResponseHeader('Content-Type') == 'application/json') {
        let response = JSON.parse(xhr.responseText);

        // Failsafe : only handle response 'confirm' for json content type
        if (response.type != 'confirm') {
            throw '!!!';
        }
        activePopup(
            {{ 'Erreur validation' | trad | json }},
            response.popupHtml,
            'modal_small'
        );
        document.querySelector('[data-popupwarning-cancel]')
            .addEventListener('click', function () {
                desactivePopup();
            });
        document.querySelector('[data-popupwarning-continue]')
            .addEventListener('click', function () {
                // Resend form with confirm
                formData = new FormData();
                formData.append('confirm', '1');
                ajaxSubmit(form, formData);
                desactivePopup();
            });
        return;
    }

    
    // Assume http 400 -> show constraint validation error
    activePopup(
        {{ 'Erreur validation' | trad | json  }},
        xhr.responseText,
        'modal_small'
    );
};

</script>
{% endblock %}