const formID2 = '241516900942858';
const apiKey2 = '6e2676fa4067aecefdfae6fca7c4bb41';
const allSubmissionIDs = []; // Array to store all submission IDs with labels

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';
};
// Fetch data for the single formID2
fetch(`https://api.jotform.com/form/${formID2}/submissions?apiKey=${apiKey2}&limit=1000`)
    .then(response => response.json())
    .then(data => {
        const allSubmissionIDs = 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 };
            });

        console.log(allSubmissionIDs);
        
    // Helper function to get the last twelve months as strings in the format "MMM yyyy"
    function getLastTwelveMonths() {
        const months = [];
        const currentDate = new Date();
        for (let i = 0; i < 12; i++) {
            const formattedDate = currentDate.toLocaleString('default', { month: 'short', year: 'numeric' });
            months.push(formattedDate);
            currentDate.setMonth(currentDate.getMonth() - 1);
        }
        return months.reverse();
    }

    // Object to hold summed monto values by month
    const monthlySums = {};

    // Extract the required data and perform the calculation for all submissions
    allSubmissionIDs.forEach(entry => {
        const answers = entry.answers;
        let monto = 0;
        let fecha = '';

        // Extract monto and fecha 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 === "fecha") {
                fecha = answers[key].answer;
            }
        }

        // Format the date (helper function to ensure uniform format)
        function formatDate(fechai) {
            const regex = /^\d{4}-\d{2}-\d{2}$/;
            if (regex.test(fechai)) {
                return fechai;
            } else {
                const partesFecha = fechai.split("/");
                return `${partesFecha[2]}-${partesFecha[1].padStart(2, '0')}-${partesFecha[0].padStart(2, '0')}`;
            }
        }

        const date = new Date(formatDate(fecha));
        const formattedDate = date.toLocaleString('default', { month: 'short', year: 'numeric' });

        console.log(`Fecha: ${fecha}, FormattedDate: ${formattedDate}, Monto: ${monto}`);

        // Sum the result by formatted date
        if (monthlySums[formattedDate]) {
            monthlySums[formattedDate] += monto;
        } else {
            monthlySums[formattedDate] = monto;
        }
    });

    console.log("Monthly Sums for all submissions:", monthlySums);

    // Get the last twelve months
    const lastTwelveMonths = getLastTwelveMonths();

    // Prepare data for the bar chart, ensuring 0 for months with no data
    const labels = lastTwelveMonths;
    const datos = lastTwelveMonths.map(month => monthlySums[month] || 0);
    console.log("Datos:", datos);

    // Insert the current month sum into the HTML
    document.getElementById("currentMonthSum").textContent = `$${datos[11].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    
        
    // Create the bar chart
    const ctx = document.getElementById("myChart").getContext("2d");
    new Chart(ctx, {
        type: "bar",
        data: {
            labels: labels,
            datasets: [{
                label: "Monto",
                tension: 0.4,
                borderRadius: 4,
                borderSkipped: false,
                borderColor: "#8ac926",
                backgroundColor: "#8ac926",
                fill: true,
                borderWidth: 3,
                data: datos,
                maxBarThickness: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false,
                }
            },
            interaction: {
                intersect: false,
                mode: 'index',
            },
            scales: {
                y: {
                    grid: {
                        drawBorder: false,
                        display: true,
                        drawOnChartArea: true,
                        drawTicks: false,
                        borderDash: [5, 5]
                    },
                    ticks: {
                        display: true,
                        padding: 10,
                        color: '#b2b9bf',
                        font: {
                            size: 11,
                            style: 'normal',
                            lineHeight: 2
                        },
                    }
                },
                x: {
                    grid: {
                        drawBorder: false,
                        display: false,
                        drawOnChartArea: false,
                        drawTicks: false,
                        borderDash: [5, 5]
                    },
                    ticks: {
                        display: true,
                        color: '#b2b9bf',
                        padding: 10,
                        font: {
                            size: 11,
                            style: 'normal',
                            lineHeight: 2
                        },
                    }
                },
            },
        },
    });


        // Filter the active submissions
        const activeSubmissions = allSubmissionIDs.filter(submission => submission.status === 'active');
        const activeCount = activeSubmissions.length;

        document.getElementById("noProyectos").textContent = `${activeCount}`;

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

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

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

            totalResult += monto;
        });

        console.log("Total Result:", totalResult);
        document.getElementById("results-container").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
            }
        }

        
        const currentMonth = new Date().getMonth();
        const currentYear = new Date().getFullYear(); // Corrected to get the year properly
        
        
        // Get current date information
        const now = new Date();
        
        const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1;  // Handle December -> November transition
        const lastMonthYear = currentMonth === 0 ? currentYear - 1 : currentYear;
        
        // Initialize counters
        let idsThisMonth = 0;
        let idsUntilLastMonth = 0;
        
        // Loop through submissions to count IDs
        allSubmissionIDs.forEach(entry => {
            const answers = entry.answers;
            let fecha = null;
        
            // Extract the 'fecha' value from the answers
            for (const key in answers) {
                if (answers[key].name === "fecha") {
                    fecha = parseDate(answers[key].answer);
                    break;
                }
            }
        
            if (fecha) {
                const submissionMonth = fecha.getMonth();  // Get the month of submission (0-11)
                const submissionYear = fecha.getFullYear();  // Get the year of submission
        
                // Check if the submission was created this month
                if (submissionMonth === currentMonth && submissionYear === currentYear) {
                    idsThisMonth++;  // Increment counter for this month
                }
                // Check if the submission was created up until last month (but not in the current month)
                else if (submissionYear < currentYear || (submissionYear === currentYear && submissionMonth <= lastMonth)) {
                    idsUntilLastMonth++;  // Increment counter for past months
                }
            }
        });
        
        // Calculate the ratio
        let idRatio = 0;
        if (idsUntilLastMonth > 0) {
            idRatio = ((idsThisMonth / idsUntilLastMonth)-1)*100;
        }
        
        console.log("IDs this month:", idsThisMonth);
        console.log("Total IDs until last month:", idsUntilLastMonth);
        console.log("ID ratio (this month / until last month):", idRatio);
        
        document.getElementById("submissionChange").textContent = `${idRatio.toFixed(2)}%`;
        
        // Optionally change color depending on whether it's an increase or decrease
        const submissionChangeElement = document.getElementById("submissionChange");
        if (idRatio >= 0) {
            submissionChangeElement.classList.remove("text-danger");
            submissionChangeElement.classList.add("text-success"); // Green for positive change
        } else {
            submissionChangeElement.classList.remove("text-success");
            submissionChangeElement.classList.add("text-danger"); // Red for negative change
        }
        
        // Initialize counters
        let montoThisMonth = 0;
        let montoUntilLastMonth = 0;
        // Loop through submissions to count IDs
        allSubmissionIDs.forEach(entry => {
            const answers = entry.answers;
            let fecha = null;
            let monto;
        
            // Extract the 'fecha' value from the answers
            for (const key in answers) {
                if (answers[key].name === "fecha") {
                    fecha = parseDate(answers[key].answer);
                    break;
                } else if (answers[key].name === "monto") {
                    monto = parseFloat(answers[key].answer.replace(/[\$,]/g, ""));
                }
            }
        
            if (fecha) {
                const submissionMonth = fecha.getMonth();  // Get the month of submission (0-11)
                const submissionYear = fecha.getFullYear();  // Get the year of submission
        
                // Check if the submission was created this month
                if (submissionMonth === currentMonth && submissionYear === currentYear) {
                    montoThisMonth += monto;  // Increment counter for this month
                }
                // Check if the submission was created up until last month (but not in the current month)
                else if (submissionYear < currentYear || (submissionYear === currentYear && submissionMonth <= lastMonth)) {
                    montoUntilLastMonth += monto ;  // Increment counter for past months
                }
            }
        });
        console.log("Monto this month:", montoThisMonth);
        console.log("Total montos until last month:", montoUntilLastMonth);
        
        const VPcolocacion = ((montoThisMonth / montoUntilLastMonth) - 1) * 100;
    console.log("Variación porcentual colocación mensual:", VPcolocacion);
    
    // Get the element where the value will be displayed
    const VPcolocacionElement = document.getElementById("VPcolocacion");
    
    // Format the value with a plus sign if positive
    let formattedVPcolocacion = VPcolocacion >= 0 
        ? `+${VPcolocacion.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}` 
        : `${VPcolocacion.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    
    // Set the text content of the element
    VPcolocacionElement.textContent = `${formattedVPcolocacion}%`;
    
    // Change the color based on whether the value is positive or negative
    if (VPcolocacion >= 0) {
        VPcolocacionElement.classList.remove("text-danger");
        VPcolocacionElement.classList.add("text-success"); // Green for positive values
    } else {
        VPcolocacionElement.classList.remove("text-success");
        VPcolocacionElement.classList.add("text-danger"); // Red for negative values
    }
    
    let totalAmountCom = 0;
        let ComLastMonth = 0;
    const previousMonthDate = new Date(now);
        previousMonthDate.setMonth(currentMonth - 1); // Move to previous month
        const pastMonth = previousMonthDate.getMonth(); // Get the month of the previous date
        const pastYear = previousMonthDate.getFullYear(); // Handle year change

        activeSubmissions.forEach(entry => {
            const answers = entry.answers;
            let amount = 0;
            let comision = 0;
            let fecha = null;

            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);
                }
            }

            if (fecha && fecha.getMonth() === currentMonth && fecha.getFullYear() === currentYear) {
                const amountCom = amount * comision;
                totalAmountCom += amountCom;
            } else if (fecha.getFullYear() === pastYear && fecha.getMonth() === pastMonth) {
                const amountCom = amount * comision;
                ComLastMonth += amountCom;
            }
        });

        console.log("Colocado con comisiones:", totalAmountCom);
        document.getElementById("comisionesTotal").textContent = `$${(totalAmountCom / 1.16).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
        
        const VPComisiones = ((totalAmountCom/ComLastMonth)-1)*100;
        console.log("Variacion comisiones:", VPComisiones)
        /// Get the element where the value will be displayed
        const VPComisionesElement = document.getElementById("VPComisiones");
                    
        // Format the value with a plus sign if positive
        let formattedVPComisiones = VPComisiones >= 0 
                        ? `+${VPComisiones.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}` 
                        : `${VPComisiones.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                    
                    // Set the text content of the element
                    VPComisionesElement.textContent = `${formattedVPComisiones}%`;
                    
                    // Change the color based on whether the value is positive or negative
                    if (VPComisiones >= 0) {
                        VPComisionesElement.classList.remove("text-danger");
                        VPComisionesElement.classList.add("text-success"); // Green for positive values
                    } else {
                        VPComisionesElement.classList.remove("text-success");
                        VPComisionesElement.classList.add("text-danger"); // Red for negative values
                    }
            
        const projectSums = {};
        let totalMonto = 0;

        activeSubmissions.forEach(submission => {
            const answers = submission.answers;
            let monto = 0;
            let projectName = "Unnamed Project";

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

            totalMonto += monto;

            if (projectSums[projectName]) {
                projectSums[projectName] += monto;
            } else {
                projectSums[projectName] = monto;
            }
        });

        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);

        const namesLabels = Object.keys(projectPercentages);
        const datosPie = Object.values(projectPercentages);

        function calculateHHI(projectSums) {
            const projectShares = Object.values(projectPercentages).map(percentage => parseFloat(percentage) / 100);
            return projectShares.reduce((sum, share) => sum + share ** 2, 0);
        }

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

        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) + '%';
                            }
                        }
                    }
                }
            }
        });
    })
    .catch(error => console.error(`Error fetching data for formID ${formID2}:`, error));

