document.addEventListener("DOMContentLoaded", function() {
    const formID = '240286932205858';
    const apiKey = '6e2676fa4067aecefdfae6fca7c4bb41';
    const knownSubmissionID = localStorage.getItem("id_form");
    console.log("known submission:", knownSubmissionID);
    const knownRFC = localStorage.getItem("rfc");
    console.log("known rfc:", knownRFC);
    const apiUrl = "https://api.jotform.com/submission/";
    const redirectUrl = "https://vilarkptl.com/dashboard/pages/publicprofilecredit.html";
    
    // Function to handle button click
    function handleClick(submissionID) {
        fetch(apiUrl + submissionID + "?apiKey=" + apiKey)
            .then(response => response.json())
            .then(data => {
            
        
            // Extract answers from data
            var submissions = data.content;
            var jsonData = {}; // Initialize as an empty object
            
            var response = data.content.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;
            }, {});
            
            // Assign the newDictionary object to jsonData
            jsonData = newDictionary;
            sessionStorage.setItem('rowData', JSON.stringify(jsonData));
            localStorage.setItem('rowData', JSON.stringify(jsonData));
    
            window.location.href = "https://vilarkptl.com/dashboard/pages/profile.html";
        });
    }
    // Fetch data from the API
    fetch(`https://api.jotform.com/form/${formID}/submissions?apiKey=${apiKey}`)
        .then(response => response.json())
        .then(data => {
            
            // Extract submission IDs
            const submissionIDs = data.content
                .filter(entry => {
                    
                    const answers = entry.answers;
    
                    // Loop through answers to find RFC field
                    for (const key in answers) {
                        if (answers[key].name === "rfc" && answers[key].answer === knownRFC) {
                            return entry.id !== knownSubmissionID;;
                        }
                    }
                    
                    return false; // RFC field not found or RFC doesn't match the known RFC
                })
                .map(entry => entry.id);
    
            console.log("Submission IDs filled by the person with RFC", knownRFC + ":", submissionIDs);
    
            // Create buttons dynamically
            const buttonsContainer = document.getElementById("buttons-container");

        if (submissionIDs.length === 0) {
            // No other projects found
            const message = document.createElement("div");
            message.textContent = "No se encontraron otros proyectos asociados a ID:" + knownRFC;
            buttonsContainer.appendChild(message);
        } else {
            // Display buttons in different lines
            submissionIDs.forEach(submissionID => {
                const button = document.createElement("button");
                button.className = "btn bg-gradient-primary";
                button.textContent = "Proyecto " + submissionID;
                button.addEventListener("click", () => handleClick(submissionID));
                
                // Add a line break after each button
                buttonsContainer.appendChild(button);
                buttonsContainer.appendChild(document.createElement("br"));
            });
        }


        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
});