const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { getDbPool } = require('../config/db');

const JWT_SECRET = process.env.JWT_SECRET || 'supersecretjwtkey_lssoft_2026';

function verifyToken(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ success: false, message: 'Unauthorized access.' });
  }

  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.admin = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ success: false, message: 'Invalid or expired session token.' });
  }
}

// GET /api/dashboard/stats
router.get('/stats', verifyToken, async (req, res) => {
  try {
    const filter = req.query.filter || 'monthly';
    const now = new Date();
    let start, end;
    
    const formatDate = d => {
      const offset = d.getTimezoneOffset() * 60000;
      return new Date(d.getTime() - offset).toISOString().split('T')[0];
    };
    
    switch (filter) {
      case 'weekly':
        start = new Date(now); start.setDate(start.getDate() - 6);
        end = now;
        break;
      case 'monthly':
        start = new Date(now.getFullYear(), now.getMonth(), 1);
        end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
        break;
      case 'yearly':
        start = new Date(now.getFullYear(), 0, 1);
        end = new Date(now.getFullYear(), 11, 31);
        break;
      case 'custom':
        start = req.query.startDate ? new Date(req.query.startDate) : now;
        end = req.query.endDate ? new Date(req.query.endDate) : now;
        break;
      case 'today':
      default:
        start = now;
        end = now;
        break;
    }
    
    const startStr = formatDate(start);
    const endStr = formatDate(end);
    
    const pool = getDbPool();
    if (!pool) {
      return res.json({ success: true, data: { metrics: [], charts: { trend: [], invoiceStatus: [], expenseCategories: [] } } });
    }

    // Metrics
    const [incomeRows] = await pool.query("SELECT SUM(amount) as sum FROM transactions WHERE type = 'Income' AND txn_date BETWEEN ? AND ?", [startStr, endStr]);
    const [expenseRows] = await pool.query("SELECT SUM(amount) as sum FROM transactions WHERE type = 'Expense' AND txn_date BETWEEN ? AND ?", [startStr, endStr]);
    const [customerRows] = await pool.query("SELECT COUNT(*) as count FROM customers WHERE DATE(created_at) BETWEEN ? AND ?", [startStr, endStr]);
    const [invoiceRows] = await pool.query("SELECT SUM(due_amount) as sum FROM invoices WHERE status != 'Paid' AND invoice_date BETWEEN ? AND ?", [startStr, endStr]);

    const totalIncome = incomeRows[0].sum || 0;
    const totalExpense = expenseRows[0].sum || 0;
    const newCustomers = customerRows[0].count || 0;
    const pendingInvoices = invoiceRows[0].sum || 0;
    const netProfit = totalIncome - totalExpense;

    // Charts: Income vs Expense Trend
    const [trendRows] = await pool.query(`
      SELECT txn_date, type, SUM(amount) as total
      FROM transactions 
      WHERE txn_date BETWEEN ? AND ?
      GROUP BY txn_date, type
      ORDER BY txn_date ASC
    `, [startStr, endStr]);

    // Charts: Invoice Status Breakdown
    const [statusRows] = await pool.query(`
      SELECT status, COUNT(*) as count
      FROM invoices
      WHERE invoice_date BETWEEN ? AND ?
      GROUP BY status
    `, [startStr, endStr]);

    // Charts: Expense Breakdown
    const [expenseCatRows] = await pool.query(`
      SELECT c.name as category, SUM(t.amount) as total
      FROM transactions t
      JOIN txn_categories c ON t.category_id = c.id
      WHERE t.type = 'Expense' AND t.txn_date BETWEEN ? AND ?
      GROUP BY c.name
    `, [startStr, endStr]);

    const metrics = [
      { label: 'Total Income', value: '৳' + Number(totalIncome).toLocaleString(), icon: 'heroicons:arrow-trending-up', trend: 'up', change: filter },
      { label: 'Total Expense', value: '৳' + Number(totalExpense).toLocaleString(), icon: 'heroicons:arrow-trending-down', trend: 'down', change: filter },
      { label: 'Net Profit', value: '৳' + Number(netProfit).toLocaleString(), icon: 'heroicons:currency-dollar', trend: netProfit >= 0 ? 'up' : 'down', change: filter },
      { label: 'New Customers', value: newCustomers.toString(), icon: 'heroicons:users', trend: 'up', change: filter },
      { label: 'Pending Invoices', value: '৳' + Number(pendingInvoices).toLocaleString(), icon: 'heroicons:document-text', trend: 'neutral', change: filter },
    ];

    res.json({
      success: true,
      data: {
        metrics,
        charts: {
          trend: trendRows,
          invoiceStatus: statusRows,
          expenseCategories: expenseCatRows
        }
      }
    });

  } catch (error) {
    console.error('Dashboard Stats Error:', error);
    res.status(500).json({ success: false, message: 'Failed to load dashboard statistics.' });
  }
});

module.exports = router;
