const formID3 = '240676903884872';
const apiKey3 = '6e2676fa4067aecefdfae6fca7c4bb41';

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

// Fetch form submissions from JotForm API
fetch(`https://api.jotform.com/form/${formID3}/submissions?apiKey=${apiKey3}`)
  .then(response => response.json())
  .then(data => {
    // Assuming the form submission data is stored in the 'response' variable
    var submissions = data.content;

    var jsonData = [];

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

      // Retrieve the id from each submission
      var id = submission.id;

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

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

      // Add the id to the newDictionary
      newDictionary['id'] = id;

      jsonData.push(newDictionary);
    });

    // Create the table element
    var tablepm = document.createElement('table');

    // Create the table header row with the counter column, details column, and ID column
    var thead = document.createElement('thead');
    var headerRow = document.createElement('tr');

    // Create the counter header cell
    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);

    // Create the Details header cell
    var detailsHeaderCell = document.createElement('th');
    detailsHeaderCell.textContent = 'Details';
    detailsHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
    headerRow.appendChild(detailsHeaderCell);

    // Create the ID header cell
    var idHeaderCell = document.createElement('th');
    idHeaderCell.textContent = 'ID';
    idHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
    headerRow.appendChild(idHeaderCell);

    // Get all unique keys from the jsonData
    var keys = Object.keys(jsonData[0]);

    // Create the table header cells for each key
    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);
    });

    // Add the header row to the thead
    thead.appendChild(headerRow);

    // Append the thead to the table
    tablepm.appendChild(thead);

    // Iterate over the jsonData to create table rows
    jsonData.forEach(function(entry, index) {
      var row = document.createElement('tr');
    
      // Create the counter cell for each row
      var counterCell = document.createElement('td');
      counterCell.textContent = index + 1;
      row.appendChild(counterCell);
    
      // Create the button cell for the "Generar Contrato" button in the second column
      var buttonCell = document.createElement('td');
      var detailsButton = document.createElement('button');
      detailsButton.textContent = 'Generar Contrato';
      detailsButton.classList.add("btn", "btn-warning");
    
      // Add an event listener to the "Generar Contrato" button
      detailsButton.addEventListener('click', function() {
        // Store the rowData in the session
        sessionStorage.setItem('rowData', JSON.stringify(entry));
        console.log("rowData stored in session:", entry);
        // Navigate to the details page
        window.location.href = '../docs/contrato_inv.html';
      });
    
      buttonCell.appendChild(detailsButton);
      row.appendChild(buttonCell);

      // Create the ID cell for each row
      var idCell = document.createElement('td');
      var idButton = document.createElement('button');
      idButton.textContent = 'Descargar reporte';
      idButton.classList.add("btn", "btn-info");
      idButton.addEventListener('click', function() {
        window.location.href = `https://www.jotform.com/server.php?action=getSubmissionPDF&sid=${entry.id}&formID=${formID3}`;
      });
      idCell.appendChild(idButton);
      row.appendChild(idCell);

      // Create the remaining cells for each key
      keys.forEach(function(key) {
        var cell = document.createElement('td');
        cell.textContent = entry[key];
        row.appendChild(cell);
      });

      // Add the row to the table
      tablepm.appendChild(row);
    });

    // Append the table to the table container
    tableContainer3.appendChild(tablepm);
    console.log(jsonData.length);
  })
  .catch(error => {
    // Handle any errors that occur during the request
    console.error(error);
  });
