const accountModel = require('../models/accountModel');
const db = require('../db/config');

exports.getAllTransactions = async (req, res) => {
  const transactions = await accountModel.getAllTransactions();
  res.json(transactions);
};

exports.getTransactionsByType = async (req, res) => {
  const { type } = req.params;
  const transactions = await accountModel.getTransactionByType(type);
  res.json(transactions);
};

exports.getProfitLoss = async (req, res) => {
  const summary = await accountModel.getProfitLossSummary();
  const profit = summary.total_sales - (summary.total_purchases + summary.total_expenses);
  res.json({ ...summary, profit });
};
exports.getBankSummary = async (req, res) => {
    const bankId = req.params.bankId;
    try {
      const summary = await accountModel.getBankSummary(bankId);
      res.json(summary);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };
  exports.getLedgerByAccount = async (req, res) => {
    const accountId = req.params.accountId;
  
    try {
      const [rows] = await db.query(
        'SELECT * FROM accounts_ledger WHERE reference = ? ORDER BY created_at DESC',
        [accountId]
      );
      res.json(rows);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };

  exports.getCustomerSummary = async (req, res) => {
    const customerId = req.params.customerId;
    try {
      const summary = await accountModel.getCustomerSummary(customerId);
      res.json(summary);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };

  exports.getBankSummary = async (req, res) => {
    const bankId = req.params.bankId;
    try {
      const summary = await accountModel.getBankSummary(bankId);
      res.json(summary);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };