
window.addEventListener('load', fillInputFieldsWithData);
function saveCookiesData(name) {
    const urlInput = document.querySelector(`input[data-service="${name}"][placeholder="URL"]`);
    const cookiesInput = document.querySelector(`input[data-service="${name}"][placeholder="json"]`);
    const url = urlInput.value;
    const cookies = cookiesInput.value;

    const data = {
        web: name,
        url: url,
        cookies: cookies
    };
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "dist/php/custom.php", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = function() {
        if (xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            const successMessageId = name + "SuccessMessage";
            const successMessageElement = document.getElementById(successMessageId);
            if (successMessageElement) {
                successMessageElement.textContent = response.success || response.warning;
                successMessageElement.style.display = "block";
                setTimeout(function() {
                    successMessageElement.style.display = "none";
                }, 3000); // Hide after 3 seconds
            }     
        } else {
            console.error("Error saving cookies:", xhr.statusText);
        }
    };
    xhr.send(JSON.stringify(data));
}
function fillInputFieldsWithData() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "dist/php/custom.php", true); 
  xhr.onload = function() {
    if (xhr.status === 200) {
      const websites = JSON.parse(xhr.responseText);
      
      websites.forEach(websiteName => {
        // Fetch cookies and URL for the website
        fetch(`dist/php/custom.php?website=${websiteName}`)
          .then(response => response.json())
          .then(data => {
            if (data.error) {
              console.error(data.error); 
            } else {
              const urlInput = document.querySelector(`input[data-service="${websiteName}"][placeholder="URL"]`);
              const cookiesInput = document.querySelector(`input[data-service="${websiteName}"][placeholder="json"]`);

              if (urlInput && cookiesInput) {
                urlInput.value = data.url;
                cookiesInput.value = data.cookies;
              } else {
                console.error(`Input fields for ${websiteName} not found.`);
              }
            }
          })
          .catch(error => console.error("Error fetching cookies:", error));
      });
    } else {
      console.error("Error fetching websites:", xhr.statusText);
    }
  };
  xhr.send();
}
