const router = require('express').Router();
//import models
const Finance = require('../models/finance.model');
let Tutor = require('../models/tutor.user.model');

router.route('/tutors').get((req,res) =>{
    Tutor.find({}, {tutor_name:1, _id:0})
        .then(tutors => res.json(tutors))
        .catch(err => res.status(400).json('Error: '+ err));
});

router.route('/').get((req ,res) => {
    Finance.find()
        .then( financedetails => res.json(financedetails))
        .catch(err => res.status(400).json('Error :'+err));
});

router.route('/store').post((req ,res) =>{
    const account_month = req.body.account_month;
    const direct_income = req.body.direct_income;
    const indirect_income = req.body.indirect_income;
    const total_income = req.body.total_income;
    const direct_expenses = req.body.direct_expenses;
    const indirect_expenses = req.body.indirect_expenses;
    const total_expenses = req.body.total_expenses;
    const gross_revenue = req.body.gross_revenue;

    const newFinancialDetails = new Finance({
        account_month,
        direct_income,
        indirect_income,
        total_income,
        direct_expenses,
        indirect_expenses,
        total_expenses,
        gross_revenue
    });

    newFinancialDetails.save()
        .then(()=> res.json('Financial Details Added!'))
        .catch(err => res.status(400).json('Error :'+err));
});

router.route('/:id').get((req , res) =>{
    Finance.findById(req.params.id)
        .then(financedetails => res.json(financedetails))
        .catch(err => res.status(400).json('Error :'+err));
});

router.route('/update/:id').post((req , res) =>{
    Finance.findById(req.params.id)
        .then(financialDetails =>{
            financialDetails.account_month = req.body.account_month;
            financialDetails.direct_income = req.body.direct_income;
            financialDetails.indirect_income = req.body.indirect_income;
            financialDetails.total_income = req.body.total_income;
            financialDetails.direct_expenses = req.body.direct_expenses;
            financialDetails.indirect_expenses = req.body.indirect_expenses;
            financialDetails.total_expenses = req.body.total_expenses;
            financialDetails.gross_revenue = req.body.gross_revenue;

            financialDetails.save()
                .then(()=> res.json('Finance Details Updated!'))
                .catch(err => res.status(400).json('Error :'+err));
        })
        .catch(err => res.status(400).json('Error :'+err));
});

router.route('/:id').delete((req ,res) =>{
    Finance.findByIdAndDelete(req.params.id)
        .then(()=> res.json('Financial Details Deleted!'))
        .catch(err => res.status(400).json('Error :'+err));
});

module.exports = router;