const PDFDocument = require('pdfkit');
const fs = require('fs');
const path = require('path');

function generateCertificate(learnerId, learnerName, completionDate) {
  return new Promise((resolve, reject) => {
    try {
      const filename = `certificate_${learnerId}_${Date.now()}.pdf`;
      const filepath = path.join(__dirname, '..', 'public', 'certificates', filename);

      // Ensure directory exists
      const dir = path.dirname(filepath);
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }

      const doc = new PDFDocument({
        size: 'A4',
        margin: 50
      });

      const stream = fs.createWriteStream(filepath);
      doc.pipe(stream);

      // Background color
      doc.rect(0, 0, 595.28, 841.89).fill('#f5f5f5');

      // Border
      doc.strokeColor('#1a3a5c');
      doc.lineWidth(3);
      doc.rect(40, 40, 515.28, 761.89).stroke();

      // Inner border
      doc.lineWidth(1);
      doc.rect(50, 50, 495.28, 741.89).stroke();

      // Logo/Title
      doc.fontSize(32)
        .font('Helvetica-Bold')
        .fillColor('#1a3a5c')
        .text('Connecticut Elderly Services', { align: 'center', lineGap: 5 });

      doc.fontSize(14)
        .font('Helvetica')
        .fillColor('#f0a500')
        .text('PCA Certification Training Program', { align: 'center' });

      // Certificate title
      doc.fontSize(28)
        .font('Helvetica-Bold')
        .fillColor('#1a3a5c')
        .text('Certificate of Completion', { align: 'center', lineGap: 20, y: 200 });

      // Main text
      doc.fontSize(12)
        .font('Helvetica')
        .fillColor('#333')
        .text('This is to certify that', { align: 'center' });

      doc.fontSize(18)
        .font('Helvetica-Bold')
        .fillColor('#1a3a5c')
        .text(learnerName, { align: 'center', lineGap: 10 });

      doc.fontSize(12)
        .font('Helvetica')
        .fillColor('#333')
        .text('has successfully completed the', { align: 'center' });

      doc.fontSize(14)
        .font('Helvetica-Bold')
        .fillColor('#f0a500')
        .text('Connecticut Elderly Services PCA Certification Training', { align: 'center', lineGap: 15 });

      doc.fontSize(12)
        .font('Helvetica')
        .fillColor('#333')
        .text('This certification recognizes the completion of all required modules and the successful passage of the final examination, demonstrating knowledge and commitment to providing quality personal care assistance to the elderly community.', { align: 'center', width: 400, lineGap: 10 });

      // Date
      const dateStr = new Date(completionDate).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });

      doc.fontSize(11)
        .font('Helvetica')
        .fillColor('#333')
        .text(`Completed: ${dateStr}`, { align: 'center', lineGap: 20, y: 550 });

      // Signature line
      doc.moveTo(150, 600)
        .lineTo(300, 600)
        .stroke();

      doc.fontSize(10)
        .font('Helvetica')
        .fillColor('#333')
        .text('Connecticut Department of Social Services', { align: 'center', y: 605 });

      // Certificate ID
      const certId = `CES-${learnerId}-${Math.random().toString(36).substr(2, 9).toUpperCase()}`;
      doc.fontSize(9)
        .font('Helvetica')
        .fillColor('#999')
        .text(`Certificate ID: ${certId}`, { align: 'center', y: 750 });

      doc.end();

      stream.on('finish', () => {
        resolve(`/certificates/${filename}`);
      });

      stream.on('error', reject);
    } catch (err) {
      reject(err);
    }
  });
}

module.exports = {
  generateCertificate
};
