// daygig-materials.js — Materials: list, add form

// ── Materials ─────────────────────────────────────────────────────────────
  function toggleMatForm() {
    const body = document.getElementById('matFormBody');
    body.style.display = body.style.display === 'none' ? '' : 'none';
  }

  async function materialsLoad() {
    const tbody  = document.getElementById('mat-tbody');
    const sub    = document.getElementById('mat-sub');
    const search = document.getElementById('mat-search')?.value.trim() || '';
    if (!tbody) return;
    tbody.innerHTML = '<tr><td colspan="7" style="padding:32px;text-align:center;color:var(--text-dim);">Loading…</td></tr>';
    try {
      const url = '/api/materials?active_only=1' + (search ? `&search=${encodeURIComponent(search)}` : '');
      const res  = await fetch(url);
      const data = await res.json();
      const mats = Array.isArray(data) ? data : (data.materials || []);
      if (!mats.length) {
        tbody.innerHTML = '<tr><td colspan="7" style="padding:32px;text-align:center;color:var(--text-dim);">No materials yet. Add one above.</td></tr>';
        sub.textContent = 'Raw inputs — paper, blanks, packaging, ink';
        return;
      }
      sub.textContent = `${data.total || mats.length} material${(data.total||mats.length) !== 1 ? 's' : ''}`;
      tbody.innerHTML = mats.map(m => {
        const cost  = (m.cost_per_unit || 0) / 100;          // cost_per_unit is stored in cents
        const qty   = m.quantity_on_hand || 0;
        const value = (m.inventory_value_cents || 0) / 100;
        return `<tr style="border-bottom:1px solid var(--border);">
          <td style="padding:7px 10px;font-family:var(--mono);font-size:11px;color:var(--text-soft);">${m.sku || '—'}</td>
          <td style="padding:7px 10px;font-size:13px;color:var(--text);font-weight:500;">${m.name}</td>
          <td style="padding:7px 10px;font-size:12px;color:var(--text-soft);">${m.unit_of_measure || '—'}</td>
          <td style="padding:7px 10px;text-align:right;font-family:var(--mono);font-size:12px;color:var(--text);">${qty > 0 ? qty.toFixed(2) : '—'}</td>
          <td style="padding:7px 10px;text-align:right;font-family:var(--mono);font-size:12px;color:var(--text-soft);">$${cost.toFixed(4)}</td>
          <td style="padding:7px 10px;text-align:right;font-family:var(--mono);font-size:12px;color:var(--text);">${value > 0 ? dgMoney(value) : '—'}</td>
          <td style="padding:7px 10px;font-size:12px;color:var(--text-soft);">${m.supplier || '—'}</td>
        </tr>`;
      }).join('');
    } catch(e) { tbody.innerHTML = `<tr><td colspan="7" style="padding:20px;color:var(--err);">Error: ${e.message}</td></tr>`; }
  }

  async function submitMaterial() {
    const name     = document.getElementById('mat-name').value.trim();
    const code     = document.getElementById('mat-code').value.trim();
    const unit     = document.getElementById('mat-unit').value;
    const cost     = parseFloat(document.getElementById('mat-cost').value || '0');
    const category = document.getElementById('mat-category').value.trim();
    const vendor   = document.getElementById('mat-vendor').value.trim();
    const notes    = document.getElementById('mat-notes').value.trim();
    const msg      = document.getElementById('mat-msg');

    if (!name || !code) {
      msg.style.display = ''; msg.style.color = 'var(--err)';
      msg.textContent = 'Name and Code are required.'; return;
    }
    msg.style.display = ''; msg.style.color = 'var(--text-soft)';
    msg.textContent = 'Saving…';
    try {
      const res  = await fetch('/api/materials', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
          name, code,
          unit_of_measure: unit,
          default_unit_cost: cost,
          category: category || null,
          vendor: vendor || null,
          notes: notes || null,
          is_active: true,
        }),
      });
      const data = await res.json();
      if (data.id || data.ok) {
        msg.style.color = 'var(--accent)';
        msg.textContent = '✓ Saved.';
        ['mat-name','mat-code','mat-cost','mat-category','mat-vendor','mat-notes'].forEach(id => {
          const el = document.getElementById(id); if (el) el.value = '';
        });
        document.getElementById('mat-unit').value = 'each';
        toggleMatForm();
        materialsLoad();
        _allMaterials = []; // bust BOM cache so next BOM open gets fresh list
      } else {
        msg.style.color = 'var(--err)';
        msg.textContent = data.error || 'Error saving material.';
      }
    } catch(e) {
      msg.style.color = 'var(--err)';
      msg.textContent = 'Network error: ' + e.message;
    }
  }