const formID = '243167507287867';
const apiKey = '6e2676fa4067aecefdfae6fca7c4bb41';

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

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

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

    //Function que solo añade meses a la fecha
      function addMonths(originalDate, monthsToAdd) {
      // Make a copy of the original date to avoid modifying it directly
      const newDate = new Date(originalDate);
    
      // Calculate the new month
      const currentMonth = newDate.getMonth();
      newDate.setMonth(currentMonth + monthsToAdd);
    
      return newDate;
    }
    
    function generateTable(submissionData) {    //////Variables para el cálulo///
      const options = { year: 'numeric', month: 'long', day: 'numeric' };
      const kic = parseFloat(submissionData["kic"]);
      console.log("kic:", kic)
      const kcv = parseFloat(submissionData["kcv"]);
      console.log("kcv:", kcv)
      const tic = parseFloat(submissionData["tic"]);
      console.log("tic:", tic)
      const monto = parseFloat(submissionData["Monto a Aportar"].replace(/[\$,]/g, ""));
      console.log("Monto inversión:", monto)
      const tcv = parseFloat(submissionData["tcv"]);
      console.log("tcv:", tcv)
      const plzo= parseFloat(submissionData["Plazo de inversi\u00f3n"]);
      console.log("Plazo:", plzo)
      const modldd = submissionData["Modalidad de Inversi\u00f3n"];
      console.log(modldd)
      const fechai= submissionData["Fecha de inicio"];
      console.log("Fecha de inicio:", fechai)
    
    var numOfMonth = 1; // Número de días a sumar, puedes cambiarlo a lo que necesites.
    let periodos = [];
  let fecha = [];
  let saldogl = [];
  let int = [];
  let saldoord = [];
  let saldototal = [];
  let pagoex = [];
  let pagop = [];
    
        if(modldd === 'Inversi\u00f3n Balloon'){
          const interestic = tic
          amount = monto
          const residual = kic
          const periodo = kcv
          const plazo = plzo
          const fecha_inicio = fechai
          var n = Math.floor(plazo / periodo); // Redondear hacia abajo
        
          const amountt = 1 * amount;
            
          //const date = new Date();
          let interes = interestic * 0.01 * (periodo / 360);
          const R=residual*0.01*amountt/Math.pow(1 + interes, n)
          let payment = (amountt-R) * interes / (1 - Math.pow(1 + interes, -n));
        
          // Utilizar el valor redondeado de n en los cálculos
          payment = (amountt-R) * interes / (1 - Math.pow(1 + interes, -n));
          
          var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
          var inicio = [hoy.toLocaleDateString('es-ES', options)];
          fecha = [hoy];
          periodos = [0];
          saldogl = [0]
          int = [0]
          saldoord = [amountt];
          saldototal = [amountt];
          pagoex = [0]
          pagop[0]
            
        
          //Nuestro loop con ecuaciones en diferencia
          for (i = 0; i<=n; i++){
             periodos[i + 1] = periodos[i] + 1;
            fecha[i + 1] = addMonths(hoy, numOfMonth*[i+1]);
            pagoex[i+1] = payment;
            int[i+1] = saldototal[i]*interes;
            saldogl[i+1] = payment - int[i+1];
            saldoord[i+1] = saldototal[i] + int[i+1];
            saldototal[i+1] = saldototal[i] - saldogl[i+1];
            pagop[i+1] = pagop[i];
              }
           pagop[n] = saldoord[n]
           saldototal[n] = 0
           saldogl[n] = pagop[n] -int[n]
 
        }else {
            const interest_ic = parseFloat(tic)
            const interest_cv = parseFloat(tcv)
            amount = monto;
            let amount_inicial
            console.log("Monto:", amount);
            if(modldd == "Mezcla de ambas"){
                const monto_inicial = parseFloat(submissionData["Monto Inicial a Aportar"].replace(/,/g, ''));
                console.log("Monto inicial:", monto_inicial)
                amount_inicial = monto_inicial;
            } else {
                amount_inicial = 0
            }
            console.log("Monto Inicial:", amount_inicial);
            const k_ic = parseFloat(kic)
            const k_cv = parseFloat(kcv)
            const months = parseFloat(plzo)
            console.log("Meses:", months);
            let fecha_inicio
            if(fechai === undefined){
                fechainicio = new Date()
                fecha_inicio = `${fechainicio.getFullYear()}-${fechainicio.getMonth() + 1}-${fechainicio.getDate()}`;
            } else {
                fecha_inicio = fechai
            } 
            const interestic = interest_ic*0.01/12;
            const interestcv = interest_cv*0.01/12;
            const amountt = 1*amount;
            
            let amounttotal;
            let pagostotal;
            let aportacion_ic;
            let aportacion_cv;
            let capital_ic;
            let capital_cv;
            let modalidad;
            
            if(modldd == "Aportaci\u00f3n \u00fanica"){
                amounttotal = 1*amount
                pagostotal = 1*amount
                aportacion_ic= amounttotal*k_ic/100
                aportacion_cv = amounttotal*k_cv/100
                capital_ic = 0
                capital_cv = 0
                modalidad = 1
            } else if(modldd == "Aportaci\u00f3n mensual"){
                amounttotal = 1*amount
                pagostotal = 1*amount*months
                aportacion_ic= amounttotal*k_ic/100
                aportacion_cv = amounttotal*k_cv/100
                capital_ic = amounttotal*k_ic/100
                capital_cv = amounttotal*k_cv/100
                modalidad = 2
            }  else if(modldd == "Mezcla de ambas"){
                amounttotal = 1*(amount+amount_inicial)
                pagostotal = 1*((amount*months)+amount_inicial)
                aportacion_ic= amounttotal*k_ic/100
                aportacion_cv = amounttotal*k_cv/100
                capital_ic = amount*k_ic/100
                capital_cv = amount*k_cv/100
                modalidad = 3
                
            }
        
             // Vectores que utilizaremos en el loop que genera la tabla
        
          var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
          var inicio = [hoy.toLocaleDateString('es-ES', options)];
          fecha = [hoy];
          periodos = [0];
        
            const interest = interest_ic*0.01/12;
            const plazo = months;
            
            const m = months
            console.log(m)
            
            saldoord= [aportacion_ic];
            saldogl = [aportacion_cv];
            pagop = [0];
            saldototal = [amounttotal];
            int = [0];
            interes_g =[0];
               
            for (i = 0; i<=m-1; i++){
                periodos[i + 1] = periodos[i] + 1;
                fecha[i + 1] = addMonths(hoy, numOfMonth*[i+1]);
                 saldoord[i+1] = saldoord[i]*(1+interestic) + capital_ic;
                saldogl[i+1] = saldogl[i]+ capital_cv;
                saldototal[i+1] = saldoord[i+1]+saldogl[i+1];
                pagop[i+1] = saldogl[i]*interestcv;
                interes_g[i+1] = saldogl[i]*interestcv;
                int[i+1] = saldoord[i]*(interestic); 
                }
        
            
            pagoex = [0];
            
            if (modalidad === 1) {
                 for (let i = 0; i <= m; i++) {
                    pagoex[i]= 0+pagop[i];
                }
            } else if (modalidad >= 2) {
                for (let i = 0; i <= m; i++) {
                    pagoex[i]= pagop[i]-amountt;
                }
            }
            console.log("PAGOEX:", pagoex)
            pagoex[m] = saldototal[m-1]+interes_g[m]+int[m]
    }
            console.log(pagoex);
            console.log(saldogl);
            console.log(int);
            console.log(saldoord);
            console.log(saldototal);
            console.log(pagoex);
            console.log(pagop);
            console.log(periodos);
            console.log(fecha);
            let nameAcred;
            if(submissionData["Tipo de inversionista"] == "Persona moral"){
                nameAcred = submissionData["Razón social"];
            } else {
                nameAcred = submissionData["Nombre completo"];
            } 
            const empresa = submissionData["ID"];

             // Table headers
            const headers = [
                "Periodo", "Saldo Ordinario", "Rendimiento Ordinario", "Saldo Global",
                "Rendimiento mensual", "Pagos", "Saldo Total", "Fecha", "Inversionista", "No. Contrato"
            ];
        
            const table = document.createElement("table");
            table.setAttribute("id", "generated-table");
        
            const header = table.createTHead();
            const headerRow = header.insertRow(0);
        
            headers.forEach(headerText => {
                const th = document.createElement("th");
                th.textContent = headerText;
                headerRow.appendChild(th);
            });
        
            const tbody = table.createTBody();
            for (let i = 0; i < periodos.length; i++) {
                const row = tbody.insertRow();
        
                row.insertCell(0).textContent = periodos[i];
                row.insertCell(1).textContent = `$${saldoord[i]?.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(2).textContent = `$${int[i]?.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(3).textContent = `$${saldogl[i]?.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(4).textContent = `$${pagop[i]?.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(5).textContent = `$${pagoex[i]?.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(6).textContent = `$${saldototal[i]?.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
                row.insertCell(7).textContent = fecha[i]?.toLocaleDateString('es-ES');
                row.insertCell(8).textContent = nameAcred;
                row.insertCell(9).textContent = empresa;
                
                
            }
        
            return table
        }


        const tablesPromises = submissionIDs.map(submissionID => {
            return fetch(`https://api.jotform.com/submission/${submissionID}?apiKey=${apiKey}`)
                .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 table = generateTable(jsonData);
                    console.log(table)
                    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(tablesPromises)
    .then(tables => {
        const tableContainer = document.getElementById("table-container");
        console.log("Tabla:", tableContainer);

        var headers = ["Periodo", "Saldo Ordinario", "Rendimiento Ordinario", "Saldo Global", "Rendimiento mensual", "Pagos", "Saldo Total", "Fecha", "Inversionista", "No. Contrato"];
        const concatenatedTable = document.createElement("table");
        concatenatedTable.setAttribute("id", "concatenated-table");
        concatenatedTable.classList.add('TF');

        // Create and append the caption element
        const caption = document.createElement("caption");
        caption.textContent = "Your Table Caption Here";
        concatenatedTable.appendChild(caption);

        const thead = concatenatedTable.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 = 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, 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-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);
                    
            
                    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['Pagos']);
                        }
                    });
                    
            
                    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, ",")}`;
                    
                    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
                            }]
                        },
                        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
                                    }
                                },
                            },
                        },
                    });
                }, 100); 
        
            });
    });
