console.log("USERS JS STARTED");

/* ================= GLOBAL ================= */

let page = 1;
const limit = 25;
let total = 0;
let selectedUser = null;

/* ================= INIT ================= */

window.onload = async function () {

    console.log("WINDOW LOADED");

    const rows = document.getElementById("rows");

    if (!rows) {
        console.error("ROWS NOT FOUND");
        return;
    }

    await loadUsers();

    document.getElementById("applyBtn").onclick = () => {
        page = 1;
        loadUsers();
    };

    document.getElementById("prevBtn").onclick = () => {
        if (page > 1) {
            page--;
            loadUsers();
        }
    };

    document.getElementById("nextBtn").onclick = () => {
        page++;
        loadUsers();
    };
};

/* ================= LOAD USERS ================= */

async function loadUsers() {

    console.log("LOADING USERS");

    const params = new URLSearchParams({
        page,
        limit
    });

    try {

        const res = await fetch(`/users/list.php?${params}`, {
            credentials: "same-origin"
        });

        const text = await res.text();

        console.log("RAW RESPONSE:", text);

        const data = JSON.parse(text);

        if (data.status !== "success") {
            alert(data.message || "Failed");
            return;
        }

        renderUsers(data.data.users);

    } catch (e) {
        console.error("ERROR:", e);
    }
}

/* ================= RENDER ================= */

function renderUsers(users) {

    const rows = document.getElementById("rows");

    rows.innerHTML = "";

    if (!users.length) {
        rows.innerHTML = "<tr><td colspan='6'>No users</td></tr>";
        return;
    }

    users.forEach(u => {

        const tr = document.createElement("tr");

        tr.style.cursor = "pointer";

        tr.onclick = () => openProfile(u);

        tr.innerHTML = `
            <td>${u.email}</td>
            <td>${u.company_name || "-"}</td>
            <td>${u.rsp_name || "-"}</td>
            <td>${u.role_key}</td>
            <td>${u.status}</td>
            <td>${u.email_verified ? "Yes" : "No"}</td>
        `;

        rows.appendChild(tr);
    });
}

/* ================= PROFILE ================= */

function openProfile(u) {

    selectedUser = u;

    document.getElementById("pEmail").innerText = u.email;
    document.getElementById("pFirst").value = u.first_name || "";
    document.getElementById("pLast").value = u.last_name || "";
    document.getElementById("pStatus").value = u.status;
    document.getElementById("pVerified").checked = u.email_verified == 1;
    document.getElementById("pRole").value = u.role_key || "user";

    document.getElementById("profileModal").style.display = "flex";
}

/* ================= SAVE ================= */

async function saveAdmin() {

    console.log("SAVING USER");

    const res = await fetch("/users/admin_update.php", {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            user_id: selectedUser.id,
            role_key: document.getElementById("pRole").value
        })
    });

    const data = await res.json();

    if (data.status !== "success") {
        alert(data.message);
        return;
    }

    closeProfile();
    loadUsers();
}

/* ================= CLOSE ================= */

function closeProfile() {
    document.getElementById("profileModal").style.display = "none";
}