const PDFDocument = require('pdfkit');
const pool = require('../config/db');

async function getDashboardStats(req, res) {
  try {
    const [[productStats]] = await pool.query(`
      SELECT
        COUNT(*) AS total_products,
        COALESCE(SUM(quantity), 0) AS total_items,
        COALESCE(SUM(quantity * unit_price), 0) AS total_value,
        SUM(CASE WHEN quantity <= min_stock_level THEN 1 ELSE 0 END) AS low_stock_count
      FROM products
    `);

    const [[categoryStats]] = await pool.query('SELECT COUNT(*) AS total_categories FROM categories');

    const [[movementStats]] = await pool.query(`
      SELECT
        SUM(CASE WHEN type = 'in' THEN 1 ELSE 0 END) AS stock_in_count,
        SUM(CASE WHEN type = 'out' THEN 1 ELSE 0 END) AS stock_out_count
      FROM stock_movements
      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    `);

    const [recentMovements] = await pool.query(`
      SELECT sm.*, p.name AS product_name, p.sku
      FROM stock_movements sm
      JOIN products p ON sm.product_id = p.id
      ORDER BY sm.created_at DESC LIMIT 5
    `);

    const [lowStockProducts] = await pool.query(`
      SELECT p.*, c.name AS category_name
      FROM products p
      LEFT JOIN categories c ON p.category_id = c.id
      WHERE p.quantity <= p.min_stock_level
      ORDER BY p.quantity ASC LIMIT 10
    `);

    res.json({
      stats: {
        ...productStats,
        ...categoryStats,
        ...movementStats,
      },
      recentMovements,
      lowStockProducts,
    });
  } catch (error) {
    console.error('Dashboard stats error:', error);
    res.status(500).json({ message: 'Server error' });
  }
}

async function getInventoryReport(req, res) {
  try {
    const [products] = await pool.query(`
      SELECT p.*, c.name AS category_name,
        (p.quantity * p.unit_price) AS total_value
      FROM products p
      LEFT JOIN categories c ON p.category_id = c.id
      ORDER BY c.name, p.name
    `);

    const [[totals]] = await pool.query(`
      SELECT
        COUNT(*) AS total_products,
        COALESCE(SUM(quantity), 0) AS total_quantity,
        COALESCE(SUM(quantity * unit_price), 0) AS total_value
      FROM products
    `);

    res.json({ products, totals, generatedAt: new Date().toISOString() });
  } catch (error) {
    console.error('Inventory report error:', error);
    res.status(500).json({ message: 'Server error' });
  }
}

async function getLowStockReport(req, res) {
  try {
    const [products] = await pool.query(`
      SELECT p.*, c.name AS category_name,
        (p.min_stock_level - p.quantity) AS shortage
      FROM products p
      LEFT JOIN categories c ON p.category_id = c.id
      WHERE p.quantity <= p.min_stock_level
      ORDER BY shortage DESC
    `);

    res.json({ products, count: products.length, generatedAt: new Date().toISOString() });
  } catch (error) {
    console.error('Low stock report error:', error);
    res.status(500).json({ message: 'Server error' });
  }
}

async function getMovementReport(req, res) {
  try {
    const { start_date, end_date } = req.query;

    let query = `
      SELECT sm.*, p.name AS product_name, p.sku, u.name AS user_name
      FROM stock_movements sm
      JOIN products p ON sm.product_id = p.id
      LEFT JOIN users u ON sm.user_id = u.id
      WHERE 1=1
    `;
    const params = [];

    if (start_date) {
      query += ' AND sm.created_at >= ?';
      params.push(start_date);
    }

    if (end_date) {
      query += ' AND sm.created_at <= ?';
      params.push(`${end_date} 23:59:59`);
    }

    query += ' ORDER BY sm.created_at DESC';

    const [movements] = await pool.query(query, params);

    const summary = movements.reduce(
      (acc, m) => {
        if (m.type === 'in') acc.total_in += m.quantity;
        else if (m.type === 'out') acc.total_out += m.quantity;
        acc.total_movements += 1;
        return acc;
      },
      { total_in: 0, total_out: 0, total_movements: 0 }
    );

    res.json({ movements, summary, generatedAt: new Date().toISOString() });
  } catch (error) {
    console.error('Movement report error:', error);
    res.status(500).json({ message: 'Server error' });
  }
}

async function downloadInventoryPdf(req, res) {
  try {
    const [products] = await pool.query(`
      SELECT p.name, p.sku, c.name AS category_name, p.quantity,
        p.unit_price, (p.quantity * p.unit_price) AS total_value
      FROM products p
      LEFT JOIN categories c ON p.category_id = c.id
      ORDER BY p.name
    `);

    const [[totals]] = await pool.query(`
      SELECT COALESCE(SUM(quantity * unit_price), 0) AS total_value FROM products
    `);

    const doc = new PDFDocument({ margin: 50 });
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=inventory-report.pdf');
    doc.pipe(res);

    doc.fontSize(20).text('Inventory Report', { align: 'center' });
    doc.fontSize(10).text(`Generated: ${new Date().toLocaleString()}`, { align: 'center' });
    doc.moveDown(2);

    doc.fontSize(12).text(`Total Products: ${products.length}`);
    doc.text(`Total Inventory Value: $${Number(totals.total_value).toFixed(2)}`);
    doc.moveDown();

    const tableTop = doc.y;
    const colWidths = [120, 80, 80, 60, 70, 80];
    const headers = ['Product', 'SKU', 'Category', 'Qty', 'Price', 'Value'];

    doc.font('Helvetica-Bold').fontSize(9);
    let x = 50;
    headers.forEach((h, i) => {
      doc.text(h, x, tableTop, { width: colWidths[i] });
      x += colWidths[i];
    });

    doc.font('Helvetica').fontSize(8);
    let y = tableTop + 18;

    products.forEach((p) => {
      if (y > 700) {
        doc.addPage();
        y = 50;
      }
      x = 50;
      const row = [
        p.name,
        p.sku,
        p.category_name || 'N/A',
        String(p.quantity),
        `$${Number(p.unit_price).toFixed(2)}`,
        `$${Number(p.total_value).toFixed(2)}`,
      ];
      row.forEach((cell, i) => {
        doc.text(cell, x, y, { width: colWidths[i] });
        x += colWidths[i];
      });
      y += 16;
    });

    doc.end();
  } catch (error) {
    console.error('PDF report error:', error);
    res.status(500).json({ message: 'Server error generating PDF' });
  }
}

async function downloadCsvReport(req, res) {
  try {
    const { type = 'inventory' } = req.query;

    let rows = [];
    let filename = 'report.csv';

    if (type === 'inventory') {
      const [products] = await pool.query(`
        SELECT p.name, p.sku, c.name AS category, p.quantity, p.min_stock_level,
          p.unit_price, (p.quantity * p.unit_price) AS total_value, p.supplier, p.location
        FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.name
      `);
      rows = products;
      filename = 'inventory-report.csv';
    } else if (type === 'low-stock') {
      const [products] = await pool.query(`
        SELECT p.name, p.sku, c.name AS category, p.quantity, p.min_stock_level,
          (p.min_stock_level - p.quantity) AS shortage
        FROM products p LEFT JOIN categories c ON p.category_id = c.id
        WHERE p.quantity <= p.min_stock_level ORDER BY shortage DESC
      `);
      rows = products;
      filename = 'low-stock-report.csv';
    } else if (type === 'movements') {
      const { start_date, end_date } = req.query;
      let query = `
        SELECT p.name AS product, p.sku, sm.type, sm.quantity,
          sm.previous_quantity, sm.new_quantity, sm.reason, sm.reference_no,
          u.name AS user, sm.created_at
        FROM stock_movements sm
        JOIN products p ON sm.product_id = p.id
        LEFT JOIN users u ON sm.user_id = u.id WHERE 1=1
      `;
      const params = [];
      if (start_date) { query += ' AND sm.created_at >= ?'; params.push(start_date); }
      if (end_date) { query += ' AND sm.created_at <= ?'; params.push(`${end_date} 23:59:59`); }
      query += ' ORDER BY sm.created_at DESC';
      const [movements] = await pool.query(query, params);
      rows = movements;
      filename = 'stock-movements-report.csv';
    }

    if (rows.length === 0) {
      return res.status(404).json({ message: 'No data for report' });
    }

    const headers = Object.keys(rows[0]);
    const csv = [
      headers.join(','),
      ...rows.map((row) =>
        headers.map((h) => {
          const val = row[h];
          if (val === null || val === undefined) return '';
          const str = String(val);
          return str.includes(',') || str.includes('"') ? `"${str.replace(/"/g, '""')}"` : str;
        }).join(',')
      ),
    ].join('\n');

    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
    res.send(csv);
  } catch (error) {
    console.error('CSV report error:', error);
    res.status(500).json({ message: 'Server error generating CSV' });
  }
}

module.exports = {
  getDashboardStats,
  getInventoryReport,
  getLowStockReport,
  getMovementReport,
  downloadInventoryPdf,
  downloadCsvReport,
};
