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

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

// Fetch form submissions from JotForm API
fetch(`https://api.jotform.com/form/${formID}/submissions?apiKey=${apiKey}`)
  .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.answer, value.text]);
        }
      });

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

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

      jsonData.push(newDictionary);
    });

    // Create the table element
    var table = 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 = 'Contrato Maestro';
    detailsHeaderCell.classList.add("text-uppercase", "text-secondary", "text-xxs", "font-weight-bolder", "opacity-7");
    headerRow.appendChild(detailsHeaderCell);

    // Create the Details header cell
    var detailsHeaderCell = document.createElement('th');
    detailsHeaderCell.textContent = 'Anexo';
    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 = 'Reporte';
    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
    table.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 Anexo';
      detailsButton.classList.add("btn", "btn-primary");
    
      // 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/anexo_arrendamiento.html';
      });

     
      buttonCell.appendChild(detailsButton);
      row.appendChild(buttonCell);
      
      //Boton de descargar reporte
       // 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-warning");
      idButton.addEventListener('click', function() {
        window.location.href = `https://www.jotform.com/pdf-submission/${entry.id}`;
        //window.location.href = `https://www.jotform.com/server.php?action=getSubmissionPDF&sid=${entry.id}&formID=${formID3}`;


      });
      idCell.appendChild(idButton);
      row.appendChild(idCell);
      
      
      //Bot贸n de Perfil individual
      // Create the button cell for the "Generar Contrato" button in the second column
      var profbuttonCell = document.createElement('td');
      var profdetailsButton = document.createElement('button');
      profdetailsButton.textContent = 'Perfil';
      profdetailsButton.classList.add("btn", "btn-success");
    
      // Add an event listener to the "Generar Contrato" button
      profdetailsButton.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 = 'https://vilarkptl.com/dashboard/pages/profile_arrendamiento.html';
      });
    
      profbuttonCell.appendChild(profdetailsButton);
      row.appendChild(profbuttonCell);

      /*/ Create the button cell for the "Details" button in the second column
      var buttonCell = document.createElement('td');
      var detailsButton = document.createElement('button');
      detailsButton.textContent = 'Crear Contrato';
      detailsButton.classList.add("btn", "btn-primary");
      detailsButton.addEventListener('click', function() {
        var rowData = JSON.stringify(entry);
        window.location.href = 'contrato_maestropf.html'
        //?data=
        //+ encodeURIComponent(rowData);
      });
      buttonCell.appendChild(detailsButton);
      row.appendChild(buttonCell);*/

     

      // 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
      table.appendChild(row);
    });

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