const formIDs2 = ['243167527463865', '243168214308857'];
const apiKey2 = '6e2676fa4067aecefdfae6fca7c4bb41';
const allSubmissionIDs = []; // Array to store all submission IDs with labels

// Function to calculate the difference in days and determine active status
const calculateDaysDifference = (submissionDate, peri, term) => {
    const n = Math.floor(term / peri); // Calculate n
    const fechas = []; // Array to store generated dates

    // Convert submission date to a Date object
    function formatDate(fechai) {
            // Regular expression to check for "aaaa-mm-dd" format
            var regex = /^\d{4}-\d{2}-\d{2}$/;
            
            if (regex.test(fechai)) {
                // If the date is already in "aaaa-mm-dd" format, return it as is
                return fechai;
            } else {
                // Otherwise, split the date and reformat it
                var partesFecha = fechai.split("/");
                // Formar la fecha en formato "aaaa-mm-dd"
                return partesFecha[2] + "-" + partesFecha[1].padStart(2, '0') + "-" + partesFecha[0].padStart(2, '0');
            }
        }
        
        var fecha_inicio = formatDate(submissionDate);
    const hoy = new Date(fecha_inicio.replace(/-/g, '\/'));

    // Function to add days to a date
    const addDays = (numOfDays, date) => {
        const result = new Date(date);
        result.setDate(result.getDate() + numOfDays);
        return result;
    };

    // Generate the list of dates
    for (let i = 0; i <= n; i++) {
        fechas.push(addDays(peri * (i + 1), hoy));
    }

    // Function to count how many dates have passed
    const contarFechasPasadas = (fechas) => {
        const fechaActual = new Date();
        let contador = 0;

        for (const fecha of fechas) {
            if (fecha < fechaActual) {
                contador++;
            }
        }

        return contador;
    };

    const fp = contarFechasPasadas(fechas);
    return fp >= n ? 'inactive' : 'active';
};

const fetchPromises2 = formIDs2.map(formID => 
    fetch(`https://api.jotform.com/form/${formID}/submissions?apiKey=${apiKey2}&limit=100`)
        .then(response => response.json())
        .then(data => {
            const submissionIDs = data.content
                .filter(entry => {
                    const answers = entry.answers;
                    for (const key in answers) {
                        if (answers[key].name === "contratoFirmado" && answers[key].answer.length > 0) {
                            return true;
                        }
                    }
                    return false;
                })
                .map(entry => {
                    const answers = entry.answers;
                    let submissionDate, peri, term;

                    // Extract the relevant fields from the answers
                    for (const key in answers) {
                        if (answers[key].name === "fecha") {
                            submissionDate = answers[key].answer;
                        } else if (answers[key].name === "peri") {
                            peri = parseInt(answers[key].answer, 10);
                        } else if (answers[key].name === "plz") {
                            term = parseInt(answers[key].answer, 10);
                        }
                    }

                    // Determine the status of the submission
                    const status = calculateDaysDifference(submissionDate, peri, term);

                    return { id: entry.id, status: status, answers: answers };
                });

            allSubmissionIDs.push(...submissionIDs); // Add all labeled submission IDs to the array
        })
        .catch(error => console.error(`Error fetching data for formID ${formID}:`, error))
);

// After fetching all data
Promise.all(fetchPromises2).then(() => {
    console.log(allSubmissionIDs)
    // Filter the active submissions
    const activeSubmissions = allSubmissionIDs.filter(submission => submission.status === 'active');
    const activeCount = activeSubmissions.length;
    const HCount= allSubmissionIDs.length
    document.getElementById("noProyectos").textContent = `${activeCount}`;
    document.getElementById("noProyectosH").textContent = `${HCount}`;

    // Extract the required data and perform the calculation
    let totalResult = 0; // Initialize total result

    activeSubmissions.forEach(entry => {
        const answers = entry.answers;
        let monto = 0;

        // Extract monto and comision from the answers
        for (const key in answers) {
            if (answers[key].name === "monto") {
                monto = parseFloat(answers[key].answer.replace(/[\$,]/g, ""));
            }
        }

            // Perform the calculation
            const result = monto;
            totalResult += result; // Add result to total
        });

        console.log("Total Result:", totalResult);

        // Display the total result in HTML
        const resultsContainer = document.getElementById("results-container");
        resultsContainer.textContent = `$${totalResult.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
        
        // Function to parse date strings in either format
        function parseDate(dateString) {
            if (dateString.includes("/")) {
                // Handle format DD/MM/YYYY
                const [day, month, year] = dateString.split("/");
                return new Date(`${year}-${month}-${day}`);
            } else if (dateString.includes("-")) {
                // Handle format YYYY-MM-DD
                return new Date(dateString);
            } else {
                return null; // If the format is unrecognized, return null
            }
        }
        
        let totalAmountCom = 0;
        const currentMonth = new Date().getMonth(); // Get the current month (0-11)
        const currentYear = new Date().getYear(); // Get the current month (0-11)
        
        activeSubmissions.forEach(entry => {
            const answers = entry.answers;
            let amount = 0;
            let comision = 0;
            let fecha = null;
        
            // Extract monto, comision, and fecha from the answers
            for (const key in answers) {
                if (answers[key].name === "monto") {
                    amount = parseFloat(answers[key].answer.replace(/[\$,]/g, ""));
                } else if (answers[key].name === "comision") {
                    comision = parseFloat(answers[key].answer) * 0.01;
                } else if (answers[key].name === "fecha") {
                    fecha = parseDate(answers[key].answer);
                }
            }
        
            console.log(fecha)
            // Check if the 'fecha' is in the current month
            if (fecha && fecha.getMonth() === currentMonth && fecha.getYear() === currentYear) {
                const amountCom = amount * (comision);
                totalAmountCom += amountCom; // Add result to total
            }
        });
        
        console.log("Colocado con comisiones:", totalAmountCom);
        document.getElementById("comisionesTotal").textContent = `$${(totalAmountCom/1.16).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
        
                
    // Object to hold summed monto values by project
    const projectSums = {};

    // Calculate the total monto
    let totalMonto = 0;

    // Extract the required data and perform the calculation
    activeSubmissions.forEach(submission => {
        const answers = submission.answers;
        let monto = 0;
        let projectName = "Unnamed Project";

        // Extract monto and nombrecompleto from the answers
        for (const key in answers) {
            if (answers[key].name === "monto") {
                monto = parseFloat(answers[key].answer.replace(/[\$,]/g, ""));
            } else if (answers[key].name === "noContrato" || answers[key].name === "empresa" ) {
                projectName = answers[key].answer || "Unnamed Project";
            }
        }

        totalMonto += monto;

        // Sum the result by project
        if (projectSums[projectName]) {
            projectSums[projectName] += monto;
        } else {
            projectSums[projectName] = monto;
        }
    });

    // Calculate the percentage for each project
    const projectPercentages = {};
    for (const projectName in projectSums) {
        projectPercentages[projectName] = ((projectSums[projectName] / totalMonto) * 100);
    }

    console.log("Sums by name:", projectSums);
    console.log("Percentages by name:", projectPercentages);

    // Prepare data for the pie chart
    const namesLabels = Object.keys(projectPercentages);
    const datosPie = Object.values(projectPercentages);

    // Function to calculate HHI
    function calculateHHI(projectSums) {
        // Convert the percentage shares to decimals
        const projectShares = Object.values(projectPercentages).map(percentage => parseFloat(percentage) / 100);

        // Calculate the HHI
        const hhi = projectShares.reduce((sum, share) => sum + share ** 2, 0);

        return hhi;
    }

    const hhi = calculateHHI(projectSums);

    console.log("Herfindahl-Hirschman Index (HHI):", hhi);
    document.getElementById("indexHHI").textContent = `${(hhi * 100).toFixed(2)}%`;

    // Create the pie chart
    const pieData = {
        labels: namesLabels,
        datasets: [{
            weight: 9,
            cutout: 0,
            tension: 0.9,
            pointRadius: 2,
            borderWidth: 2,
            data: datosPie,
            backgroundColor: ['#ff595e', '#ff924c', '#ffca3a', '#c5ca30', '#8ac926', '#36949d', '#1982c4', '#4267ac', '#565aa0', '#6a4c93'],
            borderWidth: 1
        }]
    };

    const pieChart = document.getElementById("pie-chart").getContext("2d");
    new Chart(pieChart, {
        type: "pie",
        data: pieData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false,
                },
                tooltip: {
                    callbacks: {
                        label: function(tooltipItem) {
                            return tooltipItem.label + ': ' + tooltipItem.raw.toFixed(2) + '%';
                        }
                    }
                }
            }
        }
    });
});
