/* global lecygne */
// =====================================================================
// Impression de documents (Bon de livraison / Facture) à l'en-tête de
// la société. Ouvre une fenêtre dédiée et déclenche l'impression —
// aucune dépendance, le navigateur permet l'export PDF (« Enregistrer
// au format PDF »). Exposé en global : window.printDocument(...).
// =====================================================================

function _esc(s) {
  return String(s == null ? "" : s)
    .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function _clientName(c) {
  if (!c) return "—";
  return c.societe || [c.prenoms, c.nom_client].filter(Boolean).join(" ") || `#${c.code_client}`;
}

// data = { kind: 'bl'|'facture', company, client, lignes, port, facture }
function printDocument(data) {
  const { kind, company = {}, client, lignes = [], port = 0, facture, commande } = data;
  const cur = company.currency || "XOF";
  const fmt = (v) => lecygne.fmtAmount(v, cur);
  const isFacture = kind === "facture";

  const ht = lignes.reduce((s, l) => s + Number(l.montant || 0), 0) + Number(port || 0);
  const taux = Number(facture ? facture.taux_tva : (company.vat_rate != null ? company.vat_rate : 18));
  const tva = ht * taux / 100;
  const ttc = ht + tva;

  const docTitle = isFacture ? "FACTURE" : "BON DE LIVRAISON";
  const docNo = isFacture ? (facture && facture.no_facture) : (commande && (commande.no_bl || ("BL-" + commande.no_commande)));
  const docDate = lecygne.fmtDate(isFacture ? (facture && facture.date_facture) : (commande && commande.date_commande)) ;

  const rows = lignes.map((l) => `
    <tr>
      <td>${_esc(l.article ? l.article.nom_article : ("#" + l.ref_article))}</td>
      <td>${_esc(l.service ? l.service.nom_service : ("#" + l.code_service))}</td>
      <td class="r">${_esc(l.quantite)}</td>
      <td class="r">${_esc(fmt(l.prix_unitaire))}</td>
      <td class="r">${_esc(fmt(l.montant))}</td>
    </tr>`).join("");

  const totalsRows = isFacture
    ? `<div class="row"><span>Total HT</span><span>${fmt(ht)}</span></div>
       <div class="row"><span>TVA ${taux} %</span><span>${fmt(tva)}</span></div>
       <div class="grand"><span>Total TTC</span><span>${fmt(ttc)}</span></div>`
    : `<div class="grand"><span>Total</span><span>${fmt(ht)}</span></div>`;

  const logo = company.logo_url
    ? `<img src="${_esc(company.logo_url)}" alt="logo" style="height:54px;object-fit:contain" />`
    : `<div style="font-size:34px">⚜</div>`;

  const fiscal = [company.ninea ? "NINEA : " + company.ninea : "", company.rccm ? "RCCM : " + company.rccm : ""]
    .filter(Boolean).join(" · ");
  const coords = [company.address, company.city, company.phone, company.email].filter(Boolean).join(" · ");

  const html = `<!DOCTYPE html><html lang="fr"><head><meta charset="utf-8">
<title>${_esc(docTitle)} ${_esc(docNo || "")}</title>
<style>
  *{box-sizing:border-box;font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;}
  body{margin:0;padding:32px;color:#1c2128;font-size:13px;}
  .head{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid ${_esc(company.primary_color || "#1d6fb8")};padding-bottom:14px;margin-bottom:18px;}
  .head .co{font-size:18px;font-weight:700;}
  .head .meta{font-size:11px;color:#5b626c;margin-top:4px;line-height:1.5;}
  .doc{text-align:right;}
  .doc h1{font-size:20px;margin:0;color:${_esc(company.primary_color || "#1d6fb8")};}
  .doc .sub{font-size:12px;color:#5b626c;margin-top:6px;line-height:1.6;}
  .to{margin:8px 0 18px;font-size:12px;}
  .to b{font-size:13px;}
  table{width:100%;border-collapse:collapse;margin-top:8px;}
  th{text-align:left;font-size:11px;color:#5b626c;border-bottom:1px solid #cfd2d8;padding:6px 8px;}
  td{padding:7px 8px;border-bottom:1px solid #eceef1;}
  .r{text-align:right;font-variant-numeric:tabular-nums;}
  .totals{display:flex;justify-content:flex-end;margin-top:14px;}
  .totals .box{width:260px;}
  .row{display:flex;justify-content:space-between;padding:4px 0;color:#5b626c;}
  .grand{display:flex;justify-content:space-between;padding:8px 0;border-top:1px solid #cfd2d8;font-weight:700;font-size:15px;}
  .foot{margin-top:40px;font-size:11px;color:#8a909a;text-align:center;}
  @media print{ body{padding:0;} .noprint{display:none;} }
  .noprint{margin-bottom:16px;}
  .btn{padding:8px 16px;border:1px solid #1d6fb8;background:#1d6fb8;color:#fff;border-radius:6px;cursor:pointer;font-size:13px;}
</style></head><body>
  <div class="noprint"><button class="btn" onclick="window.print()">Imprimer / Enregistrer en PDF</button></div>
  <div class="head">
    <div>
      <div style="display:flex;align-items:center;gap:12px">${logo}<div class="co">${_esc(company.display_name || "Le Cygne")}</div></div>
      <div class="meta">${_esc(company.legal_name || "")}<br>${_esc(coords)}<br>${_esc(fiscal)}</div>
    </div>
    <div class="doc">
      <h1>${_esc(docTitle)}</h1>
      <div class="sub">N° ${_esc(docNo || "—")}<br>Date : ${_esc(docDate)}</div>
    </div>
  </div>
  <div class="to">Client :<br><b>${_esc(_clientName(client))}</b>${client && client.adresse ? "<br>" + _esc(client.adresse) : ""}${client && client.ville ? " · " + _esc(client.ville) : ""}</div>
  <table>
    <thead><tr><th>Article</th><th>Service</th><th class="r">Qté</th><th class="r">P.U.</th><th class="r">Montant</th></tr></thead>
    <tbody>${rows || '<tr><td colspan="5" style="text-align:center;color:#8a909a;padding:18px">Aucune ligne</td></tr>'}</tbody>
  </table>
  <div class="totals"><div class="box">${totalsRows}</div></div>
  <div class="foot">${_esc(company.display_name || "Le Cygne")} — Merci de votre confiance.</div>
</body></html>`;

  const w = window.open("", "_blank", "width=820,height=900");
  if (!w) { alert("Veuillez autoriser les fenêtres pop-up pour imprimer."); return; }
  w.document.open(); w.document.write(html); w.document.close();
}

// ---- Relances d'impayés (relevé par client, une page par client) -----
// groups = [{ client, factures:[{no_facture,date_facture,montant_ttc,deja_paye,reste_a_payer}], total }]
function printRelances(data) {
  const { company = {}, groups = [] } = data;
  const cur = company.currency || "XOF";
  const fmt = (v) => lecygne.fmtAmount(v, cur);
  const today = lecygne.fmtDate(new Date().toISOString().slice(0, 10));

  const logo = company.logo_url
    ? `<img src="${_esc(company.logo_url)}" alt="logo" style="height:48px;object-fit:contain" />`
    : `<div style="font-size:30px">⚜</div>`;
  const coords = [company.address, company.city, company.phone, company.email].filter(Boolean).join(" · ");

  const pages = groups.map((g) => {
    const lines = g.factures.map((f) => `
      <tr>
        <td>${_esc(f.no_facture)}</td>
        <td>${_esc(lecygne.fmtDate(f.date_facture))}</td>
        <td class="r">${_esc(fmt(f.montant_ttc))}</td>
        <td class="r">${_esc(fmt(f.deja_paye))}</td>
        <td class="r"><b>${_esc(fmt(f.reste_a_payer))}</b></td>
      </tr>`).join("");
    return `
    <section class="page">
      <div class="head">
        <div><div style="display:flex;align-items:center;gap:10px">${logo}<div class="co">${_esc(company.display_name || "Le Cygne")}</div></div>
          <div class="meta">${_esc(coords)}</div></div>
        <div class="doc"><h1>RELANCE</h1><div class="sub">Le ${_esc(today)}</div></div>
      </div>
      <div class="to">À l'attention de :<br><b>${_esc(_clientName(g.client))}</b>${g.client && g.client.adresse ? "<br>" + _esc(g.client.adresse) : ""}${g.client && g.client.ville ? " · " + _esc(g.client.ville) : ""}</div>
      <p class="msg">Sauf erreur de notre part, les factures suivantes restent impayées à ce jour. Nous vous remercions de bien vouloir procéder à leur règlement.</p>
      <table>
        <thead><tr><th>Facture</th><th>Date</th><th class="r">TTC</th><th class="r">Déjà payé</th><th class="r">Reste dû</th></tr></thead>
        <tbody>${lines}</tbody>
      </table>
      <div class="totals"><div class="box"><div class="grand"><span>Total dû</span><span>${_esc(fmt(g.total))}</span></div></div></div>
      <div class="foot">${_esc(company.display_name || "Le Cygne")}${company.ninea ? " · NINEA " + _esc(company.ninea) : ""}</div>
    </section>`;
  }).join("");

  const html = `<!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Relances impayés</title>
<style>
  *{box-sizing:border-box;font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;}
  body{margin:0;color:#1c2128;font-size:13px;}
  .page{padding:32px;min-height:96vh;page-break-after:always;}
  .head{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid ${_esc(company.primary_color || "#1d6fb8")};padding-bottom:12px;margin-bottom:16px;}
  .co{font-size:17px;font-weight:700;} .meta{font-size:11px;color:#5b626c;margin-top:4px;}
  .doc{text-align:right;} .doc h1{margin:0;font-size:20px;color:${_esc(company.primary_color || "#1d6fb8")};} .doc .sub{font-size:12px;color:#5b626c;margin-top:4px;}
  .to{margin:6px 0 12px;font-size:12px;} .msg{font-size:12px;color:#5b626c;margin-bottom:14px;}
  table{width:100%;border-collapse:collapse;} th{text-align:left;font-size:11px;color:#5b626c;border-bottom:1px solid #cfd2d8;padding:6px 8px;}
  td{padding:7px 8px;border-bottom:1px solid #eceef1;} .r{text-align:right;font-variant-numeric:tabular-nums;}
  .totals{display:flex;justify-content:flex-end;margin-top:14px;} .totals .box{width:240px;}
  .grand{display:flex;justify-content:space-between;padding:8px 0;border-top:1px solid #cfd2d8;font-weight:700;font-size:15px;}
  .foot{margin-top:30px;font-size:11px;color:#8a909a;text-align:center;}
  @media print{ .noprint{display:none;} } .noprint{padding:14px 32px 0;}
  .btn{padding:8px 16px;border:1px solid #1d6fb8;background:#1d6fb8;color:#fff;border-radius:6px;cursor:pointer;font-size:13px;}
</style></head><body>
  <div class="noprint"><button class="btn" onclick="window.print()">Imprimer / Enregistrer en PDF</button></div>
  ${pages || '<section class="page"><p>Aucun impayé.</p></section>'}
</body></html>`;

  const w = window.open("", "_blank", "width=820,height=900");
  if (!w) { alert("Veuillez autoriser les fenêtres pop-up pour imprimer."); return; }
  w.document.open(); w.document.write(html); w.document.close();
}

window.printDocument = printDocument;
window.printRelances = printRelances;
