document.addEventListener('DOMContentLoaded', function () {
    const userEmail = document.getElementById("user-email").getAttribute("data-email");
    const profileId = document.getElementById("profile_id").getAttribute("data-profile-id");

    const createButton = document.getElementById('create-object-btn'); // Iegūstam pogu jauna objekta izveidei
    const objectsContainer = document.getElementById('objects-container'); // Iegūstam konteineru esošajiem objektiem

    const popupDialog = document.getElementById('popup-dialog'); // Iegūstam uznirstošo dialogu
    const confirmBtn = document.getElementById('confirm-btn'); // Iegūstam apstiprināšanas pogu
    const cancelBtn = document.getElementById('cancel-btn'); // Iegūstam atcelšanas pogu
    const objectNameInput = document.getElementById('object-name-input'); // Iegūstam ievades lauku objekta nosaukumam

    // Funkcija esošo objektu iegūšanai
    function fetchExistingObjects() {
        fetch("../php/get_accounts.php", {
            method: "POST",
            body: new URLSearchParams({
                profile_id: profileId // Sūtām profila ID uz serveri
            })
        })
            .then(response => response.json())
            .then(data => {
                if (!data.error) {
                    data.forEach(accountName => addObjectToContainer(accountName)); // Pievienojam katru konta nosaukumu konteineram
                }
            })
            .catch(error => console.error("Error fetching accounts:", error)); // Kļūdas ziņojums, ja neizdodas iegūt kontus
    }

    // Funkcija, kas pievieno objektu konteineram
     function addObjectToContainer(accountName) {
        const objectBox = document.createElement('div');
        objectBox.classList.add('object-box');

        const textBox = document.createElement('div');
        textBox.textContent = accountName;
        textBox.classList.add('text-box');

        const deleteBtn = document.createElement('button');
        deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
        deleteBtn.classList.add('delete-btn');

        objectBox.appendChild(textBox);
        objectBox.appendChild(deleteBtn);
        objectsContainer.appendChild(objectBox);

        objectBox.style.cursor = 'pointer';
        objectBox.addEventListener('click', function () {
            // Store the values in sessionStorage
            sessionStorage.setItem('email', userEmail);
            sessionStorage.setItem('profile_id', profileId);
            sessionStorage.setItem('account_name', accountName);

            // Redirect to the next page without URL parameters
            window.location.href = "../html/history.html";
        });

        deleteBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            if (confirm("Are you sure you want to delete this account?")) {
                deleteAccount(accountName, profileId, objectBox);
            }
        });
    }
    
    // Funkcija, kas dzēš kontu
    function deleteAccount(accountName, profileId, objectBox) {
        fetch("../php/delete_account.php", {
            method: "POST",
            body: new URLSearchParams({
                account_name: accountName, // Send account name to server
                profile_id: profileId // Send profile ID to server
            })
        })
        .then(response => response.json()) // Parse the response as JSON
        .then(data => {
            if (data.success) {
                // Display the success message
                alert(data.success);
                objectsContainer.removeChild(objectBox); // Remove the object from the container
            } else if (data.error) {
                // Display the error message
                alert(data.error);
            }
        })
        .catch(error => console.error("Error deleting account:", error)); // Error message if account deletion fails
    }

    fetchExistingObjects(); // Iegūstam esošos objektus

    createButton.addEventListener('click', function () {
        popupDialog.style.display = 'flex'; // Parādām uznirstošo dialogu
    });

    cancelBtn.addEventListener('click', function () {
        popupDialog.style.display = 'none'; // Hide the popup dialog
        objectNameInput.value = ''; // Clear the input field
    });

    confirmBtn.addEventListener('click', function () {
        const accountName = objectNameInput.value; // Get account name from input field
        if (accountName) {
            // Send account name and profile ID to the server for validation and insertion
            fetch("../php/register_account.php", {
                method: "POST",
                body: new URLSearchParams({
                    account_name: accountName, // Send account name to server
                    profile_id: profileId // Send profile ID to server
                })
            })
            .then(response => response.text())
            .then(serverMessage => {
                if (serverMessage.includes("Account name already exists")) {
                    // Show alert if the account name is a duplicate
                    alert(serverMessage);
                } else if (serverMessage.includes("New subaccount created successfully")) {
                    // Only add the account to the list if it was successfully created
                    addObjectToContainer(accountName);
                    popupDialog.style.display = 'none'; // Hide dialog on success
                    objectNameInput.value = ''; // Clear the input field
                } else {
                    console.error("Unexpected server response:", serverMessage);
                }
            })
            .catch(error => console.error("Error creating account:", error)); // Error message if account creation fails
        } else {
            alert('Please enter a valid name!'); // Alert if no valid name is entered
        }
    });
    
});
