const ejs = require('ejs');
const path = require('path');
const pdf = require('html-pdf');
const fs = require('fs');
const { logger } = require('nodejs-log-agent');

const generatePDF = async (data) => {
    try {
        // Render file template.ejs dengan data dinamis
        const templatePath = path.join(__dirname, `../views/invoice.ejs`);
        const htmlContent = await ejs.renderFile(templatePath, data);

        // Get current date for directory structure
        const now = new Date();
        const year = now.getFullYear();
        // Month is 0-indexed, so add 1 and pad with '0' if less than 10
        const month = String(now.getMonth() + 1).padStart(2, '0');
        // Day of the month, pad with '0' if less than 10
        const day = String(now.getDate()).padStart(2, '0');

        // Construct the directory path: invoice/tahun/bulan/tanggal
        const dailyInvoiceDir = path.join(__dirname, `../public/invoice`, String(year), month, day);

        // Ensure the directory exists. If not, create it recursively.
        await fs.promises.mkdir(dailyInvoiceDir, { recursive: true });

        // Construct the full file path
        const fileName = `invoice-${data.inv_id}-${data.inv_status}.pdf`;
        const filePath = path.join(dailyInvoiceDir, fileName);

        return new Promise((resolve, reject) => {
            // Konfigurasi tambahan untuk html-pdf
            const options = {
                format: 'A4',
                border: {
                    top: "20px",
                    right: "20px",
                    bottom: "20px",
                    left: "20px"
                }
            };

            pdf.create(htmlContent, options).toFile(filePath, function (err, result) {
                if (err) {
                    reject({
                        status: false,
                        message: 'Failed to generate PDF',
                        error: err
                    });
                } else {
                    resolve({
                        status: true,
                        message: 'PDF generated successfully',
                        pdfName: fileName, // Return just the file name
                        pdfPath: `/invoice/${year}/${month}/${day}/${fileName}`// Return the full path for reference
                    });
                }
            });
        });
    } catch (error) {
        logger.error("function PDF Generate", { message : error.message , stack : error.stack, error : error });
        throw new Error(error.message);
    }
}

module.exports = { generatePDF };