/* =============================================================
   File: assets/js/register.js   —  used by register.html only
   ============================================================= */

document.addEventListener("DOMContentLoaded", function(){

  var user = requireLogin();
  if(!user) return;

  $("#logoutBtn").addEventListener("click", logout);

  /* ---------- state / city dropdowns ---------- */
  var stateEl = $("#arch_state");
  var cityEl  = $("#arch_city");
  populateStates(stateEl);
  stateEl.addEventListener("change", function(){ populateCities(stateEl, cityEl); });

  /* ---------- numeric-only inputs ---------- */
  digitsOnly($("#arch_mobile"));
  digitsOnly($("#arch_pin"));

  /* ---------- submit ---------- */
  $("#regForm").addEventListener("submit", function(e){
    e.preventDefault();

    var name    = $("#arch_name").value.trim();
    var mobile  = $("#arch_mobile").value.trim();
    var email   = $("#arch_email").value.trim();
    var pin     = $("#arch_pin").value.trim();
    var address = $("#arch_address").value.trim();

    var ok = true;
    ok = Validate.mark("f-name",    Validate.filled(name))   && ok;
    ok = Validate.mark("f-mobile",  Validate.mobile(mobile)) && ok;
    ok = Validate.mark("f-email",   Validate.email(email))   && ok;
    ok = Validate.mark("f-pin",     Validate.pin(pin))       && ok;
    ok = Validate.mark("f-address", Validate.filled(address))&& ok;

    if(!ok){
      toast("Please fix the highlighted fields");
      var firstBad = document.querySelector(".field.invalid");
      if(firstBad) firstBad.scrollIntoView({ behavior:"smooth", block:"center" });
      return;
    }

    /* ---------------------------------------------------------
       DEVELOPER (PHP): send this form to register_architect.php.
       The server should generate the login ID and temporary
       password and return them in the response.

       fetch("register_architect.php", { method:"POST", body:new FormData(this) })
         .then(r => r.json())
         .then(res => { ... redirect to credentials.php?id=res.id ... });
    --------------------------------------------------------- */
    var architect = {
      name:    name,
      mobile:  mobile,
      email:   email,
      state:   stateEl.value,
      city:    cityEl.value || "—",
      pin:     pin,
      address: address,
      loginId: mobile,
      pass:    generatePassword(),
      status:  "invited",
      date:    new Date().toLocaleDateString("en-IN")
    };

    Store.addArchitect(architect);   // new record goes to index 0
    Store.setLastInvite(0);
    window.location.href = "credentials.html";
  });

});
