// ═══════════════════════════════════════════════════════════════
//  Export utilities (Excel + PDF)
// ═══════════════════════════════════════════════════════════════

const XLSX_COLS = [
  'שם הרכז/ת','שם הרשומ"ק','אשכול פעילות','שם פעילות','מספר יחידות','מתודה',
  'אוכלוסיה מתוכננת','מספר משתתפים משוער','מגדר','זרם קהילתי','מטרות','יעדים',
  'רבעון לביצוע','תקציב פעילות מתוכנן','תקציב כיבוד מתוכנן','תקציב פרסום מתוכנן',
  'אישור עקרוני הרשות החרדית','שם מלא של הספק כפי שיופיע בחשבונית',
  'תעודות/רשיונות ספק','סילבוס וחומרים נלווים','מדדי הצלחה','תאריך התחלה','תאריך סיום',
  'טיוטת פרסום לאישור','עלות הפעילות','עלות הכיבוד','עלות הפרסום',
  'תיאום תוכן עם משרדי ממשלה','אישור משפטי וחשבי - פעילות 3.3',
  'אישור ביצוע הרשות החרדית','הטמעת הפעילות ביומן המשותף',
  'מספר יחידות שהושלמו','סה"כ משתתפים בפועל','מספר מפגשים',
  'תאריך מפגש ראשון','תאריך מפגש אחרון','שם ספק 1','שם ספק 2','שם ספק 3',
  'דירוג ספק 1','דירוג ספק 2','דירוג ספק 3','תקציב פרסום','תקציב כיבוד',
  'חוות דעת מביצוע פעילות','הערות','סך תקציב שמומש בפועל',
  'אסמכתאות לתשלום','אישור תשלום'
];

window.activityToRow = function(a, state) {
  const coord = state.users.find(u => u.id === a.coordinatorId);
  const auth = state.authorities.find(x => x.id === a.authorityId);
  const cluster = window.clusterById(a.cluster);
  return [
    coord?.name || '',
    auth?.name || '',
    cluster?.name || '',
    a.activityName || '',
    a.units || '',
    a.method || '',
    a.targetPopulation || '',
    a.plannedParticipants || '',
    a.gender || '',
    a.communityStream || '',
    a.goals || '',
    a.objectives || '',
    a.quarter || '',
    a.plannedBudget || '',
    a.plannedCatering || '',
    a.plannedPublicity || '',
    a.principleApproval === 'approved' ? 'אושר עקרוני' : a.principleApproval === 'rejected' ? 'נדחה' : a.principleApproval === 'pending' ? 'ממתין' : '',
    a.supplierName || '',
    (a.supplierCerts || []).join(' '),
    a.syllabus || '',
    a.successMetrics || '',
    a.startDate || '',
    a.endDate || '',
    a.publicityDraft || '',
    a.actualActivityCost || '',
    a.actualCatering || '',
    a.actualPublicity || '',
    a.govCoordination || '',
    a.legalAccountingApproval || '',
    a.executionApproval === 'approved' ? 'אושר לביצוע' : '',
    a.calendarIntegration ? 'כן' : '',
    a.completedUnits || '',
    a.actualParticipants || '',
    a.meetingsCount || '',
    a.firstMeetingDate || '',
    a.lastMeetingDate || '',
    a.suppliers?.[0]?.name || '',
    a.suppliers?.[1]?.name || '',
    a.suppliers?.[2]?.name || '',
    a.suppliers?.[0]?.rating || '',
    a.suppliers?.[1]?.rating || '',
    a.suppliers?.[2]?.rating || '',
    a.actualPublicity || '',
    a.actualCatering || '',
    a.opinionReview || '',
    a.notes || '',
    a.totalActualBudget || '',
    (a.paymentEvidence || []).join(' '),
    a.paymentApproval === 'approved' ? 'אושר לתשלום' : a.paymentApproval === 'pending' ? 'טרם אושר' : ''
  ];
};

window.exportAllToExcel = function(state) {
  const wb = XLSX.utils.book_new();
  const headers = ['אישור עקרוני', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
                   'אישור ביצוע', '', '', '', '', '', '', '', '', '',
                   'לטיפול הרכזים הארציים', '', '', '',
                   'אישור תשלום', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
  const rows = [ headers, XLSX_COLS, ...state.activities.map(a => window.activityToRow(a, state)) ];
  const ws = XLSX.utils.aoa_to_sheet(rows);
  ws['!rtl'] = true;
  XLSX.utils.book_append_sheet(wb, ws, 'תכנית עבודה');
  XLSX.writeFile(wb, `תכנית-עבודה-ארצית-${new Date().toISOString().slice(0,10)}.xlsx`);
};

window.exportAuthorityToExcel = function(state, authId) {
  const auth = state.authorities.find(a => a.id === authId);
  const activities = state.activities.filter(a => a.authorityId === authId);
  const wb = XLSX.utils.book_new();
  const headers = ['אישור עקרוני', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
                   'אישור ביצוע', '', '', '', '', '', '', '', '', '',
                   'לטיפול הרכזים הארציים', '', '', '',
                   'אישור תשלום', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
  const rows = [ headers, XLSX_COLS, ...activities.map(a => window.activityToRow(a, state)) ];
  const ws = XLSX.utils.aoa_to_sheet(rows);
  ws['!rtl'] = true;
  XLSX.utils.book_append_sheet(wb, ws, 'תכנית עבודה');
  XLSX.writeFile(wb, `תכנית-עבודה-${auth.name}-${new Date().toISOString().slice(0,10)}.xlsx`);
};

window.exportActivitiesToExcel = function(activities, state) {
  const wb = XLSX.utils.book_new();
  const headers = ['אישור עקרוני', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
                   'אישור ביצוע', '', '', '', '', '', '', '', '', '',
                   'לטיפול הרכזים הארציים', '', '', '',
                   'אישור תשלום', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
  const rows = [ headers, XLSX_COLS, ...activities.map(a => window.activityToRow(a, state)) ];
  const ws = XLSX.utils.aoa_to_sheet(rows);
  ws['!rtl'] = true;
  XLSX.utils.book_append_sheet(wb, ws, 'תכנית עבודה');
  XLSX.writeFile(wb, `תכנית-עבודה-${new Date().toISOString().slice(0,10)}.xlsx`);
};

window.generatePaymentExcel = function(activities, state) {
  if (!activities.length) return;
  const auth = state.authorities.find(a => a.id === activities[0].authorityId);
  const wb = XLSX.utils.book_new();
  const headers = ['אישור עקרוני', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
                   'אישור ביצוע', '', '', '', '', '', '', '', '', '',
                   'לטיפול הרכזים הארציים', '', '', '',
                   'אישור תשלום', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
  const rows = [ headers, XLSX_COLS, ...activities.map(a => window.activityToRow(a, state)) ];
  const ws = XLSX.utils.aoa_to_sheet(rows);
  ws['!rtl'] = true;
  XLSX.utils.book_append_sheet(wb, ws, 'דרישת תשלום');
  const fname = `דרישת-תשלום-${auth?.name || ''}-${new Date().toISOString().slice(0,10)}.xlsx`;
  XLSX.writeFile(wb, fname);
};

window.generatePaymentPDF = async function(activities, state) {
  const el = document.getElementById('payment-preview');
  if (!el) {
    // Create a temporary hidden element
    const tmp = document.createElement('div');
    tmp.style.position = 'fixed';
    tmp.style.top = '-9999px';
    tmp.style.right = '0';
    tmp.style.width = '794px';  // A4 width
    tmp.style.background = 'white';
    document.body.appendChild(tmp);
    const root = ReactDOM.createRoot(tmp);
    root.render(React.createElement(window.PaymentPreview, { activities, state }));
    await new Promise(r => setTimeout(r, 400));

    const target = tmp.querySelector('#payment-preview');
    const canvas = await html2canvas(target, { scale: 2, useCORS: true, background: '#ffffff' });
    const img = canvas.toDataURL('image/png');
    const pdf = new window.jspdf.jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' });
    const pdfW = pdf.internal.pageSize.getWidth();
    const pdfH = pdf.internal.pageSize.getHeight();
    const imgH = canvas.height * pdfW / canvas.width;

    let pos = 0;
    if (imgH <= pdfH) {
      pdf.addImage(img, 'PNG', 0, 0, pdfW, imgH);
    } else {
      // Multi-page
      let remaining = imgH;
      while (remaining > 0) {
        pdf.addImage(img, 'PNG', 0, pos, pdfW, imgH);
        remaining -= pdfH;
        pos -= pdfH;
        if (remaining > 0) pdf.addPage();
      }
    }

    const auth = state.authorities.find(a => a.id === activities[0].authorityId);
    pdf.save(`דרישת-תשלום-${auth?.name}-${new Date().toISOString().slice(0,10)}.pdf`);

    root.unmount();
    document.body.removeChild(tmp);
  } else {
    const canvas = await html2canvas(el, { scale: 2, useCORS: true, background: '#ffffff' });
    const img = canvas.toDataURL('image/png');
    const pdf = new window.jspdf.jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' });
    const pdfW = pdf.internal.pageSize.getWidth();
    const imgH = canvas.height * pdfW / canvas.width;
    pdf.addImage(img, 'PNG', 0, 0, pdfW, imgH);
    const auth = state.authorities.find(a => a.id === activities[0].authorityId);
    pdf.save(`דרישת-תשלום-${auth?.name}-${new Date().toISOString().slice(0,10)}.pdf`);
  }
};
