var express = require('express');
var router = express.Router();
var Sale = require('../models/Sale');
var Customer = require('../models/Customer');
var Product = require('../models/Product');

var populateSale = function(query) {
  return query.populate('customer', 'firstName lastName customerNumber');
};

router.get('/daily', function(req, res) {
  var date = req.query.date;
  var reportDate = date ? new Date(date) : new Date();
  reportDate.setHours(0, 0, 0, 0);
  var endOfDay = new Date(reportDate);
  endOfDay.setHours(23, 59, 59, 999);

  populateSale(
    Sale.find({ salesDate: { $gte: reportDate, $lte: endOfDay } }).sort({ salesDate: -1 })
  )
    .then(function(sales) {
      var totalRevenue = 0;
      for (var i = 0; i < sales.length; i++) {
        totalRevenue += sales[i].totalAmountPaid;
      }
      res.json({
        reportType: 'Daily',
        sales: sales,
        totalRevenue: totalRevenue,
        totalTransactions: sales.length
      });
    })
    .catch(function(error) {
      res.status(500).json({ error: error.message });
    });
});

router.get('/weekly', function(req, res) {
  var date = req.query.date;
  var reportDate = date ? new Date(date) : new Date();
  var dayOfWeek = reportDate.getDay();
  var startOfWeek = new Date(reportDate);
  startOfWeek.setDate(reportDate.getDate() - dayOfWeek);
  startOfWeek.setHours(0, 0, 0, 0);
  var endOfWeek = new Date(startOfWeek);
  endOfWeek.setDate(startOfWeek.getDate() + 7);

  populateSale(
    Sale.find({ salesDate: { $gte: startOfWeek, $lt: endOfWeek } }).sort({ salesDate: -1 })
  )
    .then(function(sales) {
      var totalRevenue = 0;
      for (var i = 0; i < sales.length; i++) {
        totalRevenue += sales[i].totalAmountPaid;
      }
      res.json({
        reportType: 'Weekly',
        sales: sales,
        totalRevenue: totalRevenue,
        totalTransactions: sales.length
      });
    })
    .catch(function(error) {
      res.status(500).json({ error: error.message });
    });
});

router.get('/monthly', function(req, res) {
  var year = req.query.year;
  var month = req.query.month;
  var reportYear = year || new Date().getFullYear();
  var reportMonth = month || new Date().getMonth() + 1;

  var startOfMonth = new Date(reportYear, reportMonth - 1, 1);
  var endOfMonth = new Date(reportYear, reportMonth, 0, 23, 59, 59, 999);

  populateSale(
    Sale.find({ salesDate: { $gte: startOfMonth, $lte: endOfMonth } }).sort({ salesDate: -1 })
  )
    .then(function(sales) {
      var totalRevenue = 0;
      for (var i = 0; i < sales.length; i++) {
        totalRevenue += sales[i].totalAmountPaid;
      }
      var period = reportYear + '-' + (reportMonth < 10 ? '0' + reportMonth : reportMonth);
      res.json({
        reportType: 'Monthly',
        period: period,
        sales: sales,
        totalRevenue: totalRevenue,
        totalTransactions: sales.length
      });
    })
    .catch(function(error) {
      res.status(500).json({ error: error.message });
    });
});

router.get('/customers', function(req, res) {
  Customer.find().sort({ createdAt: -1 })
    .then(function(customers) {
      res.json(customers);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

router.get('/products', function(req, res) {
  Product.find().sort({ createdAt: -1 })
    .then(function(products) {
      res.json(products);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

router.get('/sales', function(req, res) {
  populateSale(Sale.find().sort({ salesDate: -1 }))
    .then(function(sales) {
      res.json(sales);
    })
    .catch(function(err) {
      res.status(400).json({ error: err.message });
    });
});

module.exports = router;
