// daygig-expenses.js — Expense / spending list and form

// ── Profile helpers ───────────────────────────────────────────────────────
function dgExpensesSettings() {
  return (window.DAYGIG_SETTINGS && typeof window.DAYGIG_SETTINGS === 'object')
    ? window.DAYGIG_SETTINGS
    : (typeof settings === 'object' ? settings : {});
}

function dgExpensesIsPersonal() {
  const s = dgExpensesSettings();
  return String(s.user_profile || s.profile || '').toLowerCase() === 'personal';
}

function dgExpenseLabel(accountName) {
  const name = String(accountName || '').trim();
  if (!name) return 'Uncategorized';
  if (dgExpensesIsPersonal()) {
    return name
      .replace(/^Expenses:/, '')
      .replace(/^COGS:/, '')
      .replace(/^Income:/, '')
      .replace(/^Assets:/, '')
      .replace(/:/g, ' › ')
      .trim() || 'Uncategorized';
  }
  return name.replace('Expenses:', '').replace('COGS:', 'COGS: ').trim();
}

function dgExpenseMoney(cents, fallbackAmount) {
  const n = Number(cents);
  if (!Number.isNaN(n)) return dgMoneyC(Math.abs(n));
  const raw = String(fallbackAmount || '0').replace(/[^0-9.-]/g, '');
  const parsed = Number(raw || 0);
  return dgMoney(Math.abs(parsed));
}

function dgExpenseSetText(id, text) {
  const el = document.getElementById(id);
  if (el) el.textContent = text;
}

function dgExpenseApplyProfileCopy() {
  const personal = dgExpensesIsPersonal();

  document.querySelectorAll('.card-title').forEach(el => {
    if (personal && el.textContent.trim() === 'Log an Expense') el.textContent = 'Log Spending';
    if (!personal && el.textContent.trim() === 'Log Spending') el.textContent = 'Log an Expense';
    if (personal && el.textContent.trim() === 'Recent Expenses') el.textContent = 'Recent Spending';
    if (!personal && el.textContent.trim() === 'Recent Spending') el.textContent = 'Recent Expenses';
  });

  document.querySelectorAll('.card-sub').forEach(el => {
    const txt = el.textContent.trim();
    if (personal && txt.startsWith('Direct business spending')) {
      el.textContent = 'Manual spending entry — useful for cash purchases, missing bank imports, or quick category tracking.';
    }
  });
}

// ── Expenses / spending ───────────────────────────────────────────────────
async function loadExpenseAccounts() {
  try {
    const res  = await fetch('/api/accounts');
    const data = await res.json();
    const sel  = document.getElementById('exp-account');
    if (!sel) return;

    const current = sel.value;
    const personal = dgExpensesIsPersonal();
    const accounts = (data.accounts || []).filter(a => {
      if (personal) return a.account_type === 'expense';
      return a.account_type === 'expense' || a.account_type === 'cogs';
    });

    sel.innerHTML = `<option value="">— select ${personal ? 'category' : 'account'} —</option>`;
    accounts.forEach(a => {
      const opt = document.createElement('option');
      opt.value = a.id;
      opt.textContent = dgExpenseLabel(a.name);
      sel.appendChild(opt);
    });
    if (current) sel.value = current;
  } catch (e) {
    console.warn('Could not load expense accounts:', e);
  }
  loadExpenseProperties();
}

// Landlord mode: fill the optional property selector on the expense form so an
// expense can be tagged to a property at entry (otherwise it lands in the
// Property P&L "unassigned" bucket until assigned).
async function loadExpenseProperties() {
  const sel = document.getElementById('exp-property');
  if (!sel) return;
  const profile = String((dgExpensesSettings().user_profile || 'business')).toLowerCase();
  if (profile !== 'landlord') return;
  try {
    const res = await fetch('/api/properties');
    if (!res.ok) return;
    const props = await res.json();
    const current = sel.value;
    sel.innerHTML = '<option value="">— unassigned —</option>';
    (Array.isArray(props) ? props : []).forEach(p => {
      const opt = document.createElement('option');
      opt.value = p.id;
      opt.textContent = p.name;
      sel.appendChild(opt);
    });
    if (current) sel.value = current;
  } catch (e) {
    console.warn('Could not load properties for expense form:', e);
  }
}

async function loadExpenses() {
  try {
    dgExpenseApplyProfileCopy();
    const res  = await fetch('/api/expenses?limit=50');
    const data = await res.json();
    const tbody = document.getElementById('exp-tbody');
    const sub   = document.getElementById('exp-list-sub');
    if (!tbody) return;

    const personal = dgExpensesIsPersonal();
    const rows = data.expenses || [];
    if (sub) sub.textContent = `${data.total || 0} total ${personal ? 'spending item' : 'expense'}${(data.total || 0) === 1 ? '' : 's'}`;

    if (rows.length === 0) {
      tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;color:var(--text-muted);padding:24px;">No ${personal ? 'spending' : 'expenses'} recorded yet.</td></tr>`;
      return;
    }

    tbody.innerHTML = rows.map(e => {
      const category = e.category_label || dgExpenseLabel(e.category || '');
      const vendor = e.vendor || (personal ? '—' : '—');
      const amount = dgExpenseMoney(e.amount_cents, e.amount);
      return `
        <tr>
          <td style="font-family:var(--mono);font-size:12px;">${e.expense_date || '—'}</td>
          <td>${vendor}</td>
          <td style="font-size:12px;color:var(--text-muted);">${category}</td>
          <td style="font-size:12px;color:var(--text-muted);">${e.notes || ''}</td>
          <td style="text-align:right;font-family:var(--mono);color:var(--neg);">-${amount}</td>
        </tr>`;
    }).join('');
  } catch (e) {
    console.warn('Could not load expenses:', e);
  }
}

async function submitExpense() {
  const msg    = document.getElementById('exp-msg');
  const dateEl = document.getElementById('exp-date');
  const amtEl  = document.getElementById('exp-amount');
  const acctEl = document.getElementById('exp-account');
  const venEl  = document.getElementById('exp-vendor');
  const noteEl = document.getElementById('exp-notes');

  const date   = dateEl?.value || '';
  const amount = amtEl?.value || '';
  const acct   = acctEl?.value || '';
  const vendor = (venEl?.value || '').trim();
  const notes  = (noteEl?.value || '').trim();
  const personal = dgExpensesIsPersonal();

  if (!msg) return;
  if (!date || !amount || !acct) {
    msg.textContent = `Date, amount, and ${personal ? 'category' : 'account'} are required.`;
    msg.style.color = 'var(--neg)';
    msg.style.display = 'inline';
    return;
  }

  msg.textContent = 'Saving…';
  msg.style.color = 'var(--text-muted)';
  msg.style.display = 'inline';

  try {
    const res  = await fetch('/api/expenses', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        expense_date: date,
        amount,
        account_id: acct,
        vendor,
        notes,
        property_id: (document.getElementById('exp-property')?.value || ''),
        user_profile: personal ? 'personal' : 'business',
      }),
    });
    const data = await res.json();
    if (data.ok) {
      msg.textContent = personal ? '✓ Spending saved' : '✓ Expense saved';
      msg.style.color = 'var(--pos)';
      if (amtEl) amtEl.value = '';
      if (venEl) venEl.value = '';
      if (noteEl) noteEl.value = '';
      if (acctEl) acctEl.value = '';
      const propEl = document.getElementById('exp-property');
      if (propEl) propEl.value = '';
      setTimeout(() => msg.style.display = 'none', 2500);
      loadExpenses();
      if (typeof loadDashboard === 'function') loadDashboard();
    } else {
      msg.textContent = data.error || 'Save failed.';
      msg.style.color = 'var(--neg)';
    }
  } catch (e) {
    msg.textContent = 'Network error: ' + e.message;
    msg.style.color = 'var(--neg)';
  }
}
