// =========================================================
// FILE: organisation-settings.js
// =========================================================

import { db } from "./firebase-config.js";
import { requireAuth, setupLogoutButton } from "./app-guard.js";
import { showLoader, hideLoader } from "./loader.js";
import { showToast } from "./toast.js";

import {
  doc,
  getDoc,
  updateDoc,
  serverTimestamp
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const organisationSettingsForm = document.getElementById("organisationSettingsForm");

const organisationName = document.getElementById("organisationName");
const organisationType = document.getElementById("organisationType");
const organisationSport = document.getElementById("organisationSport");
const organisationEmail = document.getElementById("organisationEmail");
const organisationPhone = document.getElementById("organisationPhone");
const organisationLocation = document.getElementById("organisationLocation");
const organisationAddress = document.getElementById("organisationAddress");

const submitButton =
  organisationSettingsForm?.querySelector("button[type='submit']");

let activeProfile = null;
let currentOrganisation = null;

function setLoading(isLoading) {
  if (!submitButton) return;

  submitButton.disabled = isLoading;

  submitButton.textContent = isLoading
    ? "Saving..."
    : "Save Organisation";
}

async function loadOrganisation() {
  if (!activeProfile?.organisationId) {
    throw new Error("No organisation linked to this user.");
  }

  const organisationRef = doc(
    db,
    "organisations",
    activeProfile.organisationId
  );

  const organisationSnap = await getDoc(organisationRef);

  if (!organisationSnap.exists()) {
    throw new Error("Organisation not found.");
  }

  currentOrganisation = {
    id: organisationSnap.id,
    ...organisationSnap.data()
  };

  organisationName.value =
    currentOrganisation.name || "";

  organisationType.value =
    currentOrganisation.type || "school";

  organisationSport.value =
    currentOrganisation.primarySport || "";

  organisationEmail.value =
    currentOrganisation.contactEmail || "";

  organisationPhone.value =
    currentOrganisation.contactPhone || "";

  organisationLocation.value =
    currentOrganisation.location || "";

  organisationAddress.value =
    currentOrganisation.address || "";
}

organisationSettingsForm?.addEventListener(
  "submit",
  async function (event) {
    event.preventDefault();

    if (!currentOrganisation) return;

    const updates = {
      name: organisationName.value.trim(),
      type: organisationType.value,
      primarySport: organisationSport.value.trim(),
      contactEmail: organisationEmail.value.trim(),
      contactPhone: organisationPhone.value.trim(),
      location: organisationLocation.value.trim(),
      address: organisationAddress.value.trim(),
      updatedAt: serverTimestamp()
    };

    if (!updates.name) {
      showToast(
        "Organisation name is required.",
        "warning"
      );

      return;
    }

    setLoading(true);
    showLoader("Saving organisation settings...");

    try {
      await updateDoc(
        doc(db, "organisations", currentOrganisation.id),
        updates
      );

      showToast(
        "Organisation updated successfully.",
        "success"
      );
    } catch (error) {
      console.error(
        "Organisation settings error:",
        error
      );

      showToast(
        "Could not update organisation: " + error.message,
        "error"
      );
    } finally {
      setLoading(false);
      hideLoader();
    }
  }
);

requireAuth(async function (user, profile) {
  activeProfile = profile;

  setupLogoutButton();

  if (profile.role !== "director") {
    window.location.href = "dashboard.html";
    return;
  }

  showLoader("Loading organisation settings...");

  try {
    await loadOrganisation();
  } catch (error) {
    console.error(
      "Organisation load error:",
      error
    );

    showToast(
      "Could not load organisation settings: " +
        error.message,
      "error"
    );
  } finally {
    hideLoader();
  }
});