const form = document.getElementById("addUserForm");
const msg = document.getElementById("msg");
const rank = document.getElementById("rank");
const customRank = document.getElementById("customRank");

rank.addEventListener("change", () => {
  customRank.hidden = rank.value !== "custom";
});

form.addEventListener("submit", async (e) => {
  e.preventDefault();

  const formData = new FormData(form);

  if (!/^\d{10}$/.test(formData.get("mobile"))) {
    msg.textContent = "Invalid mobile number";
    return;
  }

  if (!/^\d{4}$/.test(formData.get("pin"))) {
    msg.textContent = "PIN must be 4 digits";
    return;
  }

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

  const data = await res.json();
  msg.textContent = data.message;
  if(data.success){
    msg.style.backgroundColor = "#1a7e31ff"; 
    msg.style.color = "#ffffffff"; 
    msg.style.border = "1px solid #1f5a2dff";
    msg.style.padding = "15px";
    msg.style.borderRadius = "5px";
    msg.style.marginBottom = "20px";
    msg.style.textAlign = "center";
  } 
  else{
    msg.style.backgroundColor = "#f8d7da";
    msg.style.color = "#721c24";
    msg.style.border = "1px solid #f5c6cb";
    msg.style.padding = "15px";
    msg.style.borderRadius = "5px";
    msg.style.marginBottom = "20px";
    msg.style.textAlign = "center";
  }

  if (data.success) form.reset();
});

// const uplinerPreview = document.getElementById("uplinerPreview");
// const uplinerCheckboxes = document.querySelectorAll(
//   'input[name="upliner_id[]"]'
// );

// uplinerCheckboxes.forEach(cb => {
//   cb.addEventListener("change", updateUplinerPreview);
// });

// function updateUplinerPreview() {
//   uplinerPreview.innerHTML = "";

//   uplinerCheckboxes.forEach(cb => {
//     if (cb.checked) {
//       const imgSrc = cb.dataset.img;
//       if (imgSrc) {
//         const img = document.createElement("img");
//         img.src = imgSrc;
//         uplinerPreview.appendChild(img);
//       }
//     }
//   });
// }

