const User = require("../models/User");
const UserWithdrawals = require('../models/UserWithdrawals');
const UserTokens = require('../models/UserTokens');

const emailService = require('../../services/email.service');
const authService = require("../../services/auth.service");
const helperService = require("../../services/helpers.service");
const { includes } = require("lodash");
var moment = require('moment');

exports.manageWithdrawals = async (req, res) => {
  try {
      var success = req.flash('success');
      var error = req.flash('failer');

      const withdraws = await UserWithdrawals.findAll({
        include: [
          {
            model: User,
            required: true,
            where:{
              status: 1
            },
          }
        ]
      });
      // const withdrawStatus = await UserWithdrawals.findAll({
      //   attributes:['id', 'status']
      // });
      res.render('withdrawals/index', { moment: moment, data: withdraws, success: success, errors: error })
  } catch (err) {
      console.log(err);
      res.render('500', { err });

  }
};
exports.acceptWithdraw = async (req, res) => {
  try {
      const id = req.params.id;
      const { transactionDetail } = req.body
      const getWithdraw = await UserWithdrawals.findOne({
        where: {
          id
        },
        raw:true
      })
      if(getWithdraw){
        console.log('getWithdraw', getWithdraw)
      }
      const user_id = getWithdraw.user_id
      const getUserTokens = await UserTokens.findOne({
        where: {
          user_id
        },
      })
      const getUser = await User.findOne({
        where: {
          id: user_id
        },
        attributes:['email'],
      })
      if(getUserTokens){
        const amount = parseFloat(getWithdraw.withdraw_amount)
        let final_current_balance = parseFloat(getUserTokens.current_balance) - amount // 164 - 10 = 154
        final_current_balance = parseFloat(final_current_balance).toFixed(4)

        let total_withdraw = parseFloat(getUserTokens.total_withdraw) + amount
        total_withdraw = parseFloat(total_withdraw).toFixed(4)
        
        let total_onhold = parseFloat(getUserTokens.onhold) - amount
        total_onhold = parseFloat(total_onhold).toFixed(4)

        console.log('amount:::::::::::', amount)
        console.log('final_current_balance:::::::::::', final_current_balance)
        console.log('total_withdraw:::::::::::', total_withdraw)
        console.log('total_onhold:::::::::::', total_onhold)

        const withdrawal = await UserWithdrawals.update({ status: 1,  transaction_details: transactionDetail },
        {
          where: {
            id
          }
        })
        const userTokenUpdate = await UserTokens.update(
          { 
            total_withdraw: total_withdraw, 
            onhold: total_onhold, 
            current_balance: final_current_balance 
          },
          {
            where: {
              user_id
            }
          }
        )
        const html = `
          Hello ,<br/><br/>
          Your withdrawal request has approved by admin. <br/>
          Your `+ amount + ` token has been sent on your withdraw address `+ getUserTokens.withdraw_address + `<br/>
          Your current balance is `+ final_current_balance + `<br/>
          <br/><br/>
          Thanks Admin.
          `;
          emailService.sendEmail("withdraw-accept", getUser.email, html);
      }
      
      req.flash('success', 'Withdrawals accept successfully.');
      res.redirect('/admin/withdrawals');
  } catch (err) {
      console.log("err", err)
      res.render('500', { err });
  }
}
exports.cancelWithdraw = async (req, res) => {
  try {
    const id = req.params.id;
    const { transactionDetail } = req.body
    const getWithdraw = await UserWithdrawals.findOne({
      where: {
        id
      },
      raw:true
    })
    if(getWithdraw){
      console.log('getWithdraw', getWithdraw)
    }
    const user_id = getWithdraw.user_id
    const getUserTokens = await UserTokens.findOne({
      where: {
        user_id
      },
    })
    const getUser = await User.findOne({
      where: {
        id: user_id
      },
      attributes:['email'],
    })
    if(getUserTokens){
      const amount = parseFloat(getWithdraw.withdraw_amount)
      // let final_current_balance = parseFloat(getUserTokens.current_balance) - amount // 164 - 10 = 154
      // final_current_balance = parseFloat(final_current_balance).toFixed(4)

      // let total_withdraw = parseFloat(getUserTokens.total_withdraw) + amount
      // total_withdraw = parseFloat(total_withdraw).toFixed(4)
      
      let total_onhold = parseFloat(getUserTokens.onhold) - amount
      total_onhold = parseFloat(total_onhold).toFixed(4)

      console.log('amount:::::::::::', amount)
      // console.log('final_current_balance:::::::::::', final_current_balance)
      // console.log('total_withdraw:::::::::::', total_withdraw)
      console.log('total_onhold:::::::::::', total_onhold)

      await UserWithdrawals.update({ status: 2,  transaction_details: transactionDetail },
      {
        where: {
          id
        }
      })
      await UserTokens.update(
        { 
          onhold: total_onhold, 
        },
        {
          where: {
            user_id
          }
        }
      )
      const html = `
        Hello ,<br/><br/>
        Your withdrawal request has been cancelled by admin for some reasons. <br/>
        Your current balance is `+ getUserTokens.current_balance + `<br/>
        <br/><br/>
        Thanks.
        `;
        emailService.sendEmail("withdraw-cancel", getUser.email, html);
    }
    
    req.flash('success', 'Withdrawals accept successfully.');
    res.redirect('/admin/withdrawals');
  } catch (err) {
      console.log("err", err)
      res.render('500', { err });
  }
}