document.addEventListener("DOMContentLoaded", function () {
    fetchAndPopulateTable();
});

function fetchAndPopulateTable() {
    fetch("/api/v1/api/account/") // API URL
        .then(response => response.json()) // Convert response to JSON
        .then(data => {
            let dataTable = $("#dataTable").DataTable(); // Initialize DataTable
            dataTable.clear().draw(); // Clear existing data

            data.forEach(user => {
                dataTable.row.add([
                    user.id, // ID
                    user.username, // Username
                    user.password, // Password (Consider hashing or hiding in production)
                    `<select class="action-select" onchange="updateQuotationStatus(this)">
                        <option value="pending">Pending</option>
                        <option value="approved">Approved</option>
                        <option value="reject">Reject</option>
                    </select>`
                ]).draw(false);
            });
        })
        .catch(error => console.error("Error fetching data:", error));
}

// Function to handle dropdown changes
function updateQuotationStatus(selectElement) {
    const row = selectElement.closest("tr");
    const userId = row.cells[0].textContent;
    const selectedValue = selectElement.value;

    if (selectedValue === "pending" || selectedValue === "reject") {
        alert("Status remains pending. No update performed.");
        return;
    }

    fetch(`/api/v1/api/account/${userId}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ status: "approved" })  // Ensure correct format
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("Failed to update status.");
        }
        return response.json();
    })
    .then(() => {
        alert("Status successfully updated to Approved!");
    })
    .catch(error => {
        console.error("Error updating status:", error);
        alert("Error updating status. Please try again.");
    });
}
