const Storage = {
  saveTemplate(name, desc) {return Templates.saveCurrent(name, desc);},
  exportAll() {
    return {
      template: {
        paperSize: document.getElementById('paper-size').value,
        components: Pro.components.map(c => ({type: c.type, data: {...c.data}}))
      },
      data: Pro.data,
      items: Pro.items
    };
  },
  importAll(obj) {
    if (obj.template) {
      document.getElementById('paper-size').value = obj.template.paperSize || '80mm';
      changePaperSize();
      Pro.components = (obj.template.components || []).map(c => ({id: 'comp-' + (Pro.idCounter++), type: c.type, data: {...c.data}}));
      document.getElementById('drop-zone').innerHTML = '';
      Pro.components.forEach(renderComponent);
    }
    if (obj.data) {Pro.data = {...Pro.data, ...obj.data, store: {...Pro.data.store, ...obj.data.store}, receipt: {...Pro.data.receipt, ...obj.data.receipt}}; fillDataForm();}
    if (Array.isArray(obj.items)) Pro.items = obj.items.map(it => ({...it}));
    renderItems();
  },
  // Receipts archive (for reprint)
  saveReceipt() {
    const snapshot = {
      id: Pro.data.receipt.id || ('INV-' + Date.now()),
      ts: Date.now(),
      template: {paperSize: document.getElementById('paper-size').value, components: Pro.components.map(c => ({type: c.type, data: {...c.data}}))},
      data: JSON.parse(JSON.stringify(Pro.data)),
      items: JSON.parse(JSON.stringify(Pro.items))
    };
    const arr = JSON.parse(localStorage.getItem('pro.receipts') || '[]');
    arr.unshift(snapshot);
    localStorage.setItem('pro.receipts', JSON.stringify(arr));
    // Best-effort: also send to server storage
    try {apiSaveReceipt(snapshot).catch(() => {});} catch (e) {}
    return snapshot;
  },
  listReceipts() {return JSON.parse(localStorage.getItem('pro.receipts') || '[]');},
  loadReceipt(id) {
    const r = Storage.listReceipts().find(x => x.id === id);
    if (!r) return;
    Storage.importAll({template: r.template, data: r.data, items: r.items});
  }
};

// API placeholders (PHP/MySQL ready)
async function apiSaveReceipt(snapshot) {
  // POST to api/save_receipt.php
  try {
    const res = await fetch('api/save_receipt.php', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(snapshot)});
    return await res.json();
  } catch (e) {return {ok: false, error: String(e)}}
}

async function apiListReceipts() {
  try {
    const res = await fetch('api/list_receipts.php');
    return await res.json();
  } catch (e) {return {ok: false, error: String(e)}}
}
