<!DOCTYPE html>
<html>
<head>
  <title>Edit User</title>
  <link rel="stylesheet" href="assets/css/admin.css">
</head>
<body>

<div class="sidebar">
  <h3>Admin</h3>
  <a href="users.php">Users</a>
</div>

<div class="main">
  <h2>Edit User</h2>

  <form id="editForm">
    <input type="hidden" name="id" id="id">

    <input name="name" id="name" placeholder="Name" required>
    <input name="email" id="email" type="email" placeholder="Email" required>
    <input name="city" id="city" placeholder="City">
    <input name="state" id="state" placeholder="State">
    <input name="mobile" id="mobile" required>

    <select name="gender" id="gender">
      <option>Male</option>
      <option>Female</option>
      <option>Other</option>
    </select>

    <input name="rank" id="rank" placeholder="Rank">
    <input name="company" id="company" placeholder="Company">

    <button>Update User</button>
    <p id="msg"></p>
  </form>
</div>

<script>
const id = new URLSearchParams(window.location.search).get("id");
const msg = document.getElementById("msg");

async function loadUser() {
  const res = await fetch(`api/get_user.php?id=${id}`);
  const u = await res.json();

  Object.keys(u).forEach(k => {
    if (document.getElementById(k)) {
      document.getElementById(k).value = u[k];
    }
  });
}

document.getElementById("editForm").addEventListener("submit", async e => {
  e.preventDefault();
  const formData = new FormData(e.target);

  const res = await fetch("api/update_user.php", {
    method: "POST",
    body: formData
  });

  const data = await res.json();
  msg.textContent = data.message;
  msg.style.color = data.success ? "green" : "red";
});

loadUser();
</script>
</body>
</html>
