const formIDs = {
    '243167527463865': 'creditoopenmkt',
    '243168214308857': 'arrendamiento'
};
const apiKey = '6e2676fa4067aecefdfae6fca7c4bb41';
const labeledSubmissionIDs = []; // Array to store labeled submission IDs

const fetchPromises = Object.keys(formIDs).map(formID => 
    fetch(`https://api.jotform.com/form/${formID}/submissions?apiKey=${apiKey}&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 => ({
                    id: entry.id,
                    label: formIDs[formID] // Label based on formID
                }));

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

function generarFechasDePago(fechainiciar, cantidadPagos, periodo) {
            const fechas = [];
            let fechaActual = new Date(fechainiciar);

            for (let i = 0; i < cantidadPagos; i++) {
                let dia;
                let ultdia;

                switch (periodo) {
                    case 7: // Every Friday
                        while (fechaActual.getDay() !== 5) { // While the day is not Friday
                            fechaActual.setDate(fechaActual.getDate() + 1); // Move to the next day
                        }
                        dia = fechaActual.getDate();
                        break;
                    case 14: // Every 14th and 28th day of the month
                        dia = 14;
                        ultdia = 28;
                        break;
                    case 5: // Every 14th and 28th day of the month
                        dia = 5;
                        ultdia = 20;
                        break;
                    case 15: // Every 15th and last day of the month
                        dia = 15;
                        ultdia = new Date(fechaActual.getFullYear(), fechaActual.getMonth() + 1, 0).getDate(); // Get last day of the month
                        break;
                    case 28: // Every 28th day of the month
                        dia = 28;
                        break;
                    case 30: // Last day of the month
                        dia = new Date(fechaActual.getFullYear(), fechaActual.getMonth() + 1, 0).getDate();
                        break;
                    default:
                        throw new Error("Invalid value for periodo");
                }

                // Create the payment date
                let nuevaFechaPago = new Date(fechaActual.getFullYear(), fechaActual.getMonth(), dia);
                fechas.push(nuevaFechaPago);

                // If 14th or 28th, add the other day
                if (periodo === 14 || periodo === 15|| periodo === 5) {
                    fechas.push(new Date(fechaActual.getFullYear(), fechaActual.getMonth(), ultdia));
                }

                // Mover a la siguiente fecha de pago
                if (periodo === 7) {
                    fechaActual.setDate(fechaActual.getDate() + 7); // Mover al pr車ximo viernes
                    // Verificar si necesitamos pasar al siguiente mes
                    if (fechaActual.getMonth() !== nuevaFechaPago.getMonth()) {
                        fechaActual.setDate(1); // Empezar desde el primer d赤a del pr車ximo mes
                    }
                } else {
                    fechaActual.setMonth(fechaActual.getMonth() + 1); // Mover al pr車ximo mes
                }
            }

            // Eliminar duplicados en el caso de 14th y 28th
            if (periodo === 14 || periodo === 15) {
                const uniqueFechas = [...new Set(fechas.map(f => f.getTime()))].map(time => new Date(time));
                return uniqueFechas;
            }

            return fechas;
        }
function addDays(numOfDays, date) {
            date.setDate(date.getDate() + numOfDays);
            return date.toLocaleDateString('es-ES');
        }
function CreditTable(submissionData) {
           const type = submissionData["Type"];
           const tasa = submissionData["Tasa"];
           const c = submissionData["Comision"];
           const monto = submissionData["Monto"];
           const peri = parseFloat(submissionData["Periodicidad"]);
           const plzo = parseFloat(submissionData["Plazo"]);
           const fecha_inicio = submissionData["Fecha de inicio"];
            
          let periodo;
          let n;
          let payment;
          if(type == "SSII") {
            const interestic = parseFloat(tasa);
            console.log(interestic);
            const com = parseFloat(c);
            console.log(com);
            const amount = parseFloat(monto.replace("$", "").replace(/,/g, ""));
            console.log(amount);
            periodo = parseFloat(peri);
            console.log("Periodo:", periodo);
            const plazo = parseFloat(plzo);
            console.log("Plazo:", plazo);
    
            n = Math.floor(plazo / periodo); // Redondear hacia abajo
            console.log(n);
            localStorage.setItem('numperiodos', n);
          
            const amountt = amount;
            let comision = com * 0.01;
            let interes = interestic * 0.01 * (periodo / 360) ;
            console.log(interes);
            payment = amountt * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
          
            // Utilizar el valor redondeado de n en los cálculos
            payment = amountt * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
            let d = payment * n;
            let cost = (((d / amountt - 1) * 100) * 12) / ((plazo / 30) * 1.16);
            
            var amort = [0];
            var int = [0];
            var saldo_inicial = [amountt * (1 + comision)];
            var saldo_final = [amountt * (1 + comision)];
            var pago = [0];
            var iva = [0];
      
            //Nuestro loop con ecuaciones en diferencia
            for (let i = 0; i <= n; i++) {
                pago[i + 1] = payment;
                int[i + 1] = saldo_final[i] * interes / 1.16;
                iva[i + 1] = int[i + 1] * 0.16;
                amort[i + 1] = payment - int[i + 1] - iva[i + 1];
                saldo_inicial[i + 1] = saldo_final[i] + int[i + 1] + iva[i + 1];
                saldo_final[i + 1] = saldo_final[i] - amort[i + 1];      
        }
          
        } else if(type == "Balloon") {
            const interestic = parseFloat(tasa);
            const com = parseFloat(c);
            const amount = parseFloat(monto);
            const residual = parseFloat(submissionData["Porcentaje balloon"]);
            periodo = parseFloat(peri);
            const plazo = parseFloat(plzo);
            n = Math.floor(plazo / periodo); // Redondear hacia abajo
    
            const amountt = amount;
            let comision = com * 0.01;
            let interes = interestic * 0.01 * (periodo / 360);
            const R = residual * 0.01 * amountt / Math.pow(1 + interes, n);
            payment = (amountt - R) * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
    
            // Utilizar el valor redondeado de n en los cálculos
            payment = (amountt - R) * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
            var amort = [0];
            var int = [0];
            var saldo_inicial = [amountt * (1 + comision)];
            var saldo_final = [amountt * (1 + comision)];
            var pago = [0];
            var iva = [0];
            
            //Nuestro loop con ecuaciones en diferencia
            for (let i = 0; i <= n; i++) {
                pago[i + 1] = payment;
                int[i + 1] = saldo_final[i] * interes / 1.16;
                iva[i + 1] = int[i + 1] * 0.16;
                amort[i + 1] = payment - int[i + 1] - iva[i + 1];
                saldo_inicial[i + 1] = saldo_final[i] + int[i + 1] + iva[i + 1];
                saldo_final[i + 1] = saldo_final[i] - amort[i + 1];
            }
            pago[n] = saldo_inicial[n];
            saldo_final[n] = 0;
            amort[n] = pago[n] - int[n] - iva[n];
        }
            var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
            var fecha = [hoy];
            
            
            // Creemos una función que nos permita sumar periodos
            var numOfDays = periodo; // Número de días a sumar, puedes cambiarlo a lo que necesites.
        
           
            periodos = [0]
            // Un loopsillo de periodos y fechas. Lo separamos por obvias razones
            for (let i = 0; i < n; i++) {
                periodos[i + 1] = periodos[i] + 1;
                fecha[i + 1] = addDays(numOfDays * (i + 1), new Date(hoy)); // Sumamos el total de días acumulados hasta el momento
            }
            fecha[0] = addDays(numOfDays * 0, new Date(hoy)); // Sumamos el total de días acumulados hasta el momento
              console.log("Fecha vector:", fecha)
            const idunique = submissionData["No. Anexo"]
            const nameAcred = submissionData["Nombre de Acreditada"];
            const empresa = submissionData["No. Contrato Maestro"];

            const headers = ["Periodo", "Saldo Inicial", "Inter\u00e9s", "I.V.A.", "Amortizaci\u00f3n", "Pago parcial", "Saldo Final", "Fecha", "No. Anexo", "Acreditada", "No. Contrato Maestro"];
            const table = document.createElement("table");
            table.setAttribute("id", "generated-table");

            const header = table.createTHead();
            const headerRow = header.insertRow(0);
            for (let i = 0; i < headers.length; i++) {
                const th = document.createElement("th");
                th.textContent = headers[i];
                headerRow.appendChild(th);
            }
            
            var typeProject = "Crédito Mercado Abierto"
            const tbody = table.createTBody();
            for (let i = 0; i <= n; i++) {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = periodos[i];
                row.insertCell(1).innerHTML = `$${saldo_inicial[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(2).innerHTML = `$${int[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(3).innerHTML = `$${iva[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(4).innerHTML = `$${amort[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(5).innerHTML = `$${pago[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(6).innerHTML = `$${saldo_final[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(7).textContent = fecha[i];
                row.insertCell(8).textContent = typeProject;
                row.insertCell(9).textContent = idunique;
                row.insertCell(10).textContent = nameAcred;
                row.insertCell(11).textContent = empresa;
            }

            const tfoot = table.createTFoot();
            const sumRow = tfoot.insertRow(0);
            sumRow.classList.add('totals-row1');
            sumRow.insertCell(0).textContent = 'Sum of Displayed Rows';
            for (let i = 1; i <= 10; i++) {
                sumRow.insertCell(i).setAttribute('id', `demosum${i}`);
            }

            return table;
        }
function ArrendamientoTable(submissionData) {
        const interestic = parseFloat(submissionData["Tasa"]);
        const com = parseFloat(submissionData["Comision"]);
        console.log("Comisión:", com)
        const r = parseFloat(submissionData["Rentas en deposito"]);
        const b = parseFloat(submissionData["Backend"]);
        const amount = parseFloat(submissionData["Costo del equipo"]);
        console.log("Costo del equipo:", amount)
        const residual = parseFloat(submissionData["Residual"]);
        console.log("Residual:", residual)
        const accesorio = parseFloat(submissionData["Costo de accesorios"]);
        const periodo = parseFloat(submissionData["Periodicidad"]);
        const plazo = parseFloat(submissionData["Plazo"]);
        const fecha_inicio = submissionData["Fecha de inicio"];
        let n = Math.floor(plazo / periodo); // Redondear hacia abajo
            
        const amountt = 1 * amount;
        const subtotal = amountt/1.16;
                
        //const date = new Date();
        let comision = com * 0.01;
        let interes = interestic * 0.01 * (periodo / 360);
        const R=(residual*0.01)*amountt/Math.pow(1 + interes, n)
        const Rg = ((residual + b)*0.01)*amountt/Math.pow(1 + interes, n)
        console.log(Rg)
        console.log(R)
        let payment = (amountt-R) * interes / (1 - Math.pow(1 + interes, -n));
        let pg = (amountt-Rg) * (1+comision) * interes / (1 - Math.pow(1 + interes, -n));
        console.log(pg)
        console.log("Pago Renta:", payment)
        // Utilizar el valor redondeado de n en los cálculos
              
        let d = (payment/1.16)*n;
        let cost = ((payment*n+(amountt*(residual*0.01)))/amountt-1)*100;
        let rsdl = residual + b
        console.log(rsdl)
                
        amort = [0]
        amortg = [0]
        int = [0]
        intG=[0]
        ivaG=[0]
        saldo_inicial = [amountt];
        saldo_final = [amountt];
        saldo_finalG = [amountt]
        saldo_inicialG = [amountt];
        pago = [0]
        iva = [0]
        iva_ap=[0]
        renta = [0]
        total = [0]
            
        //Nuestro loop con ecuaciones en diferencia
        for (i = 0; i<=n; i++){
            pago[i+1] = payment;
            int[i+1] = saldo_final[i]*interes/1.16;
            intG[i+1] = saldo_finalG[i]*interes/1.16;
            ivaG[i+1] = intG[i+1]*0.16;
            iva[i+1] = int[i+1]*0.16;
            amort[i+1] = payment - int[i+1] - iva[i+1];
            amortg[i+1] = pg- intG[i+1] - ivaG[i+1]
            saldo_inicial[i+1] = saldo_final[i] + int[i+1] + iva[i+1];
            saldo_inicialG[i+1] = saldo_finalG[i] + intG[i+1] + ivaG[i+1];
            saldo_final[i+1] = saldo_final[i] - amort[i+1];
            saldo_finalG[i+1] = saldo_finalG[i] - amortg[i+1];  
        }
                  
        //Último pago
        pago[n] = saldo_inicial[n]
        saldo_final[n] = 0
        amort[n] = pago[n] -int[n]-iva[n]
              
        let pgAccs= [];
        const yP = Math.floor(360/periodo)
        for (let i = 0; i < Math.floor(n / yP); i++) {
          for (let j = 0; j < yP; j++) {
              let paymentsAccs = (accesorio * interes )/ (1 - Math.pow(1 + interes, -yP));
              pgAccs.push(paymentsAccs);
            }
        }
            
        let remaining = n % yP;
        if (remaining > 0) {
            for (let j = 0; j < remaining; j++) {
                let paymentsAccs = (accesorio * interes) / (1 - Math.pow(1 + interes, -remaining));
                pgAccs.push(paymentsAccs);
            }
        }
            
        console.log('Pago de accesorio:',pgAccs);
            
        let pgAccsneto = [0];
        let saldo_inaccs = [accesorio];
        let saldo_finaccs = [accesorio];
        let intaccs = [0];
        let amortccs = [0];
        let ivaccs = [0];
                
        for (let i = 0; i <= n; i++) {
            pgAccsneto[i + 1] = pgAccs[i] / 1.16;
            renta[i+1] = payment/1.16
            iva_ap[i+1] = (renta[i+1] + pgAccsneto[i+1])*0.16
            total[i+1] = renta[i+1]+iva_ap[i+1]+pgAccsneto[i+1]
            intaccs[i + 1] = saldo_finaccs[i] * interes / 1.16;
            ivaccs[i + 1] = intaccs[i + 1] * 0.16;
            amortccs[i + 1] = pgAccsneto[i] - intaccs[i + 1] - ivaccs[i + 1];
            saldo_inaccs[i + 1] = saldo_finaccs[i] + intaccs[i + 1] + ivaccs[i + 1];
            saldo_finaccs[i + 1] = saldo_finaccs[i] - amortccs[i + 1];
            
            if (saldo_finaccs[i + 1] <= 0) {
                saldo_finaccs[i + 1] = accesorio; // Reset to accesorio if it reaches zero
            }
        }
              

        var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
        var fecha = [hoy];
 
        // Creemos una función que nos permita sumar periodos
        var numOfDays = periodo; // Número de días a sumar, puedes cambiarlo a lo que necesites.
        
        
        periodos = [0]
        // Un loopsillo de periodos y fechas. Lo separamos por obvias razones
        for (let i = 0; i < n; i++) {
            periodos[i + 1] = periodos[i] + 1;
            fecha[i + 1] = addDays(numOfDays * (i + 1), new Date(hoy)); // Sumamos el total de días acumulados hasta el momento
        }
        fecha[0] = addDays(numOfDays * 0, new Date(hoy)); // Sumamos el total de días acumulados hasta el momento
        console.log("Fecha vector:", fecha)
        const idunique = submissionData["No. Anexo"]
        const nameAcred = submissionData["Nombre de Acreditada"];
        const empresa = submissionData["No. Contrato Maestro"];

        const headers = ["Periodo", "Renta", "Accesorios", "I.V.A.",  "Total", "Vencimiento anticipado", "Vencimiento Anticipado Accesorios", "Fecha", "No. Anexo", "Acreditada", "No. Contrato Maestro"];
        const table = document.createElement("table");
        table.setAttribute("id", "generated-table");

        const header = table.createTHead();
        const headerRow = header.insertRow(0);
        for (let i = 0; i < headers.length; i++) {
            const th = document.createElement("th");
            th.textContent = headers[i];
            headerRow.appendChild(th);
        }
            
        var typeProject = "Arrendamiento"
        const tbody = table.createTBody();
        for (let i = 0; i <= n; i++) {
            const row = tbody.insertRow();
            row.insertCell(0).innerHTML = periodos[i];
            row.insertCell(1).innerHTML = `$${saldo_inicialG[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            row.insertCell(2).innerHTML = `$${int[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            row.insertCell(3).innerHTML = `$${iva_ap[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            row.insertCell(4).innerHTML = `$${amort[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            row.insertCell(5).innerHTML = `$${total[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            row.insertCell(6).innerHTML = `$${saldo_finalG[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
            row.insertCell(7).textContent = fecha[i];
            row.insertCell(8).textContent = typeProject;
            row.insertCell(9).textContent = idunique;
            row.insertCell(10).textContent = nameAcred;
            row.insertCell(11).textContent = empresa;
        }

        const tfoot = table.createTFoot();
        const sumRow = tfoot.insertRow(0);
        sumRow.classList.add('totals-row1');
        sumRow.insertCell(0).textContent = 'Sum of Displayed Rows';
        for (let i = 1; i <= 10; i++) {
            sumRow.insertCell(i).setAttribute('id', `demosum${i}`);
        }

           return table;
        }
function NominaTable(submissionData) {
        if (!submissionData) return;

        const tic = parseFloat(submissionData["Tasa"]);
        const comision = parseFloat(submissionData["Comision"]);
        const monto = parseFloat(submissionData["Validación Monto Solicitado"].replace("$", "").replace(/,/g, ''));
        const periodo = parseFloat(submissionData["Periodicidad"]);
        const plazo = parseFloat(submissionData["Plazo"]);
        const fechai = submissionData["Fecha de inicio"];
        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(fechai);
        const fechaInicio = new Date(fecha_inicio);
        const n = Math.floor(plazo / periodo);
        localStorage.setItem('numperiodos', n);
        const amountt = 1 * monto;
        let comisionPorcentaje = comision * 0.01;
        let interes = tic * 0.01 * (periodo / 360);
        let payment = amountt * (1 + comisionPorcentaje) * interes / (1 - Math.pow(1 + interes, -n));
        let d = payment * n;
        let cost = (((d / amountt - 1) * 100) * 12) / ((plazo / 30) * 1.16);

        const paymentDates = generarFechasDePago(fechaInicio, n + 1, periodo);

        const periodos = [0];
        const amort = [0];
        const int = [0];
        const saldo_inicial = [amountt * (1 + comisionPorcentaje)];
        const saldo_final = [amountt * (1 + comisionPorcentaje)];
        const pago = [0];
        const iva = [0];
        for (let i = 0; i <= n; i++) {
            periodos[i + 1] = periodos[i] + 1;
            pago[i + 1] = payment;
            int[i + 1] = saldo_final[i] * interes / 1.16;
            iva[i + 1] = int[i + 1] * 0.16;
            amort[i + 1] = payment - int[i + 1] - iva[i + 1];
            saldo_inicial[i + 1] = saldo_final[i] + int[i + 1] + iva[i + 1];
            saldo_final[i + 1] = saldo_final[i] - amort[i + 1];
        }

        function generateID(fullName) {
            var words = fullName.split(" ");
            var id = "";
            for (var i = 0; i < words.length; i++) {
                id += words[i].charAt(0);
            }
              return id.slice(0, 3).toUpperCase();
            }

        const idinciales = generateID(submissionData["Nombre completo"]);
        const idcounter = submissionData["IDcounter"];
        const idunique = idinciales + idcounter;
        const nameAcred = submissionData["Nombre completo"];
        const empresa = submissionData["Empresa"];

        const headers = ["Periodo", "Saldo Inicial", "Inter\u00e9s", "I.V.A.", "Amortizaci\u00f3n", "Pago parcial", "Saldo Final", "Fecha", "ID", "Acreditada", "Empresa"];
        const table = document.createElement("table");
        table.setAttribute("id", "generated-table");

        const header = table.createTHead();
        const headerRow = header.insertRow(0);
        for (let i = 0; i < headers.length; i++) {
            const th = document.createElement("th");
            th.textContent = headers[i];
            headerRow.appendChild(th);
        }
        var typeProject = "Crédito de Nómina"
            const tbody = table.createTBody();
            for (let i = 0; i <= n; i++) {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = periodos[i] + " de " + n;
                row.insertCell(1).innerHTML = `$${saldo_inicial[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(2).innerHTML = `$${int[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(3).innerHTML = `$${iva[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(4).innerHTML = `$${amort[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(5).innerHTML = `$${pago[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(6).innerHTML = `$${saldo_final[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(7).textContent = paymentDates[i].toLocaleDateString('es-ES');
                row.insertCell(8).textContent = typeProject;
                row.insertCell(9).textContent = idunique;
                row.insertCell(10).textContent = nameAcred;
                row.insertCell(11).textContent = empresa;
            }

            const tfoot = table.createTFoot();
            const sumRow = tfoot.insertRow(0);
            sumRow.classList.add('totals-row');
            sumRow.insertCell(0).textContent = 'Sum of Displayed Rows';
            for (let i = 1; i <= 10; i++) {
                sumRow.insertCell(i).setAttribute('id', `demosum${i}`);
            }

            return table;
        }

 // Function to extract table data and convert to JSON
        function extractTableData(tableId) {
            const table = document.getElementById(tableId);
            const headers = Array.from(table.querySelectorAll('thead th')).map(th => th.textContent.trim());
            const rows = Array.from(table.querySelectorAll('tbody tr'));
        
            const data = rows.map(row => {
                const rowData = {};
                Array.from(row.cells).forEach((cell, index) => {
                    const header = headers[index];
                    rowData[header] = cell.textContent.trim();
                });
                return rowData;
            });
        
            return data;
        }
        
         
Promise.all(fetchPromises).then(() => {
    // Only after all fetchPromises have been resolved, proceed with processing tablesPromises

    const tablesPromises = labeledSubmissionIDs.map(({ id, label }) => {
        return fetch(`https://api.jotform.com/submission/${id}?apiKey=${apiKey}`)
            .then(response => response.json())
            .then(data => {
                var jsonData = {};

                var response = data.content.answers;
                const answerTextPairs = [];

                Object.entries(response).forEach(([key, value]) => {
                    if (value.hasOwnProperty("answer") && value.hasOwnProperty("text")) {
                        if (Object.prototype.toString.call(value.answer) === "[object Object]") {
                            value.answer = Object.values(value.answer).join(" ");
                        }
                        answerTextPairs.push([value.answer, value.text]);
                    }
                });

                const newDictionary = answerTextPairs.reduce((dictionary, [answer, text]) => {
                    dictionary[text] = answer;
                    return dictionary;
                }, {});

                jsonData = newDictionary;
                console.log(jsonData);

                let table;
                switch (label) {
                    case 'arrendamiento':
                        table = ArrendamientoTable(jsonData);
                        break;
                    case 'creditoopenmkt':
                        table = CreditTable(jsonData);
                        break;
                    case 'nomina':
                        table = NominaTable(jsonData);
                        break;
                    default:
                        console.error(`Unknown label: ${label}`);
                        return null;
                }
               return table

            });
    });



    Promise.all(tablesPromises)
        .then(tables => {
            const tableContainer = document.getElementById("tables-container");
            console.log("Tabla:", tableContainer);

            const headers = ["Periodo", "Saldo Inicial", "Inter\u00e9s", "I.V.A.", "Amortizaci\u00f3n", "Pago parcial", "Saldo Final", "Fecha", "Tipo de Proyecto", "ID", "Acreditada", "Empresa"];
            const concatenatedTable = document.createElement("table");
            concatenatedTable.setAttribute("id", "concatenated-table");
            concatenatedTable.classList.add('TF');

            const caption = document.createElement("caption");
            caption.textContent = "Your Table Caption Here";
            concatenatedTable.appendChild(caption);

            const thead = concatenatedTable.createTHead();
            const headerRow = thead.insertRow(0);
            headers.forEach(header => {
                const th = document.createElement("th");
                th.textContent = header;
                headerRow.appendChild(th);
            });

            const tbody = concatenatedTable.createTBody();
            tables.forEach(table => {
            if (table) {
                const rows = table.tBodies[0].rows;
                for (let i = 0; i < rows.length; i++) {
                    tbody.appendChild(rows[i].cloneNode(true));
                }
            }
        });

        const tfoot = concatenatedTable.createTFoot();
        const sumRow = tfoot.insertRow(0);
        sumRow.classList.add('totals-row');
        sumRow.insertCell(0).textContent = 'Total';
        for (let i = 1; i <= 6; i++) {
            sumRow.insertCell(i).setAttribute('id', `demosum${i}`);
        }

        tableContainer.appendChild(concatenatedTable);
        
        setTimeout(() => {
            console.log("Initializing TableFilter");
            var filtersConfig = {
                base_path: 'https://unpkg.com/tablefilter@latest/dist/tablefilter/',
                paging: {
                    results_per_page: ['Records: ', [10, 25, 50, 1000]]
                },
                state: {
                    types: ['local_storage'],
                    filters: true,
                    page_number: true,
                    page_length: true,
                    sort: true
                },
                alternate_rows: true,
                btn_reset: true,
                rows_counter: true,
                loader: {
                    html: '<div id="lblMsg"></div>',
                    css_class: 'myLoader'
                },
                status_bar: {
                    target_id: 'lblMsg',
                    css_class: 'myStatus'
                },
                col_8: 'select',
                col_10: 'select',
                rows_counter: {
                    text: 'Items: '
                },
                ignore_diacritics: true,
                mark_active_columns: true,
                highlight_keywords: true,
                no_results_message: true,
                col_types: [
                    'number', 'formatted-number', 'formatted-number', 'formatted-number', 'formatted-number', 'formatted-number', 
                    'formatted-number', { type: 'date', locale: 'fr' }, 'string', 'string', 'string'
                ],
                extensions: [{
                    name: 'sort'
                }, {
                    name: 'colOps',
                    id: [
                        'demosum1',
                        'demosum2',
                        'demosum3',
                        'demosum4',
                        'demosum5',
                        'demosum6'
                    ],
                    col: [
                        1,
                        2,
                        3,
                        4,
                        5,
                        6
                    ],
                    operation: [
                        'sum',
                        'sum',
                        'sum',
                        'sum',
                        'sum',
                        'sum'
                    ],
                    write_method: [
                        'innerHTML',
                        'innerHTML',
                        'innerHTML',
                        'innerHTML',
                        'innerHTML',
                        'innerHTML'
                    ],
                    decimal_precision: [
                        2,
                        2,
                        2,
                        2,
                        2,
                        2
                    ],
                    tot_row_index: [
                        -1, -1, -1, -1, -1, -1
                    ],
                    tot_row_css_class: 'totals-row',
                    format_result: [
                      { prefix: '$' },
                      { prefix: '$' },
                      { prefix: '$' },
                      { prefix: '$' },
                      { prefix: '$' },
                      { prefix: '$' }
                    ]},
                    {   name: 'colsVisibility',
                      text: 'Columns: ',
                      enable_tick_all: true
                  }],
            };

            var tf = new TableFilter('concatenated-table', filtersConfig);
            tf.init();

            console.log("TableFilter initialized", tf);
            // Now that tables are rendered, extract data
                    const tableData = extractTableData('concatenated-table');
                
                    const jsonData = JSON.stringify(tableData); // Convert data to JSON string
                    const parsedData = JSON.parse(jsonData); // Parse JSON string back to array
                    console.log(parsedData)
            
                    const parseCurrency = (value) => parseFloat(value.replace(/[\$,]/g, ""));
                    const parseDate = (dateString) => {
                        const [day, month, year] = dateString.split('/');
                        return new Date(year, month - 1, day);
                    };
            
                    const currentDate = new Date();
                    const amountsDue = new Array(12).fill(0);
                    const interestDue = new Array(12).fill(0);
                    const amortDue = new Array(12).fill(0);
            
                    parsedData.forEach(record => {
                        const recordDate = parseDate(record.Fecha);
                        const monthDiff = (recordDate.getFullYear() - currentDate.getFullYear()) * 12 + (recordDate.getMonth() - currentDate.getMonth());
                        if (monthDiff >= 0 && monthDiff < 12) {
                            amountsDue[monthDiff] += parseCurrency(record['Pago parcial']);
                        }
                    });
                    parsedData.forEach(record => {
                        const recordDate = parseDate(record.Fecha);
                        const monthDiff = (recordDate.getFullYear() - currentDate.getFullYear()) * 12 + (recordDate.getMonth() - currentDate.getMonth());
                        if (monthDiff >= 0 && monthDiff < 12) {
                            interestDue[monthDiff] += parseCurrency(record['Interés']);
                        }
                    });
                    parsedData.forEach(record => {
                        const recordDate = parseDate(record.Fecha);
                        const monthDiff = (recordDate.getFullYear() - currentDate.getFullYear()) * 12 + (recordDate.getMonth() - currentDate.getMonth());
                        if (monthDiff >= 0 && monthDiff < 12) {
                            amortDue[monthDiff] += parseCurrency(record['Amortización']);
                        }
                    });
            
                    const labels = [];
                    for (let i = 0; i < 12; i++) {
                        const date = new Date(currentDate.getFullYear(), currentDate.getMonth() + i, 1);
                        labels.push(date.toLocaleString('default', { month: 'short', year: 'numeric' }));
                    }
                    
                    // Insert the current month sum into the HTML
                    document.getElementById("cpcMonthSum").textContent = `$${amountsDue[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                    document.getElementById("intMonthSum").textContent = `$${interestDue[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                    
                    const ctx = document.getElementById("cpcChart").getContext("2d");
                    new Chart(ctx, {
                        type: "line",
                        data: {
                            labels: labels,
                            datasets: [{
                                label: "Total",
                                tension: 0.4,
                                borderWidth: 0,
                                pointRadius: 2,
                                pointBackgroundColor: "#6a4c93",
                                borderColor: "#6a4c93",
                                borderWidth: 3,
                                backgroundColor: 'transparent',
                                fill: true,
                                data: amountsDue,
                                maxBarThickness: 6
                            },
                            {
                              label: "Interés",
                              tension: 0.4,
                              borderWidth: 0,
                              pointRadius: 2,
                              pointBackgroundColor: "#8ac926",
                              borderColor: "#8ac926",
                              borderWidth: 3,
                              backgroundColor: 'transparent',
                              data: interestDue,
                              maxBarThickness: 6
                            },
                            {
                              label: "Amortización",
                              tension: 0.4,
                              borderWidth: 0,
                              pointRadius: 2,
                              pointBackgroundColor: "#ff595e",
                              borderColor: "#ff595e",
                              borderWidth: 3,
                              backgroundColor: 'transparent',
                              data: amortDue,
                              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: 1
                                        },
                                        stepSize: 10000
                                    }
                                },
                            },
                        },
                    });


// Function to parse date in DD/MM/YYYY or YYYY-MM-DD format
function formatDate(dateString) {
    if (dateString.includes("/")) {
        const [day, month, year] = dateString.split("/");
        return new Date(`${year}-${month}-${day}`);
    } else if (dateString.includes("-")) {
        return new Date(dateString);
    } else {
        return null;
    }
}

// Get the current date and the date for 6 days from now
const today = new Date(); // This is today
today.setHours(0, 0, 0, 0); // Set time to start of the day for accurate comparison

const sixDaysFromNow = new Date(); // Create a new Date object for 6 days from now
sixDaysFromNow.setDate(today.getDate() + 6); // Set it to 6 days after today
sixDaysFromNow.setHours(23, 59, 59, 999); // Set time to end of the day for accurate comparison

// Filter the payments due within the next 7 days, including today
const filteredPayments = tableData.filter(row => {
    const dateParts = row["Fecha"].split('/'); // Assuming date is in "DD/MM/YYYY" format
    const paymentDate = new Date(`${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`); // Construct the date as "YYYY-MM-DD"

    // Check if the payment date falls between today and six days from now
    return paymentDate >= today && paymentDate <= sixDaysFromNow;
});


// Extract relevant fields for the new table
const filteredData = filteredPayments.map(entry => ({
    "Acreditada": entry["Acreditada"],
    "Tipo de Proyecto": entry["Tipo de Proyecto"],
    "Fecha": entry["Fecha"],
    "Pago Parcial": entry["Pago parcial"]
}));

// Log the filtered data to verify
console.log(filteredData);

function createTable(data) {
    const table = document.createElement("table");
    const thead = table.createTHead();
    const tbody = table.createTBody();
    const tfoot = table.createTFoot();

    // Create header row
    const headers = ["Acreditada", "Tipo de Proyecto", "Fecha", "Pago Parcial"];
    const headerRow = thead.insertRow();
    headers.forEach(headerText => {
        const th = document.createElement("th");
        th.appendChild(document.createTextNode(headerText));
        headerRow.appendChild(th);
    });

    // Populate table with filtered data
    data.forEach(rowData => {
        const row = tbody.insertRow();
        headers.forEach(header => {
            const cell = row.insertCell();
            cell.appendChild(document.createTextNode(rowData[header]));
        });
    });

    // Create footer row for the sum
    const sumRow = tfoot.insertRow(0);
    sumRow.classList.add('totals-row');

    // Insert cells for the footer row
    sumRow.insertCell(0).textContent = 'Total Pagos Parciales'; // First cell label
    sumRow.insertCell(1); // Empty cell for 'Tipo de Proyecto'
    sumRow.insertCell(2); // Empty cell for 'Fecha'
    const sumCell = sumRow.insertCell(3); // Cell for 'Pago Parcial' sum
    sumCell.setAttribute('id', 'demosum1');

    return table;
}

// Assuming you have an element with id "tableContainer" to hold the table
const tableContainer = document.getElementById("myChart");
const paymentTable = createTable(filteredData);
tableContainer.appendChild(paymentTable);

var tf = new TableFilter(
    document.querySelector('#myChart table'),
    {
        base_path: 'https://unpkg.com/tablefilter@latest/dist/tablefilter/',
        grid: false,
        alternate_rows: false,
        btn_reset: false,
        status_bar: false,
        col_types: [
            'string', 'string', { type: 'date', locale: 'fr' },
            'formatted-number'
        ],
        sort_select: false,

        // extensions: sort and column operations
        extensions: [
            {
                name: 'sort'
            }, {
                name: 'colOps',
                id: [
                    'demosum1',
                ],
                col: [
                    3
                ],
                operation: [
                    'sum'
                ],
                decimal_precision: [
                    2
                ],
                format_result: [
                      { prefix: '$' }
                    ]},
                
        ]
    }
);
tf.init();
                        

                }, 100);
             
        })
        .catch(error => {
            console.error("Error processing tables: ", error);
        });
});