const formID1 = '243168214308857';
const apiKey1 = '6e2676fa4067aecefdfae6fca7c4bb41';

fetch(`https://api.jotform.com/form/${formID1}/submissions?apiKey=${apiKey1}&limit=1000`)
    .then(response => response.json())
    .then(data => {
        console.log("All data:", data); // Log all data to see its structure

        const submissionIDs1 = 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 => entry.id);

        console.log("Proyectos activos:", submissionIDs1);

        function generateTable(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] = pgAccs[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.
        
            function addDays(numOfDays, date) {
                date.setDate(date.getDate() + numOfDays);
                return date.toLocaleDateString('en-GB');
            }
            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 table1 = document.createElement("table");
            table1.setAttribute("id", "generated-table");

            const header = table1.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);
            }
            
            
            const tbody = table1.createTBody();
            for (let i = 0; i <= n; i++) {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = periodos[i];
                row.insertCell(1).innerHTML = `$${renta[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(2).innerHTML = `$${pgAccsneto[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 = `$${total[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(5).innerHTML = `$${saldo_inicialG[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(6).innerHTML = `$${saldo_inaccs[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(7).textContent = fecha[i];
                row.insertCell(8).textContent = idunique;
                row.insertCell(9).textContent = nameAcred;
                row.insertCell(10).textContent = empresa;
            }

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

            return table1;
        }

        

        const tablesPromises = submissionIDs1.map(submissionID1 => {
            return fetch(`https://api.jotform.com/submission/${submissionID1}?apiKey=${apiKey1}`)
                .then(response => response.json())
                .then(data => {
                    var submissions = data.content;
                    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;

                    const table1 = generateTable(jsonData);
                    return table1;
                });
        });
        // 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(tablesPromises)
            .then(tables => {
                const tableContainer1 = document.getElementById("tabla-openmkt");
                console.log("Tabla:", tableContainer1);

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

                const thead = concatenatedTable1.createTHead();
                const headerRow = thead.insertRow(0);
                for (let i = 0; i < headers.length; i++) {
                    const th = document.createElement("th");
                    th.textContent = headers[i];
                    headerRow.appendChild(th);
                }

                const tbody = concatenatedTable1.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 = concatenatedTable1.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}`);
                }

                tableContainer1.appendChild(concatenatedTable1);

                setTimeout(() => {
                    console.log("Initializing TableFilter");
                    var filtersConfig = {
                        base_path: 'https://unpkg.com/tablefilter@latest/dist/tablefilter/',
                        paging: {
                            results_per_page: ['Records: ', [10, 25, 50, 100]]
                        },
                        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_9: '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: '$' }
                            ]
                        }]
                    };

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

                    console.log("TableFilter initialized", tf);
                    // Now that tables are rendered, extract data
                    const tableData = extractTableData('concatenated-table1');
                
                    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['Total']);
                        }
                    });
                    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['Accesorios']);
                        }
                    });
                    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['Renta']);
                        }
                    });
            
                    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' }));
                    }
                     console.log(interestDue);
                     console.log(amountsDue)
                    // 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 = `$${amortDue[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: "Accesorios",
                              tension: 0.4,
                              borderWidth: 0,
                              pointRadius: 2,
                              pointBackgroundColor: "#8ac926",
                              borderColor: "#8ac926",
                              borderWidth: 3,
                              backgroundColor: 'transparent',
                              data: interestDue,
                              maxBarThickness: 6
                            },
                            {
                              label: "Renta",
                              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
                                        },
                                         // Set step size for y-axis
                                    }
                                },
                                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
                                        },
                                        stepSize: 100000
                                    }
                                },
                            },
                        },
                    });
                }, 100); 
        
            });
    });
