/**
 * Authentication module
 * Handles user login and registration forms
 * Created by: Edijs Dunavskis
 */

// Handle login form submission and redirect user to home page
document.getElementById("loginForm")?.addEventListener("submit", async (e) => {
  e.preventDefault();
  
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;
  
  try {
    // Send login request to server
    const response = await fetch("http://localhost:3001/api/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ email, password })
    });
    
    const data = await response.json();
    
    if (data.success) {
      // Save user data to browser storage for session
      localStorage.setItem("user", JSON.stringify(data.user));
      localStorage.setItem("isLoggedIn", "true");
      
      // After successful login, redirect user to home page
      window.location.href = "index.html";
    } else {
      alert(data.message);
    }
  } catch (error) {
    // If incorrect data is entered, show error message in browser
    console.error("Login error:", error);
    alert("Failed to login. Please try again.");
  }
});

// Handle user registration form submission
document.getElementById("registerForm")?.addEventListener("submit", async (e) => {
  e.preventDefault();
  
  const firstName = document.getElementById("firstName").value;
  const lastName = document.getElementById("lastName").value;
  const email = document.getElementById("regEmail").value;
  const password = document.getElementById("regPassword").value;
  const confirmPassword = document.getElementById("confirmPassword").value;
  const farmId = document.getElementById("farmId").value;
  const userRole = parseInt(document.getElementById("userRole").value);
  
  // Check if both entered passwords match
  if (password !== confirmPassword) {
    alert("Passwords do not match!");
    return;
  }
  
  try {
    // Send registration request to server
    const response = await fetch("http://localhost:3001/api/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        firstName,
        lastName,
        email,
        password,
        farmId,
        status: userRole
      })
    });
    
    const data = await response.json();
    
    if (data.success) {
      alert(data.message);
      // After successful registration, redirect user to login page
      window.location.href = "login_lapa.html";
    } else {
      alert(data.message);
    }
  } catch (error) {
    console.error("Registration error:", error);
    alert("Failed to register. Please try again.");
  }
});

/**
 * Load all registered farms
 * Insert them into dropdown menu
 */
async function loadFarms() {
  try {
    const response = await fetch("http://localhost:3001/api/farms");
    const farms = await response.json();
    
    const farmSelect = document.getElementById("farmId");
    if (farmSelect) {
      farmSelect.innerHTML = '<option value="">Select a farm...</option>';
      farms.forEach(farm => {
        const option = document.createElement("option");
        option.value = farm.id;
        option.textContent = farm.name;
        farmSelect.appendChild(option);
      });
    }
  } catch (error) {
    console.error("Failed to load farms:", error);
  }
}

// Load farms so user can select desired farm during registration
document.addEventListener("DOMContentLoaded", () => {
  loadFarms();
});
