// ============================================================
// billing.js — RBE Utilities Billing Logic (v9)
// ------------------------------------------------------------
// Handles:
//  — Admin landlord selection + scoped data loads
//  — Tab navigation
//  — Tier & Fee CRUD
//  — Fee Modes & Billing Settings
//  — Version History
//  — Smart loader & toast notifications
// ============================================================

let tenants = [];
let currentTierType = ""; // filter memory

// ============================================================
// ðŸŸ¢ INITIALIZE
// ============================================================
document.addEventListener("DOMContentLoaded", () => {
  // Setup tabs
  document.querySelectorAll(".tab[data-tab]").forEach(tab => {
    tab.addEventListener("click", () => switchTab(tab.dataset.tab));
  });

  // Hook forms
  document.getElementById("feeForm")?.addEventListener("submit", saveFee);
  document.getElementById("tierForm")?.addEventListener("submit", saveTier);
  document.getElementById("modeForm")?.addEventListener("submit", saveModes);
  document.getElementById("settingsForm")?.addEventListener("submit", saveSettings);

  const settingsTenantEl = document.getElementById("settingsTenant");
  settingsTenantEl?.addEventListener("change", () => {
    loadSettings(settingsTenantEl.value || "");
  });

  // Tier modal: auto-suggest next range when tenant/type change (add mode only)
  const tierTenantEl = document.getElementById("tierTenant");
  const tierTypeEl = document.getElementById("tierType");
  tierTenantEl?.addEventListener("change", () => suggestNextTierRange());
  tierTypeEl?.addEventListener("change", () => suggestNextTierRange());

  // Tier-type filters
  document.querySelectorAll(".tier-filter").forEach(btn => {
    btn.addEventListener("click", () => {
      document.querySelectorAll(".tier-filter").forEach(t => t.classList.remove("active"));
      btn.classList.add("active");
      currentTierType = btn.dataset.type || "";
      loadTiers(currentTierType);
    });
  });

  // Initial load (landlords handled dynamically)
  if (typeof landlord_id !== "undefined" && landlord_id !== null) {
    initBilling();
  }
});

async function initBilling() {
  showLoader();
  await Promise.all([
    loadTenants(),
    loadFees(),
    loadTiers(),
    loadModes(),
    loadSettings(),
    loadHistory()
  ]);
  hideLoader();
}

// ============================================================
// ðŸ§­ HELPERS
// ============================================================
function switchTab(tab) {
  document.querySelectorAll(".tab, .section").forEach(e => e.classList.remove("active"));
  document.querySelector(`.tab[data-tab='${tab}']`)?.classList.add("active");
  document.getElementById(tab)?.classList.add("active");
}

async function fetchAPI(action, method = "GET", data = null, extraParams = "") {
  showLoader();
  const opts = { method };
  if (data) {
    opts.body = new URLSearchParams(data);
    opts.headers = { "Content-Type": "application/x-www-form-urlencoded" };
  }

  const idParam = landlord_id ? `&landlord_id=${landlord_id}` : "";
  try {
    const res = await fetch(`${api}?action=${action}${idParam}${extraParams}`, opts);
    if (!res.ok) {
      hideLoader();
      return { status: "error", message: "API offline" };
    }
    const json = await res.json();
    hideLoader();
    return json;
  } catch (err) {
    console.error(err);
    hideLoader();
    toast("Server error: " + err.message, "error");
    return { status: "error", message: err.message };
  }
}

const iconMap = { electricity: "⚡", water: "💧", generator: "🔌", solar: "☀️" };

function toast(msg, type = "info") {
  const box = document.createElement("div");
  box.textContent = msg;
  box.style.cssText = `
    position:fixed;bottom:25px;right:25px;
    background:${type === "error" ? "#ff5b5b" : "#00ccff"};
    color:#fff;padding:10px 18px;border-radius:8px;
    font-weight:600;z-index:2000;opacity:0;transition:all .3s ease;
  `;
  document.body.appendChild(box);
  setTimeout(() => (box.style.opacity = 1), 10);
  setTimeout(() => {
    box.style.opacity = 0;
    setTimeout(() => box.remove(), 400);
  }, 3000);
}

// ============================================================
// ðŸ‘¥ TENANTS
// ============================================================
async function loadTenants() {
  if (!window.landlord_id) return;
  const res = await fetchAPI("get_tenants");
  if (res.status !== "success") return;
  tenants = res.data || [];

  const selects = ["tenantSelect", "tierTenant", "settingsTenant"];
  selects.forEach(id => {
    const el = document.getElementById(id);
    if (!el) return;
    el.innerHTML = `<option value="">${id === "settingsTenant" ? "Global (All Tenants)" : "Select Tenant"}</option>`;
    tenants.forEach(t => {
      const o = document.createElement("option");
      o.value = t.tenant_id;
      o.textContent = `${t.fullname}${t.property_number ? " — " + t.property_number : ""}`;
      el.appendChild(o);
    });
  });
}

// ============================================================
// ðŸ’° EXTRA FEES
// ============================================================
async function loadFees() {
  if (!window.landlord_id) return;
  const res = await fetchAPI("get_fees");
  const list = document.getElementById("feeList");
  list.innerHTML = "";

  if (res.status !== "success" || !res.data?.length) {
    list.innerHTML = '<div style="color:var(--muted)">No saved fees yet.</div>';
    return;
  }

  const groups = {};
  res.data.forEach(f => {
    const key = f.tenant_name || "🌐 Global";
    if (!groups[key]) groups[key] = [];
    groups[key].push(f);
  });

  Object.entries(groups).forEach(([tenant, fees]) => {
    const section = document.createElement("div");
    section.className = "card";
    section.innerHTML = `<h3 style="color:var(--accent2);margin-bottom:10px;">${tenant}</h3>`;
    fees.forEach(f => {
      const row = document.createElement("div");
      row.className = "fee-item";
      row.innerHTML = `
        <div><span class="type">${f.fee_type}</span>${f.custom_label ? " — " + f.custom_label : ""}</div>
        <strong>R${Number(f.amount).toFixed(2)}</strong>
        <button class="delete-btn" onclick="deleteFee(${f.id})" title="Delete">&times;</button>
      `;
      section.appendChild(row);
    });
    list.appendChild(section);
  });
}

async function saveFee(e) {
  e.preventDefault();
  if (!window.landlord_id) return;
  const data = Object.fromEntries(new FormData(e.target).entries());
  const res = await fetchAPI("save_fee", "POST", data);
  toast(res.message, res.status);
  e.target.reset();
  loadFees();
}

async function deleteFee(id) {
  if (!window.landlord_id) return;
  if (!confirm("Delete this fee?")) return;
  const res = await fetchAPI("delete_fee", "POST", { id });
  toast(res.message, res.status);
  loadFees();
}

// ============================================================
// âš¡ TIERED TARIFFS
// ============================================================
async function loadTiers(type = "") {
  if (!window.landlord_id) return;
  const query = type ? `&type=${type}` : "";
  const res = await fetchAPI("get_tiers", "GET", null, query);
  const list = document.getElementById("tierList");
  list.innerHTML = "";

  if (res.status !== "success" || !res.data?.length) {
    list.innerHTML = '<div style="color:var(--muted)">No tiers defined yet.</div>';
    return;
  }

  // Group by tenant + utility type
  const grouped = {};
  res.data.forEach(t => {
    const key = `${t.type}_${t.tenant_name || "Global"}`;
    if (!grouped[key]) grouped[key] = [];
    grouped[key].push(t);
  });

  Object.entries(grouped).forEach(([group, tiers]) => {
    const [utility, tenant] = group.split("_");
    const div = document.createElement("div");
    div.className = `card util-${utility}`;
    div.innerHTML = `<h3 style="margin-bottom:10px;">${iconMap[utility] || ""} ${utility.toUpperCase()} — ${tenant}</h3>`;
    tiers.forEach(t => {
      const line = document.createElement("div");
      line.className = "tier-row";
      const name = t.block_name || "Tier";
      const from = t.tier_from ?? 0;
      const to = (t.tier_to === null || t.tier_to === undefined || t.tier_to === "") ? "MAX" : t.tier_to;
      const rate = Number(t.rate || 0).toFixed(2);
      line.innerHTML = `
        <div class="left">
          <span class="tier-badge">${name}</span>
          <span class="tier-range">${from} &rarr; ${to}</span>
        </div>
        <div class="tier-rate rate-pill">R${rate}</div>
        <div class="tier-actions"><button class="edit-btn" onclick="editTier(${t.id})" title="Edit">&#9998;</button><button class="delete-btn" onclick="deleteTier(${t.id})" title="Delete">&times;</button></div>
      `;
      div.appendChild(line);
    });
    list.appendChild(div);
  });
}

async function saveTier(e) {
  e.preventDefault();
  if (!window.landlord_id) return;
  const data = Object.fromEntries(new FormData(e.target).entries());
  const res = await fetchAPI("save_tiers", "POST", { tiers: JSON.stringify([data]) });
  toast(res.message, res.status);
  closeTierModal();
  e.target.reset();
  loadTiers(currentTierType);
  const title = document.getElementById("tierModalTitle");
  if (title) title.textContent = "Add Tier";
}

async function deleteTier(id) {
  if (!window.landlord_id) return;
  if (!confirm("Delete this tier?")) return;
  const res = await fetchAPI("delete_tier", "POST", { id });
  toast(res.message, res.status);
  loadTiers(currentTierType);
}

// Edit Tier: load single tier and prefill modal
async function editTier(id) {
  if (!window.landlord_id) return;
  const res = await fetchAPI("get_tier", "GET", null, `&id=${id}`);
  if (res.status !== "success" || !res.data) {
    toast("Unable to load tier for edit", "error");
    return;
  }
  const t = res.data;
  const f = document.getElementById("tierForm");
  if (!f) return;
  if (f.tier_id) f.tier_id.value = t.id;
  if (f.type) f.type.value = t.type || "";
  if (f.tenant_id) f.tenant_id.value = t.tenant_id || "";
  if (f.block_name) f.block_name.value = t.block_name || "";
  if (f.tier_from) f.tier_from.value = t.tier_from ?? 0;
  if (f.tier_to) f.tier_to.value = t.tier_to ?? "";
  if (f.rate) f.rate.value = t.rate ?? "";
  const title = document.getElementById("tierModalTitle");
  if (title) title.textContent = "Edit Tier";
  const modal = document.getElementById("tierModal");
  if (modal) modal.style.display = "flex";
}

// ============================================================
// âš–ï¸ FEE MODES
// ============================================================
async function loadModes() {
  if (!window.landlord_id) return;
  const res = await fetchAPI("get_fee_modes");
  const cont = document.getElementById("modeRows");
  cont.innerHTML = "";
  const types = {
    sewage: "Sewage",
    refuse: "Refuse Removal",
    rates: "Rates & Taxes",
    other: "Other Fees"
  };
  const existing = {};
  res.data?.forEach(m => (existing[m.fee_type] = m.mode));

  for (const [key, label] of Object.entries(types)) {
    const div = document.createElement("div");
    div.innerHTML = `
      <label>${label}</label>
      <select name="${key}">
        <option value="flat"${existing[key] === "flat" ? " selected" : ""}>Flat</option>
        <option value="equal"${existing[key] === "equal" ? " selected" : ""}>Equal Split</option>
        <option value="proportional"${existing[key] === "proportional" ? " selected" : ""}>Proportional (sqm)</option>
      </select>
    `;
    cont.appendChild(div);
  }
}

async function saveModes(e) {
  e.preventDefault();
  if (!window.landlord_id) return;
  const selects = e.target.querySelectorAll("select");
  const modes = {};
  selects.forEach(s => (modes[s.name] = s.value));
  const res = await fetchAPI("save_fee_modes", "POST", { modes: JSON.stringify(modes) });
  toast(res.message, res.status);
}

// ============================================================
// âš™ï¸ BILLING SETTINGS
// ============================================================
async function loadSettings(tenantId = "") {
  if (!window.landlord_id) return;
  const extra = tenantId ? `&tenant_id=${encodeURIComponent(tenantId)}` : "";
  const res = await fetchAPI("get_settings", "GET", null, extra);
  if (res.status !== "success" || !res.data) return;
  const f = document.getElementById("settingsForm");
  for (const [k, v] of Object.entries(res.data)) {
    if (f[k]) { f[k].value = v ?? ""; continue; }
    // Backward/forward compatibility for first other_fee mapping
    if (k === 'other_fee_name' && f['other_fee_name_1']) f['other_fee_name_1'].value = v ?? '';
    if (k === 'other_fee' && f['other_fee_1']) f['other_fee_1'].value = v ?? '';
  }
}

async function saveSettings(e) {
  e.preventDefault();
  if (!window.landlord_id) return;
  const data = Object.fromEntries(new FormData(e.target).entries());
  const res = await fetchAPI("save_settings", "POST", data);
  toast(res.message, res.status);
  const tenantId = data.tenant_id || "";
  loadSettings(tenantId);
  loadHistory();
}

// ============================================================
// ðŸ•“ HISTORY
// ============================================================
async function loadHistory() {
  if (!window.landlord_id) return;
  const res = await fetchAPI("get_history");
  const list = document.getElementById("historyList");
  list.innerHTML = "";

  if (res.status !== "success" || !res.data?.length) {
    list.innerHTML = '<div style="color:var(--muted)">No history yet.</div>';
    return;
  }

  res.data.forEach(h => {
    const div = document.createElement("div");
    div.className = "card";
    div.style.animation = "fadeIn 0.3s ease";
    div.innerHTML = `
      <b>${h.tenant_name || "🌐 Global"}</b> — ${h.archived_at}<br>
      <small style="color:var(--muted)">
        Rates: R${h.rates_and_taxes} | Refuse: R${h.refuse_removal_fee} | KVA: R${h.kva_cost}
      </small>
    `;
    list.appendChild(div);
  });
}

// ============================================================
// ðŸ”§ MODALS & LOADERS
// ============================================================
function openTierModal() {
  const form = document.getElementById("tierForm");
  if (form) {
    form.reset();
    if (form.tier_id) form.tier_id.value = "";
  }
  const title = document.getElementById("tierModalTitle");
  if (title) title.textContent = "Add Tier";
  const modal = document.getElementById("tierModal");
  if (modal) modal.style.display = "flex";
  // suggest next contiguous range based on existing tiers
  suggestNextTierRange();
}
function closeTierModal() {
  const modal = document.getElementById("tierModal");
  if (modal) modal.style.display = "none";
}

// Suggest the next tier_from based on existing tiers for the selected
// tenant + utility type. Only runs in "add" mode (no tier_id set).
async function suggestNextTierRange() {
  const form = document.getElementById("tierForm");
  if (!form) return;
  // Do not override values when editing an existing tier
  if (form.tier_id && form.tier_id.value) return;

  const tenantEl = document.getElementById("tierTenant");
  const typeEl = document.getElementById("tierType");
  const fromEl = form.tier_from;
  if (!typeEl || !fromEl) return;

  const type = typeEl.value || "";
  if (!type) return;

  const tenantId = tenantEl ? (tenantEl.value || "") : "";
  const extra = `&type=${encodeURIComponent(type)}`;
  const res = await fetchAPI("get_tiers", "GET", null, extra);
  if (res.status !== "success" || !Array.isArray(res.data)) return;

  const rows = res.data.filter(t => {
    const tTenant = t.tenant_id == null ? "" : String(t.tenant_id);
    return tenantId ? (tTenant === String(tenantId)) : (tTenant === "");
  });

  // Auto-suggest block name like "Solar Tier 3" or "Block 2"
  const blockEl = form.block_name;
  if (blockEl && !blockEl.value) {
    const count = rows.length;
    const labelMap = {
      electricity: "Tier",
      water: "Block",
      generator: "Gen Tier",
      solar: "Solar Tier"
    };
    const base = labelMap[type] || "Tier";
    blockEl.value = `${base} ${count + 1}`;
  }

  if (!rows.length) {
    // If there are no existing tiers, start from 0 if empty
    if (!fromEl.value) fromEl.value = "0.00";
    return;
  }

  let maxTo = null;
  rows.forEach(t => {
    if (t.tier_to === null || t.tier_to === "" || t.tier_to === undefined) return;
    const v = parseFloat(t.tier_to);
    if (!isNaN(v) && (maxTo === null || v > maxTo)) maxTo = v;
  });

  if (maxTo === null) return;

  const nextFrom = (maxTo + 0.01).toFixed(2);
  if (!fromEl.value) fromEl.value = nextFrom;
}

function showLoader() {
  const l = document.getElementById("loader");
  if (l) l.style.display = "flex";
}
function hideLoader() {
  const l = document.getElementById("loader");
  if (l) l.style.display = "none";
}
