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

        // Get a reference to the table container element
        var tableContainer3 = document.getElementById('credito_nomina');


        // Fetch form submissions from JotForm API
        fetch(`https://api.jotform.com/form/${formID}/submissions?apiKey=${apiKey}&limit=100`)
        .then(response => response.json())
        .then(data => {
            var submissions = data.content;
            var jsonData = [];

            submissions.forEach(submission => {
                var response = submission.answers;
                const answerTextPairs = [];

                var id = submission.id;
                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;
                }, {});

                newDictionary['id'] = id;
                jsonData.push(newDictionary);
            });

            var table = document.createElement('table');
            table.classList.add('table');

            var thead = document.createElement('thead');
            var headerRow = document.createElement('tr');

            var counterHeaderCell = document.createElement('th');
            counterHeaderCell.textContent = 'Counter';
            counterHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
            headerRow.appendChild(counterHeaderCell);

            var detailsHeaderCell = document.createElement('th');
            detailsHeaderCell.textContent = 'Contrato Maestro';
            detailsHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
            headerRow.appendChild(detailsHeaderCell);

            var anexoHeaderCell = document.createElement('th');
            anexoHeaderCell.textContent = 'Anexo';
            anexoHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
            headerRow.appendChild(anexoHeaderCell);

            var reporteHeaderCell = document.createElement('th');
            reporteHeaderCell.textContent = 'Reporte';
            reporteHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
            headerRow.appendChild(reporteHeaderCell);

            var keys = Object.keys(jsonData[0]);
            keys.forEach(function(key) {
                var headerCell = document.createElement('th');
                headerCell.textContent = key;
                headerCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
                headerRow.appendChild(headerCell);
            });

            thead.appendChild(headerRow);
            table.appendChild(thead);

            var tbody = document.createElement('tbody');

            jsonData.forEach(function(entry, index) {
                var row = document.createElement('tr');

                var counterCell = document.createElement('td');
                counterCell.textContent = index + 1;
                row.appendChild(counterCell);

                var buttonCell = document.createElement('td');
                var detailsButton = document.createElement('button');
                detailsButton.textContent = 'Generar Contrato';
                detailsButton.classList.add("btn", "btn-primary");
                detailsButton.addEventListener('click', function() {
                    sessionStorage.setItem('rowData', JSON.stringify(entry));
                    console.log("rowData stored in session:", entry);
                    window.location.href = '../docs/contrato_maestro.html';
                });
                buttonCell.appendChild(detailsButton);
                row.appendChild(buttonCell);

                var idCell = document.createElement('td');
                var idButton = document.createElement('button');
                idButton.textContent = 'Descargar reporte';
                idButton.classList.add("btn", "btn-warning");
                idButton.addEventListener('click', function() {
                    window.location.href = `https://www.jotform.com/pdf-submission/${entry.id}`;
                });
                idCell.appendChild(idButton);
                row.appendChild(idCell);

                var profButtonCell = document.createElement('td');
                var profDetailsButton = document.createElement('button');
                profDetailsButton.textContent = 'Perfil';
                profDetailsButton.classList.add("btn", "btn-success");
                profDetailsButton.addEventListener('click', function() {
                    sessionStorage.setItem('rowData', JSON.stringify(entry));
                    console.log("rowData stored in session:", entry);
                    window.location.href = 'https://agata.financial/clientes/incorp/dashboard_incorp/pages/profile.html';
                });
                profButtonCell.appendChild(profDetailsButton);
                row.appendChild(profButtonCell);

                keys.forEach(function(key) {
                    var cell = document.createElement('td');
                    cell.textContent = entry[key];
                    row.appendChild(cell);
                });

                tbody.appendChild(row);
            });

            table.appendChild(tbody);
            tableContainer3.appendChild(table);

            // Initialize TableFilter
            var tfConfig = {
                base_path: 'https://unpkg.com/tablefilter@latest/dist/tablefilter/', // Adjust the path as needed
                alternate_rows: true,
                btn_reset: true,
                rows_counter: true,
                ignore_diacritics: true,
                mark_active_columns: true,
                highlight_keywords: true,
                no_results_message: true,
                loader: true,
                status_bar: true,
                no_results_message: true,
                watermark: 'BUSCAR POR NOMBRE',
                single_filter: {
                    include_cols: [17],
                    css_class: 'form-control',
                },
                paging: {
                        results_per_page: ['Records: ', [10, 20, 50, 100]]
                    },
                auto_filter: true,
                col_types: [
                    'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string',
                    'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string',
                    'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string',
                    'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string'
                ],
                extensions: [{
                    name: 'sort'
                },
                { name: 'colsVisibility',
                      at_start: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20],
                      text: 'Columns: ',
                      enable_tick_all: true
                  }],
                filters_cell_tag: 'th',
                themes: [{
                    name: 'transparent'
                  }],
            };

            var tf = new TableFilter(table, tfConfig);
            tf.init();
        })
        .catch(error => {
            console.error(error);
        });
   
    