document.addEventListener("DOMContentLoaded", () => {
  loadUsers();
  loadStats();

  document.getElementById("addUserForm")?.addEventListener("submit", saveUser);
});

function loadUsers() {
  fetch("user_actions.php?action=list")
    .then(res => res.json())
    .then(data => {
      const tbody = document.querySelector("#usersTable tbody");
      tbody.innerHTML = "";

      if (!data.success || data.users.length === 0) {
        tbody.innerHTML = `<tr><td colspan="6">No users found</td></tr>`;
        return;
      }

      data.users.forEach(user => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td>${user.firstName} ${user.lastName}</td>
          <td>${user.phone}</td>
          <td>${user.email}</td>
          <td>${user.is_admin == 1 ? "Admin" : "User"}</td>
          <td>${user.created_at}</td>
          <td>
            <button onclick="deleteUser(${user.id})">Delete</button>
          </td>
        `;
        tbody.appendChild(row);
      });
    });
}

function loadStats() {
  const formData = new FormData();
  formData.append("action", "get_stats");

  fetch("user_actions.php", { method: "POST", body: formData })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        document.getElementById("totalUsers").innerText = data.stats.total;
        document.getElementById("totalAdmins").innerText = data.stats.admins;
        document.getElementById("totalNormal").innerText = data.stats.users;
      }
    });
}

function saveUser(e) {
  e.preventDefault();
  const form = document.getElementById("addUserForm");
  const formData = new FormData(form);
  formData.append("action", "add_user");

  fetch("user_actions.php", { method: "POST", body: formData })
    .then(res => res.json())
    .then(data => {
      alert(data.message);
      if (data.success) {
        form.reset();
        loadUsers();
        loadStats();
      }
    });
}

function deleteUser(id) {
  if (!confirm("Delete this user?")) return;
  const formData = new FormData();
  formData.append("action", "delete_user");
  formData.append("user_id", id);

  fetch("user_actions.php", { method: "POST", body: formData })
    .then(res => res.json())
    .then(data => {
      alert(data.message);
      if (data.success) {
        loadUsers();
        loadStats();
      }
    });
}
