// sdata.jsx — data + helpers for the PRODUCTS & SERVICES (Sản phẩm & Dịch vụ) module.
// Loaded after cdata.jsx + qdata.jsx (uses TODAY, vnd; references QUOTES/CONTRACTS item names
// via fuzzy matching to derive each product's transaction history & price trend).

const PRODUCT_CATEGORIES = [
  { id:'cloud',     vi:'Hạ tầng & Cloud',     en:'Infrastructure & Cloud' },
  { id:'phan-mem',  vi:'Phần mềm & License',  en:'Software & License' },
  { id:'dich-vu',   vi:'Dịch vụ vận hành',    en:'Managed services' },
  { id:'trien-khai',vi:'Triển khai & Tư vấn', en:'Delivery & Consulting' },
  { id:'phan-cung', vi:'Phần cứng',           en:'Hardware' },
  { id:'khac',      vi:'Khác',                en:'Other' },
];
const PRODUCT_STATUS = {
  active:   { vi:'Đang bán', en:'Active',   cls:'badge-success' },
  inactive: { vi:'Ngừng',    en:'Retired',  cls:'badge-neutral' },
};
// Đơn vị tính mặc định (catalog 'units' — admin định nghĩa trước trong Cài đặt; form chọn hoặc gõ mới).
const PRODUCT_UNITS = ['gói', 'tháng', 'năm', 'quý', 'lần', 'cái', 'chiếc', 'bộ', 'giờ', 'ngày', 'người', 'license', 'thiết bị', 'hệ thống'];

// ph(date, price, note) — one point on a product's price timeline (oldest → newest).
function ph(date, price, note){ return { date, price, note:note || '' }; }

// p = { code, name, category, unit, vat, status, desc, match:[tokens], priceHistory:[ph()] }
const PRODUCTS = [
  { code:'SP-001', name:'Thuê hạ tầng Cloud & vận hành', category:'cloud', unit:'tháng', vat:8, status:'active',
    desc:'Gói thuê hạ tầng điện toán đám mây kèm vận hành 24/7, tính theo tháng.',
    match:['ha tang cloud'],
    priceHistory:[ ph('2025-01-01', 18000000, 'Giá niêm yết 2025'), ph('2026-01-01', 20000000, 'Điều chỉnh đầu năm'), ph('2026-06-01', 22000000, 'Gói mở rộng dung lượng') ] },

  { code:'SP-002', name:'Tổng đài Cloud VoIP', category:'cloud', unit:'gói', vat:8, status:'active',
    desc:'Hệ thống tổng đài Cloud VoIP, triển khai theo số máy nhánh.',
    match:['tong dai cloud voip'],
    priceHistory:[ ph('2025-06-01', 75000000, 'Giá triển khai chuẩn'), ph('2026-01-01', 80000000, 'Cập nhật theo chi phí hạ tầng') ] },

  { code:'SP-003', name:'Giải pháp số hóa quy trình AppSheet', category:'trien-khai', unit:'gói', vat:8, status:'active',
    desc:'Số hóa quy trình nội bộ trên nền tảng AppSheet, theo phạm vi triển khai.',
    match:['so hoa quy trinh appsheet'],
    priceHistory:[ ph('2025-09-01', 240000000, 'Báo giá khởi điểm'), ph('2026-01-01', 260000000, 'Tăng phạm vi module') ] },

  { code:'SP-004', name:'AppSheet Enterprise — License triển khai', category:'phan-mem', unit:'gói', vat:8, status:'active',
    desc:'Bản quyền AppSheet Enterprise kèm cấu hình triển khai ban đầu.',
    match:['appsheet enterprise'],
    priceHistory:[ ph('2025-06-01', 120000000, 'Giá license 2025'), ph('2026-01-01', 120000000, 'Giữ nguyên') ] },

  { code:'SP-005', name:'PC Health Check Annual', category:'dich-vu', unit:'năm', vat:8, status:'active',
    desc:'Dịch vụ kiểm tra & bảo trì thiết bị định kỳ theo năm (gói 80 thiết bị).',
    match:['pc health check'],
    priceHistory:[ ph('2024-06-01', 88000000, 'Giá 2024'), ph('2025-06-01', 96000000, 'Điều chỉnh 2025') ] },

  { code:'SP-006', name:'Dịch vụ vận hành hệ thống quản lý linh kiện', category:'dich-vu', unit:'tháng', vat:8, status:'active',
    desc:'Vận hành & hỗ trợ hệ thống quản lý linh kiện điện tử theo tháng.',
    match:['quan ly linh kien'],
    priceHistory:[ ph('2025-01-01', 25000000, 'Giá hợp đồng 2025'), ph('2026-01-01', 26000000, 'Cập nhật nhân sự vận hành') ] },

  { code:'SP-007', name:'Phần mềm quản lý vận hành (SaaS)', category:'phan-mem', unit:'tháng', vat:8, status:'active',
    desc:'Thuê phần mềm quản lý vận hành dạng SaaS, tính theo tháng.',
    match:['phan mem quan ly van hanh'],
    priceHistory:[ ph('2025-06-01', 14000000, 'Giá thuê SaaS'), ph('2026-06-01', 14000000, 'Giữ nguyên') ] },

  { code:'SP-008', name:'Hệ thống quản lý logistics — License', category:'phan-mem', unit:'gói', vat:8, status:'active',
    desc:'Bản quyền hệ thống quản lý logistics theo gói triển khai.',
    match:['quan ly logistics'],
    priceHistory:[ ph('2026-01-01', 220000000, 'Giá license 2026') ] },

  { code:'SP-009', name:'Phần cứng đầu đọc & thiết bị', category:'phan-cung', unit:'bộ', vat:10, status:'active',
    desc:'Thiết bị đầu đọc mã & phụ kiện đi kèm, tính theo bộ.',
    match:['dau doc'],
    priceHistory:[ ph('2025-06-01', 7000000, 'Giá nhập 2025'), ph('2026-01-01', 6500000, 'Giảm theo giá nhà cung cấp') ] },

  { code:'SP-010', name:'Tư vấn chuyển đổi số', category:'trien-khai', unit:'gói', vat:8, status:'active',
    desc:'Dịch vụ tư vấn lộ trình chuyển đổi số cho doanh nghiệp.',
    match:['tu van chuyen doi so'],
    priceHistory:[ ph('2025-09-01', 40000000, 'Giá gói tư vấn') ] },

  { code:'SP-011', name:'Triển khai & đào tạo vận hành', category:'trien-khai', unit:'gói', vat:8, status:'active',
    desc:'Dịch vụ triển khai tại hiện trường kèm đào tạo chuyển giao vận hành.',
    match:['dao tao van hanh','trien khai & dao tao'],
    priceHistory:[ ph('2025-06-01', 80000000, 'Giá triển khai chuẩn') ] },

  { code:'SP-012', name:'Hợp tác phát triển module AI', category:'trien-khai', unit:'giai đoạn', vat:8, status:'active',
    desc:'Hợp tác phát triển module AI theo từng giai đoạn.',
    match:['module ai'],
    priceHistory:[ ph('2026-04-01', 70000000, 'Giá giai đoạn 1') ] },
];

function sdeburr(s){ return (s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/đ/g, 'd'); }
function productMatches(prod, name){ const n = sdeburr(name); return (prod.match || []).some(tok => n.includes(sdeburr(tok))); }
function productPrice(p){ const h = p.priceHistory || []; return h.length ? h[h.length - 1].price : 0; }
function productPrevPrice(p){ const h = p.priceHistory || []; return h.length > 1 ? h[h.length - 2].price : null; }
function productTrend(p){
  const cur = productPrice(p), prev = productPrevPrice(p);
  if (prev == null || prev === cur) return { dir:'flat', pct:0, diff:0 };
  const pct = Math.round((cur - prev) / prev * 100);
  return { dir:cur > prev ? 'up' : 'down', pct:Math.abs(pct), diff:cur - prev };
}
// Giá vốn (giá nhập từ NCC) — khai trên sản phẩm, NỘI BỘ (không in cho khách).
function productCost(p){ return +p.cost || 0; }
// Markup dự kiến: chênh = giá bán − giá vốn; Biên = chênh / giá bán (đồng nhất cách tính của productSpread).
function productMargin(p){
  const sell = productPrice(p), cost = productCost(p);
  const diff = sell - cost;
  return { sell, cost, diff, pct: sell ? Math.round(diff / sell * 100) : 0, has: cost > 0 };
}
// transactions where this product was quoted / contracted (newest first)
function productTransactions(prod, quotes, contracts){
  const out = [];
  (contracts || []).forEach(c => (c.items || []).forEach(it => { if (productMatches(prod, it.name)) out.push({ date:c.signDate, kind:'contract', code:c.code, customer:c.customer, qty:it.qty, price:it.price, itemName:it.name }); }));
  (quotes || []).forEach(q => (q.items || []).forEach(it => { if (productMatches(prod, it.name)) out.push({ date:q.issueDate, kind:'quote', code:q.code, customer:q.customer, qty:it.qty, price:it.price, itemName:it.name }); }));
  return out.sort((a, b) => a.date < b.date ? 1 : -1);
}
function productCustomers(prod, quotes, contracts){
  return [...new Set(productTransactions(prod, quotes, contracts).map(t => t.customer))];
}
// Chênh lệch giá mua (HĐ mua, đầu vào) vs giá bán (HĐ bán, đầu ra) theo từng sản phẩm.
function productSpread(prod, contracts){
  const buy = [], sell = [];
  (contracts || []).forEach(c => (c.items || []).forEach(it => {
    if (sdeburr(it.name) === sdeburr(prod.name) || productMatches(prod, it.name)) {
      (c.direction === 'buy' ? buy : sell).push({ code:c.code, customer:c.customer, date:c.signDate, price:+it.price || 0, qty:+it.qty || 0, itemName:it.name });
    }
  }));
  const avg = a => a.length ? Math.round(a.reduce((s, x) => s + x.price, 0) / a.length) : 0;
  const avgBuy = avg(buy), avgSell = avg(sell);
  return { buy, sell, avgBuy, avgSell, diff:avgSell - avgBuy, marginPct: avgSell ? Math.round((avgSell - avgBuy) / avgSell * 100) : 0 };
}
function genProductCode(list){
  const max = (list || []).reduce((m, p) => { const mm = (p.code || '').match(/SP-(\d+)/); return mm ? Math.max(m, +mm[1]) : m; }, 0);
  return 'SP-' + String(max + 1).padStart(3, '0');
}
// Mã hàng (SKU) gợi ý từ tên: viết tắt chữ đầu các từ có nghĩa, in hoa, tối đa 8 ký tự.
function genProductSku(name){
  const words = sdeburr(name).toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);
  if (!words.length) return '';
  const initials = words.map(w => w[0]).join('');
  return (initials.length >= 3 ? initials : words.join('')).slice(0, 8);
}

Object.assign(window, {
  PRODUCT_CATEGORIES, PRODUCT_STATUS, PRODUCT_UNITS, PRODUCTS, ph, sdeburr, productMatches,
  productPrice, productPrevPrice, productTrend, productCost, productMargin, productTransactions, productCustomers, productSpread, genProductCode, genProductSku,
});
