const express = require('express');
const router = express.Router();
const htmlPdf = require('html-pdf');
const fs = require('fs');
const mustache = require('mustache');
const path = require('path');
const { db } = require('../config/dbConfig');

router.post('/api/generate-invoice', async (req, res) => {
  try {
    const orderDetails = req.body;

    // Validate required data
    if (!orderDetails || typeof orderDetails !== 'object') {
      throw new Error('Invalid order details');
    }

    // Parse order details if they're strings
    let cartItems;
    try {
      if (typeof orderDetails.order_details === 'string') {
        cartItems = JSON.parse(orderDetails.order_details);
      } else if (Array.isArray(orderDetails.order_details)) {
        cartItems = orderDetails.order_details;
      } else if (orderDetails.items) {
        cartItems = Array.isArray(orderDetails.items) ? orderDetails.items : JSON.parse(orderDetails.items);
      } else {
        throw new Error('No valid order details found');
      }
    } catch (e) {
      throw new Error('Failed to parse order details: ' + e.message);
    }

    // Ensure cartItems is an array
    if (!Array.isArray(cartItems)) {
      throw new Error('Cart items must be an array');
    }

    // Format cart items
    cartItems = cartItems.map(item => ({
      name: String(item.name || ''),
      code: String(item.code || ''),
      quantity: Number(item.quantity) || 0,
      price: Number(item.price) || 0,
      subtotal: Number(item.quantity * item.price) || 0
    }));

    const templatePath = path.join(__dirname, '../template/Invoice.html');
    const logoPath = path.join(__dirname, '../assets/Logo.png');
    const qrPath = path.join(__dirname, '../assets/download.png');

    if (!fs.existsSync(templatePath)) {
      throw new Error(`Invoice template not found at: ${templatePath}`);
    }

    const template = fs.readFileSync(templatePath, 'utf-8');
    const logoBase64 = fs.existsSync(logoPath) ? 
      `data:image/png;base64,${fs.readFileSync(logoPath).toString('base64')}` : '';
    const qrBase64 = fs.existsSync(qrPath) ? 
      `data:image/png;base64,${fs.readFileSync(qrPath).toString('base64')}` : '';

    // Calculate totals using validated cart items
    const subtotal = cartItems.reduce((sum, item) => sum + (item.quantity * item.price), 0);
    const packageFee = Number(orderDetails.packageFee) || 100.00;
    const totalAmount = subtotal + packageFee;

    const invoiceData = {
      invoiceNumber: orderDetails.enquiryId,
      invoiceDate: orderDetails.orderDate || new Date().toISOString(),
      logoUrl: logoBase64,
      qrCodeUrl: qrBase64,
      upiId: process.env.UPI_ID || "your-upi-id@bank",
      customer: {
        company: orderDetails.customerName || orderDetails.customer_name || '',
        number: orderDetails.mobile || '',
        address1: orderDetails.district || '',
        address2: orderDetails.state || ''
      },
      products: cartItems.map((item, index) => ({
        index: index + 1,
        name: item.name,
        code: item.code,
        quantity: item.quantity,
        price: parseFloat(item.price).toFixed(2),
        priceTotal: (item.quantity * item.price).toFixed(2)
      })),
      totalNetAmount: subtotal.toFixed(2),
      packageFee: packageFee.toFixed(2),
      totalAmount: totalAmount.toFixed(2)
    };

    const buffer = await new Promise((resolve, reject) => {
      htmlPdf.create(mustache.render(template, invoiceData), {
        format: 'A4',
        border: {
          top: "20px",
          right: "20px",
          bottom: "20px",
          left: "20px"
        },
        timeout: 30000,
        renderDelay: 1000
      }).toBuffer((err, buffer) => {
        if (err) reject(err);
        else resolve(buffer);
      });
    });

    // Store PDF in database
    await db.query('UPDATE orders SET invoice_pdf = ? WHERE enquiry_id = ?', 
      [buffer, orderDetails.enquiryId]);

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment; filename=Invoice_${orderDetails.enquiryId}.pdf`,
      'Content-Length': buffer.length,
      'Cache-Control': 'no-cache'
    });

    return res.send(buffer);

  } catch (error) {
    console.error('Invoice Generation Error:', error);
    return res.status(500).json({
      success: false,
      message: 'Error generating invoice: ' + error.message
    });
  }
});

router.get('/api/get-invoice/:orderId', async (req, res) => {
  try {
      const { orderId } = req.params;

      // Use promise-based query
      const [results] = await new Promise((resolve, reject) => {
          db.query('SELECT invoice_pdf FROM orders WHERE enquiry_id = ?', [orderId], (err, results) => {
              if (err) reject(err);
              resolve(results);
          });
      });

      if (!results || !results.invoice_pdf) {
          return res.status(404).json({
              success: false,
              message: 'PDF not found'
          });
      }

      const pdfBuffer = Buffer.from(results.invoice_pdf);

      res.set({
          'Content-Type': 'application/pdf',
          'Content-Length': pdfBuffer.length,
          'Content-Disposition': `attachment; filename=Invoice_${orderId}.pdf`,
          'Cache-Control': 'no-cache'
      });

      return res.send(pdfBuffer);

  } catch (error) {
      console.error('Error retrieving PDF:', error);
      return res.status(500).json({
          success: false,
          message: 'Error retrieving PDF'
      });
  }
});

module.exports = router;