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

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

// Filter menu HTML
var filterMenu = `
<div id="filter-menu">
  <label for="numeric-column">Select Numeric Column:</label>
  <select id="numeric-column">
    <option value="">None</option>
  </select>
  <br>
  <label for="min-value">Minimum Value:</label>
  <input type="number" id="min-value" min="0">
  <br>
  <label for="max-value">Maximum Value:</label>
  <input type="number" id="max-value" min="0">
  <br>
  <button onclick="applyFilter()">Apply Filter</button>
</div>
`;

// Append filter menu to table container
tableContainer.insertAdjacentHTML('beforebegin', filterMenu);

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

      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;
      }, {});

      jsonData.push(newDictionary);
    });

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

    // Create the table header row with the counter 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);

    // 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);

    // Function to populate numeric columns in filter menu
    function populateNumericColumns() {
      var numericColumnSelect = document.getElementById('numeric-column');
      numericColumnSelect.innerHTML = '<option value="">None</option>';
      keys.forEach(function(key) {
        if (!isNaN(parseFloat(jsonData[0][key]))) {
          var option = document.createElement('option');
          option.text = key;
          option.value = key;
          numericColumnSelect.appendChild(option);
        }
      });
    }

    // Function to apply filter
    function applyFilter() {
      var numericColumn = document.getElementById('numeric-column').value;
      var minValue = parseFloat(document.getElementById('min-value').value);
      var maxValue = parseFloat(document.getElementById('max-value').value);

      var filteredData = jsonData.filter(function(entry) {
        if (numericColumn && (isNaN(parseFloat(entry[numericColumn])) || entry[numericColumn] < minValue || entry[numericColumn] > maxValue)) {
          return false;
        }
        return true;
      });

      // Clear existing table
      table.innerHTML = '';

      // Repopulate table with filtered data
      filteredData.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 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);
      });
    }

    // Populate numeric columns in filter menu
    populateNumericColumns();

    // 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);
  });
