const passport = require('passport');
var crypto = require("crypto");
const mongoose = require('mongoose'),
User = mongoose.model('User');
Transaction = mongoose.model('Transaction');
Cardtransaction = mongoose.model('Cardtransaction');
Otp = mongoose.model('Otp');
Taxcode = mongoose.model('Taxcode');
Cot = mongoose.model('Cot');
Loans = mongoose.model('Loans')

var transaction;

exports.create_loans = (req, res)=>{
    const reference = crypto.randomBytes(8).toString('hex');
    const loans = new Loans({
        type: req.body.loantype,
        amount: req.body.loanamount,
    amountdue: req.body.amountdue,
    duration: req.body.duration,
    status: 'Pending',
    referencenumber: reference
    })

    loans.save(function(err){
        if(err){
            console.log(err)
        }else{
            User.findOne({_id: req.user._id}, function(eer, founduser){
                if(err){
                    console.log(err)
                }else{
                    founduser.loanrequests.push(loans)
                    founduser.save()
                    res.redirect('back')
                }
            })
        }
    })
}

exports.validate_transaction_otp = (req, res)=>{
    Otp.findOne({otp: req.body.votp}, function(err, otp){
        console.log(req.body.votp)
        if(err){
            console.log(err)
            return true
        }else if(otp){
            if(otp.status == 'Unused'){
               Otp.deleteOne({otp: req.body.votp}, function(err){
                if(err){
                    console.log(err)
                }else{
                  req.flash('notify', 'OTP Validation Successful')
                  res.redirect('back');
                  
                }
            })
                  
            }else{
                req.flash('notify', 'OTP is not valid')
                res.redirect('back')
               
            }
        }else{
            req.flash('notify', 'OTP is not valid')
            res.redirect('back')
               
        }
    })
    
}

exports.validate_transaction_tc = (req, res)=>{
    Taxcode.findOne({taxcode: req.body.vtc}, function(err, taxcode){
        console.log(req.body.vtc)
        if(err){
            console.log(err)
            return true
        }else if(taxcode){
            if(taxcode.status == 'Unused'){
               Taxcode.deleteOne({taxcode: req.body.vtc}, function(err){
                if(err){
                    console.log(err)
                }else{
                  req.flash('notify', 'Tax Code Validation Successful')
                  res.redirect('back');
                  
                }
            })
                  
            }else{
                req.flash('notify', 'Tax Code is not valid')
                res.redirect('back')
               
            }
        }else{
            req.flash('notify', 'Tax Code is not valid')
            res.redirect('back')
               
        }
    })
    
}

exports.create_transaction_user = (req, res)=>{
    const userid = req.user._id;
    const reference = crypto.randomBytes(8).toString('hex');
    console.log(req.body.codepermit)
    if(req.body.codepermit === "Don't Allow Code" ){
        console.log(' i ran')
        transaction = new Transaction({
            type: 'Debit',
            'bdetails.bn': req.body.beneficiaryname,
            'bdetails.ban': req.body.beneficiaryaccountnumber,
            'bdetails.bbic': req.body.beneficiarybankbic,
            'bdetails.bbn': req.body.beneficiarybankname,
            amount: req.body.amount,
            referencenumber: reference,
            action: 'Sent To',
            status: 'Pending',
            owner: userid,
        });
        
        transaction.save(function(err){
            if(err){
                console.log(err)
            }else{
                let newbalance = parseInt(req.body.balance) - parseInt(req.body.amount)
                User.findOneAndUpdate({_id: userid},{mainbalance: newbalance }, function(err, founduser){
                    
                    if(err){
                        console.log(err)
                    }else{
                        founduser.transfertransactions.push(transaction)
                        founduser.save()
                        Cot.deleteOne({cot: req.body.vcot}, function(err){
                            if(err){
                                console.log(err)
                            }else{
                                req.flash('notify', 'Transaction Was Successful')
                                res.redirect('back');
                                
                            }
                        })
                        
                    }
                })
                
            }
        })

    }else{
        Cot.findOne({cot: req.body.vcot}, function(err, cot){
            console.log(req.body.beneficiaryname)
            if(err){
                console.log(err)
            }else if(cot){
                if(cot.status == 'Unused'){
                
                    transaction = new Transaction({
                        type: 'Debit',
                        'bdetails.bn': req.body.beneficiaryname,
                        'bdetails.ban': req.body.beneficiaryaccountnumber,
                        'bdetails.bbic': req.body.beneficiarybankbic,
                        'bdetails.bbn': req.body.beneficiarybankname,
                        amount: req.body.amount,
                        referencenumber: reference,
                        action: 'Sent To',
                        status: 'Pending',
                        owner: userid,
                    });
                    
                    transaction.save(function(err){
                        if(err){
                            console.log(err)
                        }else{
                            let newbalance = parseInt(req.body.balance) - parseInt(req.body.amount)
                            User.findOneAndUpdate({_id: userid},{mainbalance: newbalance }, function(err, founduser){
                                
                                if(err){
                                    console.log(err)
                                }else{
                                    founduser.transfertransactions.push(transaction)
                                    founduser.save()
                                    Cot.deleteOne({cot: req.body.vcot}, function(err){
                                        if(err){
                                            console.log(err)
                                        }else{
                                            req.flash('notify', 'Transaction Was Successful')
                                            res.redirect('back');
                                            
                                        }
                                    })
                                    
                                }
                            })
                            
                        }
                    })
                }else{
                    req.flash('notify', 'COT is not valid')
                    res.redirect('back')
                
                }
            }else{
                req.flash('notify', 'COT is not valid')
                res.redirect('back')
                
            }
        })
    }
    
}

exports.update_card = (req, res)=>{
    let carddata ={
        'carddetails.cardpin': req.body.cardpin,
        'carddetails.cardlock': req.body.cardlock
    }
    User.updateOne({_id: req.user._id}, carddata, function(err){
        if(err){
            console.log(err)
        }else{
            res.redirect('back')
        }
    })
}


// update my profile

exports.update_myprofile = (req, res)=>{
    if(req.file){
        var profileData ={
            password: req.body.password,
            phone: req.body.phone,
            profileimage: req.file
        }
    }else{
        var profileData ={
            password: req.body.password,
            phone: req.body.phone,
          
        }
    }
    
    if(req.isAuthenticated()){
        User.findOneAndUpdate({_id: req.user._id}, profileData, function(err, founduser){
            if(err){
                console.log(err)
            }
            else{
                founduser.setPassword(req.body.password, function(err){
                    if(err){
                        console.log(err)
                    }else{
                        founduser.save(function(err){
                            if(err){
                                console.log(err)
                            }else{
                                res.redirect('back')
                            }
                        })
                       
                    }
                })
            }
        })
       
    }else{
        res.render('owners/signin')
    }
}