const reportModel = require('../models/reportModel');
const { generatePdf } = require('../utils/pdfGenerator');
const { generateExcel } = require('../utils/excelGenerator');


exports.salesReport = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getSalesReport(start, end);
  res.json(data);
};

exports.purchaseReport = async (req, res) => {
  const { start, end } = req.query;

  if (!start || !end) {
    return res.status(400).json({ error: "Start and end dates are required" });
  }

  try {
    const [rows] = await reportModel.getPurchaseReport(start, end);
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

exports.profitLossReport = async (req, res) => {
  const { start, end } = req.query;

  const [dateRangeData, lifetimeData] = await Promise.all([
    reportModel.getProfitLossReport(start, end),
    reportModel.getProfitLossReport() // lifetime
  ]);

  const format = (data) => {
    const sales = parseFloat(data.total_sales) || 0;
    const purchases = parseFloat(data.total_purchases) || 0;
    const expenses = parseFloat(data.total_expenses) || 0;

    const gross_profit = sales - purchases;
    const net_profit = gross_profit - expenses;

    return {
      total_sales: sales,
      total_purchases: purchases,
      total_expenses: expenses,
      gross_profit,
      net_profit
    };
  };

  res.json({
    date_range: format(dateRangeData),
    lifetime: format(lifetimeData)
  });
};

exports.expenseReport = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getExpenseReport(start, end);
  res.json(data);
};
exports.itemSummary = async (req, res) => {
  const data = await reportModel.getItemSummary();
  res.json(data);
};
exports.customerSummary = async (req, res) => {
  const data = await reportModel.getCustomerSummary();
  res.json(data);
};
exports.supplierSummary = async (req, res) => {
  const data = await reportModel.getSupplierSummary();
  res.json(data);
};

// Shared headers
const salesHeaders = ['id', 'customer_id', 'item_id', 'quantity', 'price', 'total', 'sale_date'];
const purchaseHeaders = ['id', 'supplier_id', 'item_id', 'quantity', 'price', 'total', 'purchase_date'];
const expenseHeaders = ['id', 'title', 'amount', 'description', 'expense_date'];
const profitHeaders = ['total_sales', 'total_purchases', 'total_expenses', 'profit'];

// Sales PDF/Excel
exports.exportSalesPdf = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getSalesReport(start, end);
  generatePdf(res, 'Sales Report', salesHeaders, data);
};

exports.exportSalesExcel = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getSalesReport(start, end);
  await generateExcel(res, 'Sales Report', salesHeaders, data);
};

// Purchase PDF/Excel
exports.exportPurchasePdf = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getPurchaseReport(start, end);
  generatePdf(res, 'Purchase Report', purchaseHeaders, data);
};

exports.exportPurchaseExcel = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getPurchaseReport(start, end);
  await generateExcel(res, 'Purchase Report', purchaseHeaders, data);
};

// Expense PDF/Excel
exports.exportExpensePdf = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getExpenseReport(start, end);
  generatePdf(res, 'Expense Report', expenseHeaders, data);
};

exports.exportExpenseExcel = async (req, res) => {
  const { start, end } = req.query;
  const data = await reportModel.getExpenseReport(start, end);
  await generateExcel(res, 'Expense Report', expenseHeaders, data);
};

// Profit/Loss PDF/Excel
exports.exportProfitLossPdf = async (req, res) => {
  const { start, end } = req.query;
  const summary = await reportModel.getProfitLossReport(start, end);
  const profit = summary.total_sales - (summary.total_purchases + summary.total_expenses);
  generatePdf(res, 'Profit Loss Report', profitHeaders, [{ ...summary, profit }]);
};

exports.exportProfitLossExcel = async (req, res) => {
  const { start, end } = req.query;
  const summary = await reportModel.getProfitLossReport(start, end);
  const profit = summary.total_sales - (summary.total_purchases + summary.total_expenses);
  await generateExcel(res, 'Profit Loss Report', profitHeaders, [{ ...summary, profit }]);
};

exports.salesItemProfitSummary = async (req, res) => {
  const { start, end, status } = req.query;
  try {
    const [rows] = await reportModel.getSalesItemProfitSummary(start, end, status);
    res.json(rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: err.message });
  }
};

exports.unsoldItemsReport = async (req, res) => {
  const { start, end } = req.query;
  try {
    const [rows] = await reportModel.getUnsoldItems(start, end);
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};


exports.invoiceProfitReport = async (req, res) => {
  const { start, end } = req.query;
  try {
    const data = await reportModel.getInvoiceProfitReport(start, end);
    res.json(data);
  } catch (err) {
    console.error("Invoice Profit Report Error:", err);
    res.status(500).json({ error: err.message });
  }
};

exports.getItemValuationReport = async (req, res) => {
  const toNull = (v) => (v === 'null' || v === '' || v === undefined ? null : v);

  const category = toNull(req.query.category);
  const brand = toNull(req.query.brand);
  const item = toNull(req.query.item);

  try {
    const data = await require('../models/reportModel')
      .fetchItemValuationReport({ category, brand, item });
    res.json(data);
  } catch (error) {
    console.error('Error fetching item valuation report:', error.message);
    res.status(500).json({ error: 'Failed to fetch item valuation report' });
  }
};