// stock-doc.jsx — Chứng từ kho in được (P4): Phiếu xuất kho, Phiếu nhập kho, Báo cáo tồn theo kỳ.
// Tái dùng helper chứng từ: docCompany / docFontStack / printDocument (payment-request.jsx).

function stockEsc(s){ return String(s == null ? '' : s).replace(/[&<>]/g, m => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;' }[m])); }
function stockDateLine(d){ const t = new Date(d || TODAY); return 'ngày ' + String(t.getDate()).padStart(2, '0') + ' tháng ' + String(t.getMonth() + 1).padStart(2, '0') + ' năm ' + t.getFullYear(); }
function stockMark(co){
  const mark = (co.short || 'SWO').replace(/[^A-Za-z]/g, '').slice(0, 3).toUpperCase() || 'SWO';
  return co.logo ? `<img class="mark-img" src="${co.logo}" alt="logo">` : `<div class="mark">${mark}<i></i></div>`;
}
function stockDocCSS(co){ return `
@page{size:A4;margin:15mm}
*{box-sizing:border-box}
body{font-family:${docFontStack(co)};color:#0A1730;font-size:13px;line-height:1.5;margin:0}
.doc{max-width:740px;margin:0 auto;padding:8px}
.head{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid #1466E0;padding-bottom:10px;margin-bottom:6px}
.co{display:flex;gap:10px;align-items:center}
.mark{width:40px;height:40px;border-radius:11px;background:linear-gradient(135deg,#12C5C0,#1466E0);color:#fff;display:flex;flex-direction:column;align-items:center;justify-content:center;font-weight:800;font-size:13px;letter-spacing:.5px}
.mark i{width:60%;height:2px;background:rgba(255,255,255,.9);border-radius:1px;margin-top:2px;display:block}
.mark-img{width:46px;height:46px;object-fit:contain;border-radius:8px}
.co .n{font-weight:700;font-size:14px}
.co .m{font-size:11px;color:#54657F}
.natl{text-align:center;font-size:11px;color:#54657F}
.natl b{color:#0A1730}
h1{text-align:center;font-size:20px;letter-spacing:.5px;margin:18px 0 2px;color:#0A1730}
.sub{text-align:center;font-size:12px;color:#54657F;margin-bottom:6px}
.docno{text-align:center;font-size:12px;color:#54657F;margin-bottom:14px}
.meta{display:flex;flex-wrap:wrap;gap:4px 26px;margin:8px 0 4px;font-size:12.5px}
.meta div b{color:#1466E0}
table{width:100%;border-collapse:collapse;margin:10px 0;font-size:12.5px}
th,td{border:1px solid #D0D5DD;padding:6px 9px;text-align:left}
th{background:#EAF1FE;font-weight:700}
td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
td.c,th.c{text-align:center}
tfoot td{font-weight:700;background:#F6F9FD}
.note{font-size:12px;border-left:3px solid #12C5C0;background:#F6F9FD;padding:8px 12px;margin:10px 0}
.appr{font-size:11.5px;color:#54657F;margin:6px 0}
.sign{display:flex;justify-content:space-between;margin-top:28px;text-align:center;gap:10px}
.sign>div{flex:1}
.sign .role{font-weight:700;font-size:12.5px}
.sign .note2{font-size:11px;color:#54657F;font-style:italic}
.sign .space{height:64px}
.foot{margin-top:22px;border-top:1px solid #E3E6EC;padding-top:8px;font-size:10.5px;color:#98A2B3;text-align:center}
@media print{.no-print{display:none!important}}
`; }
function stockDocHead(co){
  return `<div class="head">
    <div class="co">${stockMark(co)}<div><div class="n">${stockEsc(co.name)}</div><div class="m">MST: ${stockEsc(co.mst)} · ${stockEsc(co.phone)} · ${stockEsc(co.email)}</div><div class="m">${stockEsc(co.addr)}</div></div></div>
    <div class="natl"><b>CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</b><br>Độc lập – Tự do – Hạnh phúc<br>———o0o———</div>
  </div>`;
}
function stockDocFoot(co){ return `<div class="foot">${stockEsc(co.short)} · ${stockEsc(co.tagline)} · ${stockEsc(co.email)} · ${stockEsc(co.phone)}</div>`; }

/* ---------- Phiếu xuất kho (PX) ---------- */
function stockIssueHTML(iss, p){
  const co = docCompany(p.branding);
  const cust = (iss.customer && window.CustomerStore && CustomerStore.byCode(iss.customer)) || {};
  const rows = (iss.lines || []).map((l, i) =>
    `<tr><td class="c">${i + 1}</td><td>${stockEsc(l.item)}</td><td>${stockEsc(l.name)}</td><td class="c">${stockEsc(l.unit)}</td><td class="num">${l.qty}</td></tr>`).join('');
  const totQty = (iss.lines || []).reduce((s, l) => s + (+l.qty || 0), 0);
  const appr = (iss.approvals || []).filter(a => a.action === 'approve').map(a => `Cấp ${a.level}: ${stockEsc(a.by)} (${fmtDate(a.at)})`).join(' · ');
  return `<!DOCTYPE html><html lang="vi"><head><meta charset="utf-8"><title>${stockEsc(iss.code)}</title><style>${stockDocCSS(co)}</style></head>
<body><div class="doc">
  ${stockDocHead(co)}
  <h1>PHIẾU XUẤT KHO</h1><div class="sub">STOCK ISSUE NOTE</div>
  <div class="docno">Số: ${stockEsc(iss.code)} &nbsp;·&nbsp; ${stockDateLine(iss.issuedDate || iss.createdDate)}</div>
  <div class="meta">
    ${iss.contract ? `<div>Hợp đồng: <b>${stockEsc(iss.contract)}</b></div>` : ''}
    ${cust.name ? `<div>Khách hàng: <b>${stockEsc(cust.shortName || cust.name)}</b></div>` : ''}
    <div>Người lập: <b>${stockEsc(iss.createdBy || '')}</b></div>
    <div>Ngày tạo: <b>${fmtDate(iss.createdDate)}</b></div>
  </div>
  <table>
    <thead><tr><th class="c" style="width:42px">STT</th><th style="width:110px">Mã hàng</th><th>Tên mặt hàng</th><th class="c" style="width:80px">ĐVT</th><th class="num" style="width:90px">Số lượng</th></tr></thead>
    <tbody>${rows || '<tr><td colspan="5" class="c" style="color:#98A2B3">—</td></tr>'}</tbody>
    <tfoot><tr><td colspan="4" class="num">Tổng số lượng</td><td class="num">${totQty}</td></tr></tfoot>
  </table>
  ${appr ? `<div class="appr"><b>Đã duyệt:</b> ${appr}</div>` : ''}
  ${iss.note ? `<div class="note">${stockEsc(iss.note)}</div>` : ''}
  <div class="sign">
    <div><div class="role">NGƯỜI LẬP PHIẾU</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div><div>${stockEsc(iss.createdBy || '')}</div></div>
    <div><div class="role">THỦ KHO</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
    <div><div class="role">NGƯỜI NHẬN HÀNG</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
  </div>
  ${stockDocFoot(co)}
</div></body></html>`;
}

/* ---------- Phiếu nhập kho (PN) ---------- */
function stockReceiptHTML(rec, p){
  const co = docCompany(p.branding);
  const ven = (rec.vendor && window.VendorStore && VendorStore.byCode(rec.vendor)) || {};
  const buyCon = (rec.buyContract && p.contracts) ? p.contracts.find(c => c.code === rec.buyContract) : null;
  const srcLabel = { manual:'Nhập thủ công', opening:'Tồn đầu kỳ', buy:'Từ hợp đồng mua' }[rec.source] || 'Nhập kho';
  const rows = (rec.lines || []).map((l, i) =>
    `<tr><td class="c">${i + 1}</td><td>${stockEsc(l.item)}</td><td>${stockEsc(l.name)}</td><td class="c">${stockEsc(l.unit)}</td><td class="num">${l.qty}</td></tr>`).join('');
  const totQty = (rec.lines || []).reduce((s, l) => s + (+l.qty || 0), 0);
  return `<!DOCTYPE html><html lang="vi"><head><meta charset="utf-8"><title>${stockEsc(rec.code)}</title><style>${stockDocCSS(co)}</style></head>
<body><div class="doc">
  ${stockDocHead(co)}
  <h1>PHIẾU NHẬP KHO</h1><div class="sub">STOCK RECEIPT NOTE</div>
  <div class="docno">Số: ${stockEsc(rec.code)} &nbsp;·&nbsp; ${stockDateLine(rec.date)}</div>
  <div class="meta">
    <div>Loại phiếu: <b>${stockEsc(srcLabel)}</b></div>
    ${rec.buyContract ? `<div>Hợp đồng mua: <b>${stockEsc(buyCon ? (buyCon.contractNo || buyCon.code) : rec.buyContract)}</b></div>` : ''}
    ${ven.name ? `<div>Nhà cung cấp: <b>${stockEsc(ven.shortName || ven.name)}</b></div>` : ''}
    <div>Người lập: <b>${stockEsc(rec.by || '')}</b></div>
  </div>
  <table>
    <thead><tr><th class="c" style="width:42px">STT</th><th style="width:110px">Mã hàng</th><th>Tên mặt hàng</th><th class="c" style="width:80px">ĐVT</th><th class="num" style="width:90px">Số lượng</th></tr></thead>
    <tbody>${rows || '<tr><td colspan="5" class="c" style="color:#98A2B3">—</td></tr>'}</tbody>
    <tfoot><tr><td colspan="4" class="num">Tổng số lượng</td><td class="num">${totQty}</td></tr></tfoot>
  </table>
  ${rec.note ? `<div class="note">${stockEsc(rec.note)}</div>` : ''}
  <div class="sign">
    <div><div class="role">NGƯỜI LẬP PHIẾU</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div><div>${stockEsc(rec.by || '')}</div></div>
    <div><div class="role">THỦ KHO</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
    <div><div class="role">NGƯỜI GIAO HÀNG</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
  </div>
  ${stockDocFoot(co)}
</div></body></html>`;
}

/* ---------- Báo cáo tồn kho theo kỳ ---------- */
// rows: [{ code, name, unit, opening, inQty, outQty, adjQty, closing }]
function stockReportHTML(rows, from, to, p){
  const co = docCompany(p.branding);
  const body = (rows || []).map((r, i) =>
    `<tr><td class="c">${i + 1}</td><td>${stockEsc(r.code)}</td><td>${stockEsc(r.name)}</td><td class="c">${stockEsc(r.unit)}</td><td class="num">${r.opening}</td><td class="num">${r.inQty}</td><td class="num">${r.outQty}</td><td class="num">${r.adjQty}</td><td class="num"><b>${r.closing}</b></td></tr>`).join('');
  const sum = (rows || []).reduce((a, r) => ({ o:a.o + r.opening, i:a.i + r.inQty, x:a.x + r.outQty, j:a.j + r.adjQty, c:a.c + r.closing }), { o:0, i:0, x:0, j:0, c:0 });
  return `<!DOCTYPE html><html lang="vi"><head><meta charset="utf-8"><title>Báo cáo tồn kho</title><style>${stockDocCSS(co)}</style></head>
<body><div class="doc">
  ${stockDocHead(co)}
  <h1>BÁO CÁO TỒN KHO</h1><div class="sub">INVENTORY REPORT</div>
  <div class="docno">Kỳ: ${fmtDate(from)} — ${fmtDate(to)}</div>
  <table>
    <thead><tr><th class="c" style="width:38px">STT</th><th style="width:100px">Mã</th><th>Tên mặt hàng</th><th class="c" style="width:60px">ĐVT</th><th class="num">Tồn đầu</th><th class="num">Nhập</th><th class="num">Xuất</th><th class="num">Đ.chỉnh</th><th class="num">Tồn cuối</th></tr></thead>
    <tbody>${body || '<tr><td colspan="9" class="c" style="color:#98A2B3">Không có mặt hàng quản lý tồn</td></tr>'}</tbody>
    <tfoot><tr><td colspan="4" class="num">Tổng cộng</td><td class="num">${sum.o}</td><td class="num">${sum.i}</td><td class="num">${sum.x}</td><td class="num">${sum.j}</td><td class="num">${sum.c}</td></tr></tfoot>
  </table>
  <div class="appr">Tồn cuối = Tồn đầu + Nhập − Xuất + Điều chỉnh. Lập ${stockDateLine(TODAY)}.</div>
  <div class="sign">
    <div><div class="role">NGƯỜI LẬP BÁO CÁO</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
    <div><div class="role">THỦ KHO</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
    <div><div class="role">PHỤ TRÁCH</div><div class="note2">(Ký, ghi rõ họ tên)</div><div class="space"></div></div>
  </div>
  ${stockDocFoot(co)}
</div></body></html>`;
}

// Tính báo cáo tồn theo kỳ từ sổ moves cho các mặt hàng quản lý tồn.
function buildStockReport(products, moves, from, to){
  const its = (products || []).filter(x => x.stockTracked);
  return its.map(it => {
    let opening = 0, inQty = 0, outQty = 0, adjQty = 0;
    (moves || []).forEach(mv => {
      if (mv.item !== it.code) return;
      const q = +mv.qty || 0;
      if (mv.date < from) { opening += (mv.type === 'out' ? -q : q); }
      else if (mv.date <= to) {
        if (mv.type === 'in') inQty += q;
        else if (mv.type === 'out') outQty += q;
        else adjQty += q;
      }
    });
    return { code:it.code, name:it.name, unit:it.unit, opening, inQty, outQty, adjQty, closing:opening + inQty - outQty + adjQty };
  });
}

Object.assign(window, { stockIssueHTML, stockReceiptHTML, stockReportHTML, buildStockReport });
