const PDFDocument = require('pdfkit');

exports.generatePdf = (res, title, headers, data) => {
  const doc = new PDFDocument({ margin: 30, size: 'A4' });
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `attachment; filename=${title}.pdf`);
  doc.pipe(res);

  doc.fontSize(18).text(title, { align: 'center' }).moveDown(1);
  doc.fontSize(12);

  // Headers
  headers.forEach((header, i) => {
    doc.text(header, { continued: i !== headers.length - 1, width: 100 });
  });
  doc.moveDown(0.5);

  // Rows
  data.forEach(row => {
    headers.forEach((key, i) => {
      doc.text(String(row[key] || ''), { continued: i !== headers.length - 1, width: 100 });
    });
    doc.moveDown(0.5);
  });

  doc.end();
};
