// daygig-subs.js — Subcontractors & 1099-NEC UI (contractor mode)

(function () {
  const $ = (id) => document.getElementById(id);
  const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => (
    { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  const money = (cents) => window.dgMoneyC(cents);
  const toCents = (v) => Math.round(parseFloat(String(v || '').replace(/[^0-9.]/g, '')) * 100) || 0;

  let _selected = null;

  async function subsCreate() {
    const errEl = $('sub-new-err'); errEl.textContent = '';
    const name = $('sub-new-name').value.trim();
    if (!name) { errEl.textContent = 'Name is required.'; errEl.classList.add('show'); return; }
    const contact = $('sub-new-contact').value.trim();
    const payload = {
      name: name,
      business_name: $('sub-new-biz').value.trim(),
      address: $('sub-new-addr').value.trim(),
      tax_id: $('sub-new-tin').value.trim(),
      email: contact.includes('@') ? contact : '',
      phone: contact.includes('@') ? '' : contact,
      w9_on_file: $('sub-new-w9').checked,
    };
    const res = await fetch('/api/subcontractors', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }).then(r => r.json());
    if (!res.ok) { errEl.textContent = res.error || 'Could not add.'; errEl.classList.add('show'); return; }
    ['sub-new-name', 'sub-new-biz', 'sub-new-addr', 'sub-new-tin', 'sub-new-contact'].forEach(id => $(id).value = '');
    $('sub-new-w9').checked = false;
    subsLoad(); subs1099();
    subsOpen(res.subcontractor.id);
  }

  async function subsLoad() {
    const listEl = $('subs-list');
    try {
      const data = await fetch('/api/subcontractors').then(r => r.json());
      const subs = data.subcontractors || [];
      if (!subs.length) { listEl.innerHTML = '<div class="hint">No subcontractors yet.</div>'; return; }
      listEl.innerHTML = subs.map(s => `
        <button class="sub-row" onclick="subsOpen(${s.id})" style="display:block;width:100%;text-align:left;background:${_selected === s.id ? 'var(--surface2)' : 'transparent'};border:1px solid var(--border-soft);border-radius:6px;padding:9px 11px;margin-bottom:6px;cursor:pointer;">
          <div style="display:flex;justify-content:space-between;gap:8px;">
            <strong style="font-size:13px;color:var(--text);">${esc(s.name)}</strong>
            <span style="font-size:10px;font-weight:700;color:${s.w9_on_file ? 'var(--pos)' : 'var(--warn-amber)'};">${s.w9_on_file ? 'W-9 ✓' : 'W-9 missing'}</span>
          </div>
          <div style="font-size:11px;color:var(--text-soft);margin-top:2px;">${esc(s.business_name || '')}${s.tax_id_masked ? ' · TIN ' + esc(s.tax_id_masked) : ''}</div>
        </button>`).join('');
    } catch (e) { listEl.innerHTML = '<div class="alert err show">Could not load.</div>'; }
  }

  async function subsOpen(id) {
    _selected = id;
    const res = await fetch('/api/subcontractors/' + id).then(r => r.json());
    if (!res.ok) return;
    const s = res.subcontractor;
    $('sub-detail').innerHTML = `
      <div class="card-header"><div class="card-title">${esc(s.name)}</div><div class="card-sub">${esc(s.business_name || '')}</div></div>
      <div class="field"><label>Name</label><input type="text" id="sd-name" value="${esc(s.name)}"></div>
      <div class="field"><label>Business name</label><input type="text" id="sd-biz" value="${esc(s.business_name || '')}"></div>
      <div class="field"><label>Address</label><input type="text" id="sd-addr" value="${esc(s.address || '')}"></div>
      <div class="field"><label>TIN / EIN</label><input type="text" id="sd-tin" value="${esc(s.tax_id || '')}"></div>
      <div class="field"><label>Email</label><input type="text" id="sd-email" value="${esc(s.email || '')}"></div>
      <div class="field"><label>Phone</label><input type="text" id="sd-phone" value="${esc(s.phone || '')}"></div>
      <label style="font-size:13px;display:flex;align-items:center;gap:6px;margin-bottom:10px;"><input type="checkbox" id="sd-w9" ${s.w9_on_file ? 'checked' : ''}> W-9 on file</label>
      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;">
        <button class="btn btn-primary" onclick="subsSave(${s.id})">Save</button>
        <button class="btn btn-ghost" onclick="subsDelete(${s.id})">Delete</button>
      </div>
      <div class="card" style="margin:0;">
        <div class="card-header"><div class="card-title" style="font-size:13px;">Record payment</div></div>
        <div style="display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap;">
          <div class="field" style="margin:0;"><label>Amount ($)</label><input type="text" id="sd-pay-amt" placeholder="0.00" style="width:110px;"></div>
          <div class="field" style="margin:0;"><label>Job ID (optional)</label><input type="text" id="sd-pay-job" placeholder="#" style="width:90px;"></div>
          <button class="btn btn-primary" onclick="subsPay(${s.id})">Record</button>
        </div>
        <div class="hint" style="margin-top:6px;">Posts to Subcontractor Labor and counts toward this sub's 1099 total.</div>
      </div>`;
    subsLoad();
  }

  async function subsSave(id) {
    const payload = {
      name: $('sd-name').value.trim(), business_name: $('sd-biz').value.trim(),
      address: $('sd-addr').value.trim(), tax_id: $('sd-tin').value.trim(),
      email: $('sd-email').value.trim(), phone: $('sd-phone').value.trim(),
      w9_on_file: $('sd-w9').checked,
    };
    const res = await fetch('/api/subcontractors/' + id, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }).then(r => r.json());
    if (!res.ok) { alert(res.error || 'Could not save.'); return; }
    subsLoad(); subs1099();
  }

  async function subsPay(id) {
    const amt = toCents($('sd-pay-amt').value);
    if (amt <= 0) return;
    const job = $('sd-pay-job').value.trim();
    const body = { amount_cents: amt, payment_method: 'bank' };
    if (job) body.job_id = parseInt(job, 10);
    const res = await fetch(`/api/subcontractors/${id}/payment`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => r.json());
    if (!res.ok) { alert(res.error || 'Could not record payment.'); return; }
    $('sd-pay-amt').value = ''; $('sd-pay-job').value = '';
    subs1099();
    alert('Payment recorded.');
  }

  async function subsDelete(id) {
    if (!confirm('Delete this subcontractor? Payment history stays in the ledger.')) return;
    const res = await fetch(`/api/subcontractors/${id}/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }).then(r => r.json());
    if (!res.ok) { alert(res.error || 'Could not delete.'); return; }
    _selected = null;
    $('sub-detail').innerHTML = '<div class="hint">Select a subcontractor to edit or record a payment.</div>';
    subsLoad(); subs1099();
  }

  async function subs1099() {
    const box = $('subs-1099');
    const yr = $('sub-1099-year').value.trim();
    try {
      const data = await fetch('/api/subcontractors/summary' + (yr ? '?year=' + yr : '')).then(r => r.json());
      if (!$('sub-1099-year').value) $('sub-1099-year').value = data.tax_year;
      const rows = data.subcontractors || [];
      let html = `<div style="font-size:12px;color:var(--text-soft);margin-bottom:8px;">${rows.length} subcontractor(s) · ${data.flagged_count} need a 1099-NEC (≥ ${data.threshold ? '$' + data.threshold : '$600'})</div>`;
      if (rows.length) {
        html += `<table class="schema-table" style="width:100%;font-size:12px;"><thead><tr><th>Name</th><th style="text-align:right;">YTD paid</th><th style="text-align:center;">1099?</th><th>Status</th></tr></thead><tbody>`;
        html += rows.map(r => `<tr>
          <td>${esc(r.name)}</td>
          <td style="text-align:right;">${money(r.ytd_paid_cents)}</td>
          <td style="text-align:center;">${r.needs_1099 ? '<strong style="color:var(--warn-amber);">YES</strong>' : 'no'}</td>
          <td>${r.needs_1099 ? (r.ready_to_file ? '<span style="color:var(--pos);">Ready</span>' : '<span style="color:var(--neg);">Missing: ' + r.missing_for_1099.join(', ') + '</span>') : '—'}</td>
        </tr>`).join('');
        html += '</tbody></table>';
      }
      if ((data.unmatched_vendors || []).length) {
        html += `<div style="font-size:11px;color:var(--text-soft);margin-top:10px;">Paid into Subcontractor Labor but no sub record yet: ${data.unmatched_vendors.map(v => esc(v.vendor) + ' (' + money(v.reportable_cents) + ')').join(', ')}. Add them above to track W-9s.</div>`;
      }
      html += `<div class="hint" style="margin-top:8px;">${esc(data.note || '')}</div>`;
      box.innerHTML = html;
    } catch (e) { box.innerHTML = '<div class="alert err show">Could not load 1099 summary.</div>'; }
  }

  window.subsLoad = subsLoad;
  window.subsCreate = subsCreate;
  window.subsOpen = subsOpen;
  window.subsSave = subsSave;
  window.subsPay = subsPay;
  window.subsDelete = subsDelete;
  window.subs1099 = subs1099;
})();
