function initSubmenuForm() {
    // Accéder aux informations stockées du parcours
    const parcours = JSON.parse(sessionStorage.getItem('parcours'));
}

// Exposer initSubmenuForm globalement pour y accéder depuis l'extérieur
window.initSubmenuForm = initSubmenuForm;// Module IIFE pour éviter la pollution de l'espace global
(function () {

    //Variables modulos et liste
    var objModNatureMar, objModMontantCA, objModAct, objModCond, objModZoneTransp, objModTPPC, objMarEnExpo, objModRG
    const listeNatureMarObj = {}
    const listeActiviteObj = {}

    // Variables propositions
    let sansFranchise, franchise350, franchise750

    //variables modale tarif commercial
    const seuil = 15

    //variables de calculs
    var tauxCotRG = 1

    // Accéder aux informations stockées du parcours
    parcours = JSON.parse(sessionStorage.getItem('parcours'));
    contrat = JSON.parse(sessionStorage.getItem('contrat'));
    fac = contrat?.["@expand"]?.enCours || null;
    tarif = fac?.["@expand"]?.tarif || null;

    console.log("Initialisation pour formulaire projet :", parcours);

    // Initialisation du formulaire et des données
    function init() {
        var select = document.querySelectorAll('select');
        M.FormSelect.init(select);

        var modals = document.querySelectorAll('.modal');
        M.Modal.init(modals);

        constantsJSON().then(() => {
            fillSelects();
            populateFormData();
            checkInputs();

        })
        afficherFAC()
        setupTableEventListeners()
    }

    function setupTableEventListeners() {

        document.querySelectorAll('input[name="typeFlux"]').forEach((input) => {
            input.addEventListener("change", function () {
                toggleTypeFlux(this.value)
            })
        })

        document.querySelectorAll('input[name="fluxDetailles"]').forEach((input) => {
            input.addEventListener("change", function () {
                toggleFluxDetailles()
            })
        })

        document.getElementById('TPPC').addEventListener('change', function () {
            document.getElementById('col-typetppc').style.display = this.checked ? "block" : "none"
        })

        document.getElementById('marEnExpo').addEventListener('change', function () {
            document.getElementById('col-marEnExpo').style.display = this.checked ? "block" : "none"
        })

        document.getElementById('rg').addEventListener('change', function () {
            document.getElementById('col-typeRG').style.display = this.checked ? "block" : "none"
        })

        document.getElementById('affinerTarif').addEventListener('change', function () {
            document.getElementById('row-sinistresAsIf').style.display = this.checked ? "block" : "none"
        })

        document.getElementById('risqueGuerreAchats').addEventListener('change', function () {
            document.getElementById('row-typeGarantieRGAchats').style.display = this.checked ? "block" : "none"
        })

        document.getElementById('risqueGuerreVentes').addEventListener('change', function () {
            document.getElementById('row-typeGarantieRGVentes').style.display = this.checked ? "block" : "none"
        })

        document.querySelectorAll("[name='zone']").forEach((zone) => {
            zone.addEventListener('change', function () {
                if (this.checked) {
                    const chip = document.getElementById("chip-modulo-zone")
                    const transport = document.querySelector('[name="moyenTransportGlobal"]:checked').value
                    const zone = document.querySelector('[name="zone"]:checked').value
                    updateModuloChip(chip, calcModZoneTransp(zone, transport))
                }
            })
        })

        document.querySelectorAll('[name="zone"], [name="zoneVentes"], [name="zoneAchats"]').forEach((checkbox) => {
            checkbox.addEventListener('change', function () {
                checkZones(this.value, this.name)
            })
        })

        document.getElementById('sinistres').addEventListener('input', function () {
            const chip = document.getElementById('chip-primePlancher')
            updateModuloChip(chip, calcPrimePlancher(), false)
        })

        document.querySelectorAll('.franchise-card button').forEach((button) => button.addEventListener('click', function (e) {
            e.preventDefault()
            openModaleTarifCom(this.name)
        }))

        document.querySelectorAll('.natureMar-autocomplete').forEach((input) => {
            input.addEventListener('change', function () {
                checkNatureMar(this)
            })
        })

        document.getElementById('activite').addEventListener('change', function () {
            checkActivite(this);
        })

        document.getElementById('sinistres').addEventListener('input', function () {
            const chip = document.getElementById('chip-primePlancher')
            updateModuloChip(chip, calcPrimePlancher(), false)
        })


        document.getElementById('sinistresAsIf').addEventListener('input', function () {
            const chip = document.getElementById('chip-modulo-sinistresAsIf')
            const sinistres = document.getElementById('sinistresAsIf').value

            updateModuloChip(chip, calcPrimeCS(sinistres), false)
        })

        document.getElementById('police').addEventListener('change', function () {
            document.querySelectorAll('.natureMar-autocomplete').forEach((input) => {
                if (input.value !== "") {
                    checkNatureMar(input)
                }
            })

            const chip = document.getElementById('chip-modulo-police')
            updateModuloChip(chip, calcModPolice(this.value))
        })

        document.getElementById("nbVehicTPPC").addEventListener('input', function () {
            if (this.value > 5) {
                const elem = document.getElementById('modalTPPC');
                const instance = M.Modal.getInstance(elem);
                instance.open()
                this.value = 5
            }
        })

        document.getElementById("capitalTPPC").addEventListener('input', function () {
            if (this.value > 99999) {
                const elem = document.getElementById('modalTPPC');
                const instance = M.Modal.getInstance(elem);
                instance.open()
                this.value = 99999
            }
        })

        document.getElementById('montant').addEventListener('input', function () {
            const chip = document.getElementById('chip-modulo-montant')
            updateModuloChip(chip, calcModMontantCA(this.value, getCA()))
        })

        document.getElementById('marchandise').addEventListener('input', function () {
            const chip = document.getElementById('chip-modulo-marchandise')
            updateModuloChip(chip, calcModNatureMar(this.value))
        })


        document.getElementById('conditionnementGlobal').addEventListener('change', function () {
            const chip = document.getElementById('chip-modulo-cond')
            updateModuloChip(chip, calcModCond(this.value))
        })

        document.getElementById('conditionnementAchats').addEventListener('change', function () {
            const chip = document.getElementById('chip-modulo-condAchats')
            updateModuloChip(chip, calcModCond(this.value))
        })

        document.getElementById('conditionnementVentes').addEventListener('change', function () {
            const chip = document.getElementById('chip-modulo-condVentes')
            updateModuloChip(chip, calcModCond(this.value))
        })

        document.getElementById('addAsIf').addEventListener('click', function () {
            addAsIf()
        })

        document.querySelectorAll('[name=zoneAchats],[name=moyenTransportAchats]').forEach((input) => {
            input.addEventListener('change', function () {
                if (this.checked) {
                    const zone = document.querySelector('[name="zoneAchats"]:checked')?.value
                    const transport = document.querySelector('[name="moyenTransportAchats"]:checked')?.value
                    const chip = document.getElementById('chip-modulo-zoneAchats')

                    updateModuloChip(chip, calcModZoneTransp(zone, transport))
                }
            })
        })

        document.querySelectorAll('[name=zoneVentes],[name=moyenTransportVentes]').forEach((input) => {
            input.addEventListener('change', function () {
                if (this.checked) {
                    const zone = document.querySelector('[name="zoneVentes"]:checked')?.value
                    const transport = document.querySelector('[name="moyenTransportVentes"]:checked')?.value
                    const chip = document.getElementById('chip-modulo-zoneVentes')

                    updateModuloChip(chip, calcModZoneTransp(zone, transport))
                }
            })
        })

        document.querySelectorAll('#valeurAnnuelleVentes, #valeurAnnuelleAchats, #montantVentes, #montantAchats').forEach((input) => {
            input.addEventListener('input', function () {
                const chipAchats = document.getElementById('chip-modulo-montantAchats')
                const chipVentes = document.getElementById('chip-modulo-montantVentes')

                const modulo = calcModMontantCA(getMontantTotal(), getValeurAnnuelleTotal())
                updateModuloChip(chipAchats, modulo)
                updateModuloChip(chipVentes, modulo)
            })
        })

        document.querySelectorAll('[name="btnZone1"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZone1');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="btnZone2"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZone2');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="btnZone3"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZone3');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="btnZone4"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZone4');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="btnZone5"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZone5');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="btnZone6"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZone6');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="btnZone7"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZoneExclus');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="zonesInfos"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalZones');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('[name="marchandiseInfos"]').forEach((button) => {
            button.addEventListener('click', function () {
                const elem = document.getElementById('modalMarchandise');
                const instance = M.Modal.getInstance(elem);
                instance.open()
            })
        })

        document.querySelectorAll('input, select').forEach((input) => {
            const recalcul = () => {
                stepExtensions()

                if (checkInputs()) {
                    document.getElementById('propositions').style.display = "flex"
                    document.getElementById('row-champsManquants').style.display = "none"

                    sansFranchise = calcCard(1)
                    franchise350 = calcCard(0.9)
                    franchise750 = calcCard(0.85)

                    fillPropCard('sansFranchise', sansFranchise)
                    fillPropCard('franchise350', franchise350)
                    fillPropCard('franchise750', franchise750)
                } else {
                    document.getElementById('propositions').style.display = "none"
                    document.getElementById('row-champsManquants').style.display = "block"
                }
            }
            input.addEventListener('input', recalcul)
            input.addEventListener('change', recalcul)
        })

        document.getElementById('comm-OK').addEventListener('click', function () {
            submitForm(this.name)
        })

        document.getElementById('commentaire').addEventListener('input', function () {
            if (document.getElementById('commentaire').value == "") {
                document.getElementById('comm-OK').disabled = true
            } else {
                document.getElementById('comm-OK').disabled = false
            }
        })

        document.getElementById('loadHistoriqueBtn').addEventListener('click', function () {
            handleLoadHistoriqueBtn();
        });

    }

    //Appel pour recevoir les constantes 
    async function constantsJSON() {
        try {
            const responsesJSON = await Promise.all([
                fetch('/fac/modulo/natureMar'),
                fetch('/fac/modulo/montantCA'),
                // fetch('/fac/modulo/franchiseTousCas'),
                fetch('/fac/modulo/activite'),
                fetch('/fac/modulo/conditionnement'),
                fetch('/fac/modulo/zoneTransport'),
                fetch('/fac/modulo/tppc'),
                fetch('/fac/modulo/marEnExpo'),
                fetch('/fac/modulo/rg'),
            ]);
            const jsonResponses = await Promise.all(responsesJSON.map(r => r.json())); // Récupérer toutes les réponses JSON

            // Extraire la valeur objRetourne de chaque réponse
            [
                objModNatureMar,
                objModMontantCA,
                // objModFranchiseTousCas,
                objModAct,
                objModCond,
                objModZoneTransp,
                objModTPPC,
                objMarEnExpo,
                objModRG
            ] = jsonResponses.map(response => response.objRetourne); // Adapter pour extraire objRetourne
        } catch (err) {
            throw err;
        }
    }

    function checkActivite(input, showError = true) {
        const errorElement = document.getElementById('activite-error')
        const moduloChipAct = document.getElementById('chip-modulo-activite')
        if (Object.keys(objModAct).includes(input.value)) {
            if (showError) {
                errorElement.textContent = ""
                errorElement.style.display = "none"
                updateModuloChip(moduloChipAct, calcModAct(input.value))
            }
            return true
        } else {
            if (showError) {
                errorElement.textContent = "Veuillez selectionner une activité parmi la liste"
                errorElement.style.display = "block"
                updateModuloChip(moduloChipAct, null)
            }
            return false
        }
    }

    function checkNatureMar(input, showError = true) {
        const errorElement = document.getElementById(input.id + '-error')
        const moduloChipAct = document.getElementById('chip-modulo-' + input.id)

        if (Object.keys(objModNatureMar).includes(input.value)) {
            if (showError) {
                errorElement.textContent = ""
                errorElement.style.display = "none"
                updateModuloChip(moduloChipAct, calcModNatureMar(input.value))
            }
            return true
        } else {
            if (showError) {
                errorElement.textContent = "Veuillez selectionner une nature de marchandise parmi la liste"
                errorElement.style.display = "block"
                updateModuloChip(moduloChipAct, null)
            }
            return false
        }
    }

    function getTypeFlux() {
        return document.querySelector('[name="typeFlux"]:checked').value
    }

    function getPolice() {
        return document.querySelector('#police').value
    }

    function getTempo() {
        const police = getPolice()
        if (police == "ca") {
            return "annuel"
        } else if (police == "national" || police == "international") {
            return "tempo"
        }

        return null
    }

    function getTypeMar() {
        if (getTypeFlux() == "global") {
            return document.getElementById('marchandise').value
        } else {
            const actArray = []
            const marAchats = document.getElementById('natureMarAchats').value
            const marVentes = document.getElementById('natureMarVentes').value

            if (marAchats !== "" && isAchatsSelected()) {
                actArray.push(marAchats)
            }
            if (marVentes !== "" && isVentesSelected()) {
                actArray.push(marVentes)
            }

            return actArray.join(', ')
        }
    }

    function getCA() {
        return document.getElementById('ca').value
    }

    function getMontantTotal() {
        if (getTypeFlux() == "global") {
            return document.getElementById('montant').value
        } else if (getTypeFlux() == "detailles") {
            var sommeMontant = 0
            if (isAchatsSelected()) {
                sommeMontant += parseFloat(document.getElementById("montantAchats").value)
            }
            if (isVentesSelected()) {
                sommeMontant += parseFloat(document.getElementById("montantVentes").value)
            }
            return sommeMontant
        }
    }

    function getValeurAnnuelleTotal() {
        if (getTypeFlux() == "detailles") {
            var sommeMontant = 0
            if (isAchatsSelected()) {
                sommeMontant += parseFloat(document.getElementById("valeurAnnuelleAchats").value)
            }
            if (isVentesSelected()) {
                sommeMontant += parseFloat(document.getElementById("valeurAnnuelleVentes").value)
            }
            return sommeMontant
        } else {
            return false
        }
    }

    function getRisqueGuerre() {
        const rgGlobal = document.querySelector('[name="typeGarantieRG"]:checked').value
        const rgGlobalCheckbox = document.getElementById('rg').checked

        const rgVentes = document.querySelector('[name="typeGarantieRGVentes"]:checked').value
        const rgVentesCheckbox = document.getElementById('risqueGuerreVentes').checked
        const rgAchats = document.querySelector('[name="typeGarantieRGAchats"]:checked').value
        const rgAchatsCheckbox = document.getElementById('risqueGuerreAchats').checked

        if (getTypeFlux() == "global" && rgGlobalCheckbox) {
            return [rgGlobal]
        } else if (getTypeFlux() == "detailles") {
            const rg = []
            if (isAchatsSelected() && rgAchatsCheckbox) {
                rg.push(rgAchats)
            }

            if (isVentesSelected() && rgVentesCheckbox) {
                rg.push(rgVentes)
            }

            return rg
        }

        return []
    }

    function getZones() {
        if (getTypeFlux() == "global") {
            return [document.querySelector('[name="zone"]:checked').value]
        } else if (getTypeFlux() == "detailles") {
            const zones = []
            if (isAchatsSelected()) {
                zones.push(document.querySelector('[name="zoneAchats"]:checked').value)
            }
            if (isVentesSelected()) {
                zones.push(document.querySelector('[name="zoneVentes"]:checked').value)
            }
            return zones
        }

        return []
    }

    function getTransportTypeRO(transport) {
        if (getTypeFlux() == "global") {
            if (document.getElementById(transport + '-global') && document.getElementById(transport + '-global').checked) {
                return document.querySelector('[name="risqueOrdinaire"]:checked').value
            }
        } else {
            const checkboxAchats = document.getElementById(transport + '-achats')
            const checkboxVentes = document.getElementById(transport + '-ventes')

            if ((checkboxAchats && checkboxAchats.checked) || (checkboxVentes && checkboxVentes.checked)) {
                return document.querySelector('[name="risqueOrdinaire"]:checked').value
            }
        }
        return ""
    }

    function isAchatsSelected() {
        return (document.getElementById('achats').checked) && (getTypeFlux() == "detailles")
    }

    function isVentesSelected() {
        return (document.getElementById('ventes').checked) && (getTypeFlux() == "detailles")
    }

    function calcModPolice(police) {
        if (police == "ca") {
            return 0.9
        } else if (police == "international" || police == "national") {
            return 1
        } else {
            return false
        }
    }

    function calcPrimeMini(police) {
        switch (police) {
            case "national":
                return 300;

            case "international":
                return 300;

            case "ca":
                return 800;
        }
    }

    function calcPrimePlancher() {
        const sinistres = document.getElementById('sinistres')

        if (sinistres.value !== "") {
            return parseFloat((sinistres.value * 100 / 65).toFixed(2))
        } else {
            return false
        }
    }

    function calcModAct(activite) {
        if (activite == "") {
            return false
        }
        if (!Object.keys(objModAct).includes(activite)) {
            return false
        }
        return parseFloat(objModAct[activite])
    }

    function calcModNatureMar(natureMar) {
        if (natureMar == "") {
            return false
        }
        if (!Object.keys(objModNatureMar).includes(natureMar)) {
            return false
        }

        var coeffTempo = 1

        if (getTempo() == "tempo") {
            coeffTempo = 1.2
        }

        return Number((objModNatureMar[natureMar].taux * coeffTempo).toFixed(5))
    }

    function getModNatureMar() {
        if (getTypeFlux() == "global") {
            const marchandise = document.getElementById('marchandise').value
            return calcModNatureMar(marchandise)
        } else if (getTypeFlux() == "detailles") {
            var modNatureMar = 1
            if (isAchatsSelected()) {
                const marchandise = document.getElementById('natureMarAchats').value
                modNatureMar *= calcModNatureMar(marchandise)
            }

            if (isVentesSelected()) {
                const marchandise = document.getElementById('natureMarVentes').value
                modNatureMar *= calcModNatureMar(marchandise)
            }
            return modNatureMar
        }
    }

    function calcModMontantCA(montant, ca) {
        if (montant && ca) {
            const palierCA = Object.keys(objModMontantCA)
                .map(palier => Number(palier))
                .sort((a, b) => a - b)
                .find((p) => ca <= p);
            if (!palierCA || palierCA == undefined) return false;

            const palierMontant = Object.keys(objModMontantCA[palierCA])
                .map(palier => Number(palier))
                .sort((a, b) => a - b)
                .find((p) => montant <= p);

            if (!palierMontant || palierMontant == undefined) return false;

            return objModMontantCA[palierCA][palierMontant];
        } else {
            return false
        }
    }

    function calcModCond(conditionnement) {
        if (Object.keys(objModCond).includes(conditionnement)) {
            return objModCond[conditionnement]["modulo"]
        } else {
            return false
        }
    }

    function calcModZoneTransp(zone, transport) {
        if (zone && transport) {
            return objModZoneTransp[zone][transport]
        } else {
            return false
        }
    }

    function calcTPPC(prime) {
        const montant = document.getElementById('capitalTPPC').value
        var tppc = 0
        var franchise = ""

        const palierModulo = Object.keys(objModTPPC)
            .map(palier => Number(palier))
            .sort((a, b) => a - b)
            .find((p) => montant <= p)

        const modulo = objModTPPC[palierModulo]?.modulo || 0
        franchise = objModTPPC[palierModulo]?.franchise
        tppc = prime * modulo

        return {
            tppc: tppc,
            franchise: franchise
        }
    }

    function calcMarEnExpo(cotRO) {
        // Calcul de la majoration en exposition
        const nbExpo = document.getElementById('nombreExposition').value
        const capital = document.getElementById('capitalExposition').value
        const type = document.getElementById('typeMarEnExpo').value

        var marEnExpo = 0
        var franchise = ""

        if (nbExpo && capital && type) {
            if (capital < 20000) {
                marEnExpo = 0
                franchise = 500
            } else if (nbExpo > 3 || capital > 50000) {
                marEnExpo = nbExpo * capital * objMarEnExpo[type] / 100
                marEnExpo = marEnExpo > cotRO * 0.1 ? cotRO * 0.1 : marEnExpo
                // franchise = "10% mini 150 maxi 1000"
                franchise = 150
            } else {
                marEnExpo = cotRO * 0.1 < 150 ? cotRO * 0.1 : 150
                // franchise = "10% mini 150 maxi 1000"
                franchise = 150
            }
        }

        return {
            marEnExpo: marEnExpo,
            franchise: franchise,
        }
    }

    function calcRG() {
        const typeFlux = getTypeFlux()
        var rg = 0

        if (typeFlux == "global" && document.getElementById('rg').checked) {
            const engagement = document.getElementById('engagementRG').value
            const zone = document.querySelector('[name="zone"]:checked').value
            const typeRG = document.querySelector('[name="typeGarantieRG"]:checked').value

            tauxCotRG = objModRG[zone][typeRG]
            rg = engagement * tauxCotRG
        } else if (typeFlux == "detailles") {
            var rgAchats = 0
            var rgVentes = 0
            var tauxAchats = 1
            var tauxVentes = 1

            if (isAchatsSelected() && document.getElementById('risqueGuerreAchats').checked) {
                const engagementAchats = parseFloat(document.getElementById('engagementRGAchats').value)
                const zone = document.querySelector('[name="zoneAchats"]:checked').value
                const typeRG = document.querySelector('[name="typeGarantieRGAchats"]:checked').value
                tauxAchats = objModRG[zone][typeRG]
                rgAchats = engagementAchats * tauxAchats
            }

            if (isVentesSelected() && document.getElementById('risqueGuerreVentes').checked) {
                const engagementVentes = parseFloat(document.getElementById('engagementRGVentes').value)
                const zone = document.querySelector('[name="zoneVentes"]:checked').value
                const typeRG = document.querySelector('[name="typeGarantieRGVentes"]:checked').value
                tauxVentes = objModRG[zone][typeRG]
                rgVentes = tauxVentes * engagementVentes
            }
            tauxCotRG = tauxAchats * tauxVentes
            rg = rgAchats + rgVentes
        }

        return rg
    }

    function calcPrimeRef(modFranchise) {
        const typeFlux = getTypeFlux()

        var modPolice = calcModPolice(getPolice())

        const activite = document.getElementById('activite').value
        const modAct = calcModAct(activite)
        var primeRef = 0

        if (typeFlux == "global") {

            const conditionnement = document.querySelector('#conditionnementGlobal').value
            const marchandise = document.getElementById('marchandise').value
            const zone = document.querySelector('[name="zone"]:checked')?.value
            const transport = document.querySelector('[name="moyenTransportGlobal"]:checked')?.value
            const montant = getMontantTotal()
            const ca = getCA()

            modNatureMar = calcModNatureMar(marchandise)
            const modCond = calcModCond(conditionnement)
            const modZoneTransp = calcModZoneTransp(zone, transport)
            const modMontantCA = calcModMontantCA(montant, ca)

            const coeff = modNatureMar * modPolice * modFranchise * modCond * modZoneTransp * modMontantCA * modAct

            primeRef = ca * coeff

        } else if (typeFlux == "detailles") {
            var primeVentes = 0, primeAchats = 0
            if (isAchatsSelected()) {
                primeAchats = calcPrimeAchats()
            }

            if (isVentesSelected()) {
                primeVentes = calcPrimeVentes()
            }
            primeRef = primeAchats + primeVentes
        }
        return primeRef
    }

    function calcPrimeCS(sinistre) {
        const affinerTarif = document.getElementById("affinerTarif").checked
        if (affinerTarif && sinistre > 0) {
            return (sinistre * 100 / 65).toFixed(2)
        }
        return false
    }

    function checkInputs() {
        const typeFlux = getTypeFlux()

        //CHAMPS COMMUN
        const inputActivite = document.getElementById('activite')
        const activite = inputActivite.value || false
        const ca = document.getElementById('ca').value || false
        const police = getPolice()


        //CHAMPS POUR FLUX GLOBAL
        const conditionnement = document.querySelector('#conditionnementGlobal').value || false

        const inputMarchandise = document.getElementById('marchandise')
        const marchandise = inputMarchandise.value || false

        const zone = document.querySelector('[name="zone"]:checked') || false
        const transport = document.querySelector('[name="moyenTransportGlobal"]:checked') || false
        const montant = document.getElementById('montant').value && validateField('montant') || false

        //CHAMPS POUR FLUX DETAILS
        const inputMarchandiseAchats = document.getElementById('natureMarAchats')
        const valeurAnnuelleAchats = document.getElementById("valeurAnnuelleAchats").value || false
        const montantAchats = document.getElementById("montantAchats").value && validateField('montantAchats') || false
        const transportAchats = document.querySelector('[name="moyenTransportAchats"]:checked') || false
        const conditionnementAchats = document.querySelector('#conditionnementAchats').value || false
        const zoneAchats = document.querySelector('[name="zoneAchats"]:checked') || false

        const inputMarchandiseVentes = document.getElementById('natureMarVentes') || false
        const valeurAnnuelleVentes = document.getElementById("valeurAnnuelleVentes").value || false
        const montantVentes = document.getElementById("montantVentes").value && validateField('montantVentes') || false
        const transportVentes = document.querySelector('[name="moyenTransportVentes"]:checked') || false
        const conditionnementVentes = document.querySelector('#conditionnementVentes').value || false
        const zoneVentes = document.querySelector('[name="zoneVentes"]:checked') || false

        //INPUT CHIPS

        const chipAct = document.getElementById("chip-act");
        const chipPolice = document.getElementById("chip-police");
        const chipCA = document.getElementById("chip-ca");
        const chipNatureMar = document.getElementById("chip-natureMar");
        const chipTransport = document.getElementById("chip-transport");
        const chipConditionnement = document.getElementById("chip-conditionnement");
        const chipMontant = document.getElementById("chip-montant");
        const chipZone = document.getElementById("chip-zone");
        const chipValeurAnnuelle = document.getElementById("chip-valeurAnnuelle");

        updateInputChip(chipAct, checkActivite(inputActivite, false))
        updateInputChip(chipPolice, police)
        updateInputChip(chipCA, ca)

        if (typeFlux == "global") {
            updateInputChip(chipNatureMar, checkNatureMar(inputMarchandise, false))
            updateInputChip(chipTransport, transport)
            updateInputChip(chipConditionnement, conditionnement)
            updateInputChip(chipMontant, montant)
            updateInputChip(chipZone, zone)
            updateInputChip(chipValeurAnnuelle, true)

            return ((conditionnement && marchandise && zone && transport && activite && montant && ca && police))

        } else if (typeFlux == "detailles") {
            let boolNatureMar = false;
            let boolTransport = false;
            let boolConditionnement = false;
            let boolMontant = false;
            let boolZone = false;
            const sources = [];

            if (isAchatsSelected()) {
                sources.push({
                    natureMar: checkNatureMar(inputMarchandiseAchats, false),
                    transport: transportAchats,
                    conditionnement: conditionnementAchats,
                    montant: montantAchats,
                    zone: zoneAchats,
                    valeurAnnuelle: valeurAnnuelleAchats,
                });
            }

            if (isVentesSelected()) {
                sources.push({
                    natureMar: checkNatureMar(inputMarchandiseVentes, false),
                    transport: transportVentes,
                    conditionnement: conditionnementVentes,
                    montant: montantVentes,
                    zone: zoneVentes,
                    valeurAnnuelle: valeurAnnuelleVentes,
                });
            }

            // Agrégation des booléens avec un ET logique
            boolNatureMar = sources.every(s => s.natureMar);
            boolTransport = sources.every(s => s.transport);
            boolConditionnement = sources.every(s => s.conditionnement);
            boolMontant = sources.every(s => s.montant);
            boolZone = sources.every(s => s.zone);
            boolValeurAnnuelle = sources.every(s => s.valeurAnnuelle)

            updateInputChip(chipNatureMar, boolNatureMar);
            updateInputChip(chipTransport, boolTransport);
            updateInputChip(chipConditionnement, boolConditionnement);
            updateInputChip(chipMontant, boolMontant);
            updateInputChip(chipZone, boolZone);
            updateInputChip(chipValeurAnnuelle, boolValeurAnnuelle)

            return boolNatureMar && boolTransport && boolConditionnement && boolMontant && boolZone && boolValeurAnnuelle && activite && ca && police;
        }
    }

    function toggleTypeFlux(type) {
        if (type == "detailles") {
            document.getElementById('row-fluxDetailles').style.display = "flex"
            document.getElementById('div-infoMarchandises').style.display = "none"
            document.getElementById('div-transport').style.display = "none"
            document.getElementById('div-zonesGeo').style.display = "none"
            document.getElementById('div-flux').style.display = "block"
            document.getElementById('row-rg').style.display = "none"
            toggleFluxDetailles()

        } else if (type == "global") {
            document.getElementById('row-fluxDetailles').style.display = "none"
            document.getElementById('div-infoMarchandises').style.display = "block"
            document.getElementById('div-transport').style.display = "block"
            document.getElementById('div-zonesGeo').style.display = "block"
            document.getElementById('div-flux').style.display = "none"
            document.getElementById('row-rg').style.display = "block"
        }
    }

    function toggleFluxDetailles() {
        const ventes = document.querySelector('input#ventes[name="fluxDetailles"]')
        const achats = document.querySelector('input#achats[name="fluxDetailles"]')
        const intersites = document.querySelector('input#intersites[name="fluxDetailles"]')

        /*Intersites ne peut pas être sélectionné seul*/
        if (intersites.checked && (!isVentesSelected() && !isAchatsSelected())) {
            intersites.checked = false
            achats.checked = true
        }

        /*Il ne peut y avoir aucun flux sélectionné*/
        if (document.querySelectorAll('[name="fluxDetailles"]:checked').length == 1) {
            document.querySelector('[name="fluxDetailles"]:checked').disabled = true
            document.querySelectorAll('[name="fluxDetailles"]:not(:checked)').forEach((checkbox) => {
                checkbox.disabled = false
            })
        } else {
            ventes.disabled = false
            achats.disabled = false
            intersites.disabled = false
        }

        /*Affichage*/
        document.getElementById('div-fluxAchats').style.display = achats.checked ? "block" : "none"
        document.getElementById('div-fluxVentes').style.display = ventes.checked ? "block" : "none"
    }

    function afficherFAC() {
        toggleTypeFlux(document.querySelector('[name="typeFlux"]:checked').value)
    }

    function updateModuloChip(elementModulo, valeur, isModulo = true) {
        if (valeur == null || valeur == false) {
            elementModulo.style.display = "none"
        } else {
            elementModulo.style.display = "inline-block"
            const titreModulo = elementModulo.innerText.split(' : ')[0]
            if (isModulo) {
                elementModulo.innerText = titreModulo + ' : x' + valeur
            } else if (!isModulo) {
                elementModulo.innerText = titreModulo + ' : ' + valeur + '€'
            }
        }
    }

    function updateStepChip(elementModulo, valeur) {
        if (valeur == null || valeur == false) {
            elementModulo.style.display = "none"
        } else {
            elementModulo.style.display = "inline-block"
            elementModulo.innerText = "Prime : " + new Intl.NumberFormat("fr-FR", {style: "currency", currency: "EUR"}).format(valeur)
        }
    }

    function updateInputChip(chip, valeur) {
        if (valeur != "" && valeur != null && valeur != false) {
            chip.style.display = "none"
        } else {
            chip.style.display = "inline-block"
        }
    }

    // Supprimer une ligne du tableau 
    function deleteAsIf(btn) {
        const row = btn.parentElement.parentElement;
        row.parentElement.removeChild(row);
    }


    function addAsIf(franchise = "", sinistre = "") {
        var prime, display = "none"
        if (franchise && sinistre) {
            prime = calcPrimeCS(sinistre)
            display = "inline-block"
        }

        const newRow = document.createElement("div")
        newRow.className = "row mrg asIfRow"
        newRow.innerHTML = `                    
                    <div class="col s1">
                        <button class="btn delete-btn" type="button">
                            <i class="material-icons">delete</i>
                        </button>
                    </div>
                    <div class="col s4">
                        <label class="left">Franchise As If</label>
                        <div class="input-field" style="margin : 0">
                            <input type="number" class="franchiseAsIf" placeholder="En (€)" value=`+ franchise + `>
                        </div>
                        <span class="helper-text red-text"></span>
                    </div>
                    <div class="col s4">
                        <label class="left">Charge sinistre annuelle revue selon as if
                            franchise</label>
                        <div class="input-field" style="margin : 0">
                            <input type="number" class="sinistresAsIf" placeholder="En (€)" value=`+ sinistre + `>
                        </div>
                        <span class="helper-text red-text"></span>
                    </div>
                    <div class="col s3">
                        <div class="chip modulo red" name="chip-modulo-sinistresAsIf" style="display: `+ display + `;">
                            Prime Plancher Indicative : `+ prime + `€
                        </div>
                    </div>
                </div>`

        newRow.querySelector('.sinistresAsIf').addEventListener('input', function () {
            const chip = newRow.querySelector('.modulo')
            updateModuloChip(chip, calcPrimeCS(this.value), false)
        })

        newRow.querySelector('.delete-btn').addEventListener('click', function () {
            deleteAsIf(this)
        })

        document.getElementById('row-sinistresAsIf').appendChild(newRow)
    }

    function extractAsIf() {
        if (document.getElementById("affinerTarif").checked == "false") {
            return ""
        } else {
            const extractArray = []
            document.querySelectorAll('.asIfRow').forEach((row) => {
                const franchise = row.querySelector('.franchiseAsIf').value
                const sinistres = row.querySelector('.sinistresAsIf').value
                if (franchise !== "" && sinistres !== "") {
                    var obj = {
                        franchise: franchise,
                        sinistres: sinistres

                    }
                    extractArray.push(obj)
                }
            })
            const jsonResult = JSON.stringify(extractArray, null, 2);
            return jsonResult;
        }
    }

    function fillSelects() {

        const optionCreator = (text, value) => {
            let option = document.createElement('option')
            option.value = value
            option.text = text
            return option
        }

        //Creation objets avec liste d'activité en clé, et null en valeur
        for (const natureMar of Object.keys(objModNatureMar)) {
            listeNatureMarObj[natureMar] = null
        }

        var elems = document.querySelectorAll('.natureMar-autocomplete');
        M.Autocomplete.init(elems, {
            data: listeNatureMarObj,
            limit: 10
        })


        //Creation objets avec liste d'activité en clé, et null en valeur
        for (const activite of Object.keys(objModAct)) {
            listeActiviteObj[activite] = null
        }

        var elems = document.querySelectorAll('.activite-autocomplete');
        M.Autocomplete.init(elems, {
            data: listeActiviteObj,
            limit: 10
        })

        //Remplissage des selects
        const selectCond = document.querySelectorAll('select[name="conditionnement"]')
        const selectMarEnExpo = document.getElementById('typeMarEnExpo')

        for (const [key, value] of Object.entries(objModCond)) {
            selectCond.forEach((select) => {
                if (select.id == "conditionnementGlobal" && value['fluxGlobal']) {
                    select.add(optionCreator(value['nom'], key))
                }
                else if (select.id !== "conditionnementGlobal" && value['fluxDetailles']) {
                    select.add(optionCreator(value['nom'], key))
                }
            })
        }

        for (const [key, value] of Object.entries(objMarEnExpo)) {
            selectMarEnExpo.add(optionCreator(key, key))
        }

        var select = document.querySelectorAll('select');
        M.FormSelect.init(select);
    }

    function populateFormData() {
        // Populate select historique
        if (!contrat.historique) {
            document.getElementById('historiqueDiv').style.display = "none";
        } else {
            document.getElementById('historiqueDiv').style.display = "block";

            const idSelect = document.getElementById('idSelect');

            contrat.historique.forEach(function (item) {
                if (item) {
                    var option = document.createElement('option');
                    option.value = item.id;
                    option.textContent = item.type + " " + item.produit + " - " + item.date + " - " + item.heure;

                    if (item.nom != undefined && item.prenom != undefined) {
                        option.textContent += " - " + item.nom + " " + item.prenom;
                    }

                    idSelect.appendChild(option);
                }
            });
            M.FormSelect.init(idSelect);
        }

        if (tarif?.typeFlux) {
            document.getElementById(tarif.typeFlux).checked = true
            toggleTypeFlux(tarif.typeFlux)
        }

        if (fac?.ca) {
            document.getElementById('ca').value = fac.ca
        }

        if (tarif?.typePolice) {
            document.querySelector('select#police option[value=' + tarif.typePolice + ']').selected = true;
            const chip = document.getElementById('chip-modulo-police')
            updateModuloChip(chip, calcModPolice(tarif.typePolice))
            M.FormSelect.init(document.querySelector('select#police'))
        }

        if (fac?.actAssuree) {
            const inputActivite = document.getElementById('activite')
            inputActivite.value = fac.actAssuree
            checkActivite(inputActivite)
        }

        if (fac?.tppc) {
            document.getElementById('TPPC').checked = true
            document.getElementById('capitalTPPC').value = fac?.capitalTPPC ?? 0
            document.getElementById('nbVehicTPPC').value = tarif?.nbVehicTPPC ?? 0
            document.getElementById('col-typetppc').style.display = "block"
        }

        if (tarif?.typeMarExpo || fac?.capitalExpo > 0 || fac?.nbVehicExpo > 0) {
            document.getElementById('col-marEnExpo').style.display = "block"
            document.getElementById('marEnExpo').checked = true
            document.getElementById('capitalExposition').value = fac?.capitalExpo ?? 0
            document.getElementById('nombreExposition').value = fac?.nbVehicExpo ?? 0

            if (tarif?.typeMarExpo) {
                document.querySelector('select#typeMarEnExpo option[value="' + tarif.typeMarExpo + '"]').selected = true;
                M.FormSelect.init(document.querySelector('select#typeMarEnExpo'))
            }
        }

        if (tarif?.typeRO) {
            document.querySelector('input[name=risqueOrdinaire][id=' + tarif?.typeRO + ']').checked = true;
        } else {
            //LORSQUE LE PROJET EXISTE SANS LE TARIF, ON DONNE LA PRIORITE SUR LE TOUS RISQUES
            const terrestre = fac?.terrestre ?? ""
            const maritime = fac?.maritime ?? ""
            const aerien = fac?.aerien ?? ""
            const postal = fac?.postal ?? ""
            const fluvial = fac?.fluvial ?? ""
            const multimodal = fac?.multimodal ?? ""

            const transport = [terrestre, maritime, aerien, postal, fluvial, multimodal]

            if (!transport.every((type) => type == "")) {
                const typeRO = transport.filter((type) => type !== "").includes('tousRisques') ? "tousRisques" : "eventMaj"
                document.querySelector('input[name=risqueOrdinaire][id=' + typeRO + ']').checked = true;
            }
        }

        if (tarif?.oldFranchise && tarif?.sinistres) {
            document.getElementById('oldFranchise').value = tarif.oldFranchise
            document.getElementById('sinistres').value = tarif.sinistres
            const chip = document.getElementById('chip-primePlancher')
            updateModuloChip(chip, calcPrimePlancher(), false)
        }

        if (tarif?.asIf) {
            document.getElementById("affinerTarif").checked = true
            document.getElementById('row-sinistresAsIf').style.display = "block"

            tarif.asIf.forEach((rowAsIf) => {
                addAsIf(rowAsIf.franchise, rowAsIf.sinistres)
            })
        }

        if (tarif?.typeFlux && tarif?.typeFlux == "global" || !tarif) {
            if (fac?.typeMar) {
                const inputNatureMar = document.getElementById('marchandise')
                const chip = document.getElementById('chip-modulo-marchandise')
                inputNatureMar.value = fac.typeMar
                checkNatureMar(inputNatureMar)
                updateModuloChip(chip, calcModNatureMar(fac.typeMar))
            }

            if (tarif?.montantGarantir) {
                document.getElementById('montant').value = tarif.montantGarantir
                const chip = document.getElementById('chip-modulo-montant')
                updateModuloChip(chip, calcModMontantCA(tarif.montantGarantir, fac.ca))
            }

            if (fac?.terrestre) {
                document.querySelector('[name="moyenTransportGlobal"][value="terrestre"] ').checked = true
            }

            if (fac?.multimodal) {
                document.querySelector('[name="moyenTransportGlobal"][value="multimodal"] ').checked = true
            }

            if (tarif?.conditionnement) {
                document.querySelector('select#conditionnementGlobal option[value=' + tarif.conditionnement + ']').selected = true;
                M.FormSelect.init(document.querySelector('select#conditionnementGlobal'))
            }

            if (tarif?.zone) {
                document.querySelector('input[name=zone][id=' + tarif.zone + ']').checked = true;
                checkZones(tarif.zone, "zone")
            } else if (fac?.zones) {
                fac.zones.forEach((zone) => {
                    document.querySelector('input[name=zone][id=' + zone + ']').checked = true;
                    checkZones(zone, "zone")
                })
            }

            if (fac?.typeRG == "auto") {
                document.querySelector('input[name=typeGarantieRG][value=' + fac.typeRG + ']').checked = true;
                document.getElementById('col-typeRG').style.display = "block"
                document.getElementById('rg').checked = true
                if (tarif?.engagementRG > 0) {
                    document.getElementById("engagementRG").value = tarif.engagementRG
                }
            }

        } else if (tarif?.typeFlux == "detailles") {
            document.getElementById('achats').checked = !!tarif.fluxAchats
            document.getElementById('ventes').checked = !!tarif.fluxVentes
            document.getElementById('intersites').checked = tarif.fluxIntersites

            toggleFluxDetailles()

            if (tarif?.fluxAchats) {
                const fluxAchats = tarif.fluxAchats

                const inputNatureMar = document.getElementById('natureMarAchats')
                inputNatureMar.value = fluxAchats.typeMar
                checkNatureMar(inputNatureMar)

                document.getElementById('valeurAnnuelleAchats').value = fluxAchats.valeurAnnuelleAchats
                document.getElementById('montantAchats').value = fluxAchats.montant
                document.querySelector('[name="moyenTransportAchats"][value="' + fluxAchats.transport + '"] ').checked = true

                document.querySelector('select#conditionnementAchats option[value=' + fluxAchats.conditionnement + ']').selected = true;
                M.FormSelect.init(document.querySelector('select#conditionnementAchats'))
                const chipCondAchats = document.getElementById('chip-modulo-condAchats')
                updateModuloChip(chipCondAchats, calcModCond(fluxAchats.conditionnement))

                document.querySelector('input[name=zoneAchats][value=' + fluxAchats.zone + ']').checked = true;
                checkZones(fluxAchats.zone, "zoneAchats")
                const chipZoneTransp = document.getElementById('chip-modulo-zoneAchats')
                updateModuloChip(chipZoneTransp, calcModZoneTransp(fluxAchats.zone, fluxAchats.transport))

                if (fluxAchats.typeRG) {
                    document.querySelector('input[name=typeGarantieRGAchats][value=' + fluxAchats.typeRG + ']').checked = true;
                    document.getElementById("engagementRGAchats").value = fluxAchats.engagementRG
                    document.getElementById('row-typeGarantieRGAchats').style.display = "block"
                    document.getElementById('risqueGuerreAchats').checked = true
                }
            }

            if (tarif?.fluxVentes) {
                const fluxVentes = tarif.fluxVentes

                const inputNatureMar = document.getElementById('natureMarVentes')
                inputNatureMar.value = fluxVentes.typeMar
                checkNatureMar(inputNatureMar)

                document.getElementById('valeurAnnuelleVentes').value = fluxVentes.valeurAnnuelleVentes
                document.getElementById('montantVentes').value = fluxVentes.montant
                document.querySelector('[name="moyenTransportVentes"][value="' + fluxVentes.transport + '"] ').checked = true

                document.querySelector('select#conditionnementVentes option[value=' + fluxVentes.conditionnement + ']').selected = true;
                M.FormSelect.init(document.querySelector('select#conditionnementVentes'))
                const chipCondVentes = document.getElementById('chip-modulo-condVentes')
                updateModuloChip(chipCondVentes, calcModCond(fluxVentes.conditionnement))

                document.querySelector('input[name=zoneVentes][value=' + fluxVentes.zone + ']').checked = true;
                checkZones(fluxVentes.zone, "zoneVentes")
                const chipZoneTransp = document.getElementById('chip-modulo-zoneVentes')
                updateModuloChip(chipZoneTransp, calcModZoneTransp(fluxVentes.zone, fluxVentes.transport))

                if (fluxVentes.typeRG) {
                    document.querySelector('input[name=typeGarantieRGVentes][value=' + fluxVentes.typeRG + ']').checked = true;
                    document.getElementById("engagementRGVentes").value = fluxVentes.engagementRG
                    document.getElementById('row-typeGarantieRGVentes').style.display = "block"
                    document.getElementById('risqueGuerreVentes').checked = true
                }
            }
            const chipAchats = document.getElementById('chip-modulo-montantAchats')
            const chipVentes = document.getElementById('chip-modulo-montantVentes')

            const moduloMontant = calcModMontantCA(getMontantTotal(), getValeurAnnuelleTotal())
            updateModuloChip(chipAchats, moduloMontant)
            updateModuloChip(chipVentes, moduloMontant)
        }

        if (checkInputs()) {
            document.getElementById('propositions').style.display = "flex"
            document.getElementById('row-champsManquants').style.display = "none"

            sansFranchise = calcCard(1)
            franchise350 = calcCard(0.9)
            franchise750 = calcCard(0.85)

            fillPropCard('sansFranchise', sansFranchise)
            fillPropCard('franchise350', franchise350)
            fillPropCard('franchise750', franchise750)
        } else {
            document.getElementById('propositions').style.display = "none"
            document.getElementById('row-champsManquants').style.display = "block"
        }
        stepExtensions()

    }

    function handleLoadHistoriqueBtn() {
        var selectedId = document.getElementById('idSelect').value;

        if (selectedId != "") {
            fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${selectedId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
                .then(response => response.json())
                .then(data => {
                    if (data.valid) {
                        window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=tarif`;
                    } else {
                        console.log('Echec lors de la mise à jour de la relation id contrat - id client :', data);
                    }
                });
        }
    }

    function checkZones(checkedZone, nameZone) {
        const zone1Checked = checkedZone.includes("2") || checkedZone.includes("3");
        const zone2Checked = checkedZone.includes("3");

        if (nameZone == "zone") {
            document.getElementById('zone1-text').classList.toggle("checkedCheckbox", zone1Checked)
        } else if (nameZone == "zoneAchats") {
            document.getElementById('zoneAchats1-text').classList.toggle("checkedCheckbox", zone1Checked)
            document.getElementById('zoneAchats2-text').classList.toggle("checkedCheckbox", zone2Checked)
        } else if (nameZone == "zoneVentes") {
            document.getElementById('zoneVentes1-text').classList.toggle("checkedCheckbox", zone1Checked)
            document.getElementById('zoneVentes2-text').classList.toggle("checkedCheckbox", zone2Checked)
        }
    }

    function exportFlux(flux) {
        if (document.querySelector('[name="typeFlux"]:checked').value == "global") {
            return ""
        }

        if (flux == "achats" && document.querySelector('#achats[name="fluxDetailles"]').checked) {
            return {
                typeMar: document.getElementById('natureMarAchats').value,
                valeurAnnuelleAchats: document.querySelector('#div-fluxAchats #valeurAnnuelleAchats').value,
                montant: document.querySelector('#montantAchats').value,
                transport: document.querySelector('[name=moyenTransportAchats]:checked').value,
                conditionnement: document.querySelector('#conditionnementAchats').value,
                zone: document.querySelector('[name="zoneAchats"]:checked').value,
                typeRG: document.getElementById('risqueGuerreAchats').checked ? document.querySelector('[name="typeGarantieRGVentes"]:checked').value : "",
                engagementRG: document.getElementById('risqueGuerreAchats').checked ? document.getElementById('engagementRGAchats').value : "",
            }
        } else if (flux == "ventes" && document.querySelector('#ventes[name="fluxDetailles"]').checked) {
            return {
                typeMar: document.getElementById('natureMarVentes').value,
                valeurAnnuelleVentes: document.querySelector('#div-fluxVentes #valeurAnnuelleVentes').value,
                montant: document.querySelector('#div-fluxVentes #montantVentes').value,
                transport: document.querySelector('[name=moyenTransportVentes]:checked').value,
                conditionnement: document.querySelector('#conditionnementVentes').value,
                zone: document.querySelector('[name="zoneVentes"]:checked').value,
                typeRG: document.getElementById('risqueGuerreVentes').checked ? document.querySelector('[name="typeGarantieRGVentes"]:checked').value : "",
                engagementRG: document.getElementById('risqueGuerreVentes').checked ? document.getElementById('engagementRGVentes').value : "",
            }
        } else {
            return ""
        }
    }

    function calcCard(modFranchise) {
        const activite = document.getElementById('activite')
        const montant = getMontantTotal()
        const ca = getCA()
        var franchiseTPPC
        var franchiseExpo

        var primeRO = calcPrimeRef(modFranchise)

        const primeMini = calcPrimeMini(getPolice())
        primeRO = (primeMini > primeRO) ? primeMini : primeRO


        if (document.getElementById("TPPC").checked) {
            const objTPPC = calcTPPC(primeRO)
            franchiseTPPC = objTPPC['franchise']
            primeRO += objTPPC['tppc']
        }

        if (document.getElementById('marEnExpo').checked) {
            const objExpo = calcMarEnExpo(primeRO)
            franchiseExpo = objExpo['franchise']
            primeRO += objExpo['marEnExpo']
        }

        primeRG = calcRG()
        primeRef = (primeRO + primeRG) * modFranchise

        const modMontantCA = calcModMontantCA(montant, ca)
        const modAct = calcModAct(activite.value)

        const tauxRO = (primeRef / ca * 100).toFixed(3)
        const tauxRG = (primeRG / ca * 100)

        primeRef = parseFloat(primeRef.toFixed(2) || 0)

        return {
            pourcentAct: modAct,
            pourcentMar: getModNatureMar(),
            pourcentCA: modMontantCA,
            pourcentFranchise: modFranchise,
            franchiseTPPC: franchiseTPPC,
            franchiseExpo: franchiseExpo,
            proposition: primeRef,
            tauxRG: tauxRG,
            tauxRO: tauxRO
        }
    }

    function calcPrimeAchats() {
        if (isAchatsSelected()) {
            const activite = document.getElementById('activite').value

            const valeurAnnuelleAchats = document.getElementById('valeurAnnuelleAchats').value
            const marchandise = document.getElementById('natureMarAchats').value
            const conditionnement = document.querySelector('#conditionnementAchats').value
            const zone = document.querySelector('[name="zoneAchats"]:checked')?.value
            const transport = document.querySelector('[name="moyenTransportAchats"]:checked')?.value

            if (marchandise && conditionnement && zone && transport && activite && valeurAnnuelleAchats) {

                const modNatureMarAchats = calcModNatureMar(marchandise)
                const modCond = calcModCond(conditionnement)
                const modZoneTransp = calcModZoneTransp(zone, transport)
                const taux = modNatureMarAchats * modCond * modZoneTransp
                const primeAchats = valeurAnnuelleAchats * taux * 0.3
                const coeffGlobal = calcModMontantCA(getMontantTotal(), getValeurAnnuelleTotal())

                const modPolice = calcModPolice(getPolice())
                const modAct = calcModAct(activite)
                const coeffGeneraux = modPolice * modAct
                const prime = coeffGeneraux * coeffGlobal * primeAchats

                return prime
            }
        } else {
            return false
        }
    }

    function calcPrimeVentes() {
        if (isVentesSelected()) {
            const activite = document.getElementById('activite').value

            const valeurAnnuelleVentes = document.getElementById('valeurAnnuelleVentes').value
            const marchandise = document.getElementById('natureMarVentes').value
            const conditionnement = document.querySelector('#conditionnementVentes').value
            const zone = document.querySelector('[name="zoneVentes"]:checked')?.value
            const transport = document.querySelector('[name="moyenTransportVentes"]:checked')?.value

            if (marchandise && conditionnement && zone && transport && activite && valeurAnnuelleVentes) {

                const modNatureMarVentes = calcModNatureMar(marchandise)
                const modCond = calcModCond(conditionnement)
                const modZoneTransp = calcModZoneTransp(zone, transport)
                const taux = modNatureMarVentes * modCond * modZoneTransp
                const modPolice = calcModPolice(getPolice())
                const modAct = calcModAct(activite)
                const primeVentes = valeurAnnuelleVentes * taux * 0.3

                const sommeMontants = getMontantTotal()
                const sommeValeurCA = getValeurAnnuelleTotal()

                const coeffGlobal = calcModMontantCA(sommeMontants, sommeValeurCA)
                const coeffGeneraux = modPolice * modAct
                const prime = coeffGeneraux * coeffGlobal * primeVentes

                return prime
            }
        }
    }


    /* STEP FUNCTIONS */
    function stepPolice() {
        if (getTypeFlux() !== "global") {
            return false
        }
        const ca = getCA()
        const modPolice = calcModPolice(getPolice())
        const chip = document.getElementById("chip-step-police")
        const stepPolice = (ca && modPolice) ? ca * modPolice : false
        updateStepChip(chip, stepPolice)
        return stepPolice
    }

    function stepActivite() {
        if (getTypeFlux() !== "global") {
            return false
        }
        const previousStep = stepPolice()

        const activite = document.getElementById('activite').value
        const modAct = calcModAct(activite)
        const chip = document.getElementById("chip-step-activite")
        const stepActivite = (previousStep && modAct) ? previousStep * modAct : false
        updateStepChip(chip, stepActivite)
        return stepActivite
    }

    function stepMarchandises() {
        if (getTypeFlux() !== "global") {
            return false
        }

        const previousStep = stepActivite()

        const modTypeMar = calcModNatureMar(getTypeMar())
        const modMontantCA = calcModMontantCA(getMontantTotal(), getCA())

        const chip = document.getElementById("chip-step-marchandises")
        const stepMarch = (previousStep && modMontantCA && modTypeMar) ? previousStep * modMontantCA * modTypeMar : false
        updateStepChip(chip, stepMarch)
        return stepMarch
    }

    function stepCond() {
        if (getTypeFlux() !== "global") {
            return false
        }

        const previousStep = stepMarchandises()
        const modCond = calcModCond(document.querySelector('#conditionnementGlobal').value)
        const chip = document.getElementById("chip-step-cond")
        const stepCond = (previousStep && modCond) ? previousStep * modCond : false
        updateStepChip(chip, stepCond)
        return stepCond
    }

    function stepZone() {
        if (getTypeFlux() !== "global") {
            return false
        }

        const previousStep = stepCond()
        const transport = document.querySelector('[name="moyenTransportGlobal"]:checked')?.value || false
        const zone = document.querySelector('[name="zone"]:checked')?.value || false
        const modZoneTransp = calcModZoneTransp(zone, transport)
        const chip = document.getElementById("chip-step-zone")
        const stepZone = (previousStep && modZoneTransp) ? previousStep * modZoneTransp : false
        updateStepChip(chip, stepZone)
        return stepZone
    }


    function stepAchats() {
        const chip = document.getElementById("chip-step-achats")
        var stepAchats = calcPrimeAchats()
        if (document.getElementById('risqueGuerreAchats').checked && stepAchats) {
            const engagement = parseFloat(document.getElementById('engagementRGAchats').value)
            const zone = document.querySelector('[name="zoneAchats"]:checked').value
            const typeRG = document.querySelector('[name="typeGarantieRGAchats"]:checked').value
            if (engagement && zone && typeRG) {
                taux = objModRG[zone][typeRG]
                rg = engagement * taux
                stepAchats += rg
            }
        }
        updateStepChip(chip, stepAchats)
        return stepAchats
    }

    function stepVentes() {
        const chip = document.getElementById("chip-step-ventes")
        var stepVentes = calcPrimeVentes()
        if (document.getElementById('risqueGuerreVentes').checked && stepVentes) {
            const engagement = parseFloat(document.getElementById('engagementRGVentes').value)
            const zone = document.querySelector('[name="zoneVentes"]:checked').value
            const typeRG = document.querySelector('[name="typeGarantieRGVentes"]:checked').value
            if (engagement && zone && typeRG) {
                taux = objModRG[zone][typeRG]
                rg = engagement * taux
                stepVentes += rg
            }
        }
        updateStepChip(chip, stepVentes)
        return stepVentes
    }


    function stepExtensions() {
        const chip = document.getElementById("chip-step-extensions")
        var previousStep, stepExtensions

        if (getTypeFlux() == "global") {
            previousStep = stepZone()
            const tppc = (document.getElementById("TPPC").checked) ? calcTPPC(previousStep)['tppc'] : 0
            const marEnExpo = (document.getElementById("marEnExpo").checked) ? calcMarEnExpo(previousStep)['marEnExpo'] : 0
            const rg = calcRG()
            stepExtensions = (previousStep && (tppc || marEnExpo || rg)) ? (previousStep + tppc + marEnExpo + rg) : false
        } else if (getTypeFlux() == "detailles") {

            previousStep = 0
            previousStep += isVentesSelected() ? stepVentes() : 0
            previousStep += isAchatsSelected() ? stepAchats() : 0
            const tppc = (document.getElementById("TPPC").checked) ? calcTPPC(previousStep)['tppc'] : 0
            const marEnExpo = (document.getElementById("marEnExpo").checked) ? calcMarEnExpo(previousStep)['marEnExpo'] : 0
            stepExtensions = (previousStep && (tppc || marEnExpo)) ? (previousStep + tppc + marEnExpo) : false
        }

        updateStepChip(chip, stepExtensions)
        return stepExtensions
    }

    function fillPropCard(idCard, cardData) {
        const card = document.getElementById(idCard)
        const pourcentageAct = parseFloat(cardData.pourcentAct * 100).toFixed(1)
        const pourcentageMar = parseFloat((cardData.pourcentMar * 1000).toFixed(6))
        const pourcentageCA = parseFloat(cardData.pourcentCA * 100).toFixed(2)
        const pourcentageFranchise = parseFloat(cardData.pourcentFranchise * 100).toFixed(0)
        const proposition = parseFloat(cardData.proposition).toFixed(2)
        const franchiseTPPC = cardData.franchiseTPPC
        const franchiseExpo = cardData.franchiseExpo

        if (tarif && tarif.selectedFranchise && tarif.selectedFranchise == idCard) {
            card.classList.add('selected-card')
        }

        card.querySelector("[id = mod-activite-" + idCard + "]").innerText = "Modulation Activité : " + pourcentageAct + "%"
        card.querySelector("[id = mod-marchandise-" + idCard + "]").innerText = "Modulation Marchandise : " + pourcentageMar + "‰"
        card.querySelector("[id = mod-ca-" + idCard + "]").innerText = "Modulation CA : " + pourcentageCA + "%"
        card.querySelector("[id = mod-franchise-" + idCard + "]").innerText = "Modulation Franchise  : " + pourcentageFranchise + "%"

        const tppcElement = card.querySelector("[id = mod-tppc-" + idCard + "]")
        const expoElement = card.querySelector("[id = mod-expo-" + idCard + "]")

        if (franchiseTPPC) {
            tppcElement.style.display = "block"
            tppcElement.innerText = "Franchise TPPC : " + franchiseTPPC + " €"
        } else {
            tppcElement.style.display = "none"
        }

        if (franchiseExpo) {
            expoElement.style.display = "block"
            expoElement.innerText = "Franchise Expo : " + franchiseExpo + " €"
        } else {
            expoElement.style.display = "none"
        }

        document.getElementById("proposition-" + idCard).innerText = proposition + "€"
    }

    async function submitForm(selectedCardId) {
        const typeFlux = getTypeFlux()
        const tppc = document.getElementById("TPPC").checked
        const rgGlobal = document.getElementById('rg').checked
        const marEnExpo = document.getElementById("marEnExpo").checked
        const selectedCard = extractPropoCard(selectedCardId)

        const bodyTarif = {
            fluxAchats: exportFlux("achats"),
            fluxVentes: exportFlux("ventes"),
            fluxIntersites: document.getElementById('intersites').checked,
            typePolice: getPolice(),
            typeRO: document.querySelector('[name="risqueOrdinaire"]:checked').value,
            conditionnement: typeFlux == "global" ? document.querySelector('#conditionnementGlobal').value : "",
            oldFranchise: document.getElementById('oldFranchise').value,
            sinistres: document.getElementById('sinistres').value,
            nbVehicTPPC: tppc ? document.getElementById("nbVehicTPPC").value : "",
            typeFlux: typeFlux,
            montantGarantir: typeFlux == "global" ? document.getElementById('montant').value : "",
            engagementRG: (typeFlux == "global" && rgGlobal) ? document.getElementById('engagementRG').value : "",
            franchise350: franchise350,
            franchise750: franchise750,
            sansFranchise: sansFranchise,
            selectedFranchise: selectedCardId,
            typeMarExpo: marEnExpo ? document.querySelector('[id="typeMarEnExpo"]').value : "",
            commentaire: document.getElementById('commentaire').value,
            zone: typeFlux == "global" ? document.querySelector('[name="zone"]:checked').value : "",
            transport: typeFlux == "global" ? document.querySelector('[name="moyenTransportGlobal"]:checked').value : "",
            asIf: extractAsIf()
        }

        const responseTarif = await fetch(`/fac/createTarif`, {
            method: 'POST',
            body: JSON.stringify(bodyTarif),
            headers: {
                'Content-Type': 'application/json',
            },
        });

        const dataTarif = await responseTarif.json();

        if (dataTarif.valid) {
            const idTarif = dataTarif.fac.id

            var cotRO = "", cotProvRO = "", cotRG = "", cotProvRG = "", rg = ""

            cotRO = document.getElementById('tarifCom').value

            if (contrat.type == "TEMPORAIRE") {
                cotRG = calcRG().toFixed(2)
            } else {
                cotProvRO = document.getElementById('tarifCom').value
                cotProvRG = calcRG().toFixed(2)
            }

            tauxCotRO = parseFloat(((document.getElementById('tarifCom').value / getCA()) * 100)).toFixed(3)
            tauxCotRG = parseFloat((tauxCotRG * 100).toFixed(6))

            if (getRisqueGuerre().length > 0) {
                rg = "auto"
            } else if (fac && fac.rg !== "auto") {
                rg = fac.rg
            }

            const bodyFAC = {
                projet: fac.projet || '',
                tarif: idTarif,
                nbVehicExpo: marEnExpo ? document.getElementById('nombreExposition').value : "",
                actAssuree: document.getElementById('activite').value,
                typeMar: getTypeMar(),
                ca: getCA(),
                typeRG: getRisqueGuerre(),
                cotRO: cotRO,
                cotProvRO: cotProvRO,
                cotRG: cotRG,
                cotProvRG: cotProvRG,
                tauxCotRO: tauxCotRO,
                tauxCotRG: tauxCotRG,
                capitalExpo: marEnExpo ? document.querySelector('[id="capitalExposition"]').value : "",
                franchiseExpo: (marEnExpo && selectedCard.franchiseExpo) ? selectedCard.franchiseExpo : "",
                capitalTPPC: tppc ? document.querySelector('[id="capitalTPPC"]').value : "",
                franchiseTPPC: (tppc && selectedCard.franchiseTPPC) ? selectedCard.franchiseTPPC : "",
                zones: getZones(),
                terrestre: getTransportTypeRO('terrestre'),
                maritime: getTransportTypeRO('maritime'),
                aerien: getTransportTypeRO('aerien'),
                postal: getTransportTypeRO('postal'),
                fluvial: "",
                multimodal: getTransportTypeRO('multimodal'),
                tppc: document.getElementById('TPPC').checked,
                rg: rg,
                primeHT: document.getElementById('tarifCom').value,
                primeMini: calcPrimeMini(getPolice())
            }

            const responseFAC = await fetch(`/fac/create`, {
                method: 'POST',
                body: JSON.stringify(bodyFAC),
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            const data = await responseFAC.json();

            if (data.valid) {
                const idProjet = data.fac.id;

                const responseContratEnCours = await fetch(`/contrat/update/${contrat.produit}/${contrat.id}/${idProjet}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                });

                const dataContratEnCours = await responseContratEnCours.json();

                if (dataContratEnCours.valid) {

                    // Obtenir la date actuelle au format "JJ/MM/AAAA"
                    const currentDate = new Date();
                    const day = String(currentDate.getDate()).padStart(2, '0');
                    const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Les mois sont indexés à partir de 0, donc +1
                    const year = currentDate.getFullYear();
                    const formattedDate = `${day}/${month}/${year}`;

                    //Obtenir l'user
                    const token = localStorage.getItem('jwtToken');
                    const decoded = jwt_decode(token);
                    const userFirstName = decoded.userFirstName;
                    const userLastName = decoded.userLastName;

                    // Obtenir l'heure actuelle au format "HHhMM"
                    const hours = String(currentDate.getHours()).padStart(2, '0');
                    const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                    const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                    const formattedTime = `${hours}:${minutes}:${seconds}`;
                    const nom = userLastName;
                    const prenom = userFirstName;

                    // Mettre à jour le champ "historique" dans le contrat avec les nouvelles données d'historique
                    const historiqueData = [
                        {
                            "type": contrat.type,
                            "date": formattedDate,
                            "heure": formattedTime,
                            "produit": "FAC",
                            "id": idProjet,
                            "nom": nom,
                            "prenom": prenom,
                        }
                    ];

                    const responseHistoriqueUpdate = await fetch(`/contrat/update/historique/${contrat.id}`, {
                        method: 'POST',
                        body: JSON.stringify({historiqueData}),
                        headers: {
                            'Content-Type': 'application/json',
                        },
                    });

                    const dataHistoriqueUpdate = await responseHistoriqueUpdate.json();

                    if (dataHistoriqueUpdate.valid) {
                        window.location.href = `/navParcours?numParcours=${getNumParcoursFromURL()}&submenu=projet`;
                    } else {
                        console.log('Echec lors de la mise à jour de l\'historique du contrat :', dataHistoriqueUpdate.message);
                    }
                }
            } else {
                console.log('Echec lors de la création de la saisie dans la collection TPPC :', data.message);
            }
        } else {
            console.log('Echec lors de la création de la saisie dans la collection FACtarif :', data.message);
        }
    }

    function extractPropoCard(cardId) {
        switch (cardId) {
            case 'sansFranchise':
                return sansFranchise
            case 'franchise350':
                return franchise350
            case 'franchise750':
                return franchise750
        }
        return null
    }

    function openModaleTarifCom(cardId) {
        const franchise = extractPropoCard(cardId)
        document.getElementById('tarifRefText').innerText = "Tarif de Référence : " + parseFloat(franchise.proposition).toFixed(2) + "€"
        document.getElementById('tarifCom').value = ""
        document.getElementById('commentaire').value = ""
        document.getElementById('comm-OK').disabled = false
        document.getElementById('tarifCom-error').style.display = "none"
        document.getElementById('col-commentaire').style.display = "none"
        document.getElementById('qualiteDiv').style.display = "none"

        document.getElementById('comm-OK').name = cardId

        document.getElementById('tarifCom').addEventListener('input', function () {
            var qualitePrime
            var emoji
            var showComment

            diff = 100 * parseFloat(document.getElementById('tarifCom').value / franchise.proposition)

            if (diff < (100 + seuil) && diff > (100 - seuil)) {
                emoji = "mood"
                showComment = false

                if (diff > 100) {
                    qualitePrime = "Tarif correct (+" + (diff - 100).toFixed(2) + "%)"
                } else if (diff < 100) {
                    qualitePrime = "Tarif correct (-" + (100 - diff).toFixed(2) + "%)"
                } else if (diff == 100) {
                    qualitePrime = "Le juste prix"
                    emoji = "thumb_up_alt"
                }
            } else {
                emoji = "mood_bad"
                showComment = true

                if (diff > (100 + seuil)) {
                    qualitePrime = "Tarif trop élevé (+" + (diff - 100).toFixed(2) + "%)"
                } else if (diff < (100 - seuil)) {
                    qualitePrime = "Tarif trop bas (-" + (100 - diff).toFixed(2) + "%)"
                }
            }

            document.getElementById('qualiteDiv').style.display = "block"
            document.getElementById('qualitePrime').innerText = qualitePrime
            document.getElementById('modalTarifCom-icon').innerText = emoji
            document.getElementById('modalTarifCom-icon').style.color = (emoji == "mood_bad") ? "red" : "green"

            if (showComment) {
                document.getElementById('tarifCom-error').style.display = "flex"
                document.getElementById('col-commentaire').style.display = "flex"
                if (document.getElementById('commentaire').value == "") {
                    document.getElementById('comm-OK').disabled = true
                }
            } else {
                document.getElementById('comm-OK').disabled = false
                document.getElementById('tarifCom-error').style.display = "none"
                document.getElementById('col-commentaire').style.display = "none"
            }
        })

        const modal = document.getElementById('modalTarifCom')
        const instance = M.Modal.getInstance(modal);
        instance.open();
    }

    // Exposer init globalement pour y accéder depuis l'extérieur
    window.initSubmenuForm = init;
})();