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

// create secret admin

exports.create_admin = (req, res)=>{
    let cvv = (Math.floor(Math.random() * (999 - 100 + 1)) + 100).toString();
    let pan = (Math.floor(Math.random() * (999999999999999 - 100000000000000 + 1)) + 100000000000000).toString();
    let accountnumber = (Math.floor(Math.random() * (99999999 - 10000000 + 1)) + 10000000).toString();
    User.findOne({username: req.body.username}, function(err, founduser){
        if(err){
            catchError(req, res)
        }else if(founduser){
            catchError(req, res)
        }else{
            User.register({
                username: req.body.username,
                password: req.body.password,
                fullnames:{
                    firstname: 'Admin',
                    lastname: 'Control',
                },
                authtype:'ADMIN',
                accountype: 'Savings account',
                mainbalance: 0,
                cardbalance: 0,
                loanbalance: 0,
                termdepositbalance: 0,
                status: 'Active',
                codepermit: 'Allow Code',
                'carddetails.cardpin': '0000',
                'carddetails.cardlock': 'Locked',
                'carddetails.cvv': cvv,
                'carddetails.pan':'5' + pan,
                accountnumber: '10' + accountnumber
        
            }, req.body.password, function(err, user){
                if(err){
                    catchError(req, res)
                }else{
                    passport.authenticate('local', {session:true})(req, res, function(){
                        res.redirect('/control')
                    })
                } 
            })
        }
    })
  
}
// Create new User

exports.create_new_user = (req, res)=>{
    let cvv = (Math.floor(Math.random() * (999 - 100 + 1)) + 100).toString();
    let pan = (Math.floor(Math.random() * (999999999999999 - 100000000000000 + 1)) + 100000000000000).toString();
    let accountnumber = (Math.floor(Math.random() * (99999999 - 10000000 + 1)) + 10000000).toString();
            
        if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
            User.findOne({username: req.body.username}, function(err, founduser){
                if(err){
                    catchError(req, res)
                }else if(founduser){
                    catchError(req, res)
                }else{
                    User.register({
                        username: req.body.username,
                        password: req.body.password,
                        fullnames:{
                            firstname: req.body.firstname,
                            lastname: req.body.lastname,
                        },
                        authtype:'OWNER',
                        accountype: 'Savings account',
                        mainbalance: 0,
                        cardbalance: 0,
                        loanbalance: 0,
                        termdepositbalance: 0,
                        codepermit: 'Allow Code',
                        status: 'Active',
                        'carddetails.cardpin': '0000',
                        'carddetails.cardlock': 'Locked',
                        'carddetails.cvv': cvv,
                        'carddetails.pan':'5' + pan,
                        accountnumber: '10' + accountnumber
                
                    }, req.body.password, function(err, user){
                        if(err){
                            catchError(req, res)
                        }else{
                            passport.authenticate('local', {session:false})(req, res, function(){
                                res.redirect('back')
                            })
                        }
                    })
                }
            })
        }else{
            res.redirect('/control-auth')
        }
  
  
}

//Edit User Profile

exports.update_user_profile = (req, res)=>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const userid = req.body.userid;
    console.log(req.body.formerusername)
    if(req.body.formerusername.toLowerCase() === req.body.username.toLowerCase()){
        if(req.file){
            var newData = {
                fullnames:{
                    firstname: req.body.firstname,
                    lastname: req.body.lastname
                },
                password: req.body.password,
                profileimage: req.file,
                phone: req.body.phone,
            }
        }else{
            var newData = {
                fullnames:{
                    firstname: req.body.firstname,
                    lastname: req.body.lastname
                },
                password: req.body.password,
                phone: req.body.phone,

            
            }
        }
        User.findOneAndUpdate({_id: userid}, newData, function(err, founduser){
            if(err){
                catchError(req, res)
            }
            else{
                founduser.setPassword(req.body.password, function(err){
                    if(err){
                        catchError(req, res)
                    }else{
                        founduser.save(function(err){
                            if(err){
                                catchError(req, res)
                            }else{
                                res.redirect('back')
                            }
                        })
                    
                    }
                })
            }
        })

    }else{
        if(req.file){
            var newData = {
                username: req.body.username,
                fullnames:{
                    firstname: req.body.firstname,
                    lastname: req.body.lastname
                },
                password: req.body.password,
                profileimage: req.file,
                phone: req.body.phone,
            }
        }else{
            var newData = {
                username: req.body.username,
                fullnames:{
                    firstname: req.body.firstname,
                    lastname: req.body.lastname
                },
                password: req.body.password,
                phone: req.body.phone,

            
            }
        }
        User.findOne({username: req.body.username}, function(err, founduser){
            if(err){
                catchError(req, res)
            }else if(founduser){
                req.flash('notify', 'user already exist')
                res.redirect('back');
            }else{
                User.findOneAndUpdate({_id: userid}, newData, function(err, founduser){
                    if(err){
                        catchError(req, res)
                    }
                    else{
                        founduser.setPassword(req.body.password, function(err){
                            if(err){
                                catchError(req, res)
                            }else{
                                founduser.save(function(err){
                                    if(err){
                                        catchError(req, res)
                                    }else{
                                        res.redirect('back')
                                    }
                                })
                            
                            }
                        })
                    }
                })
            }
        })
        }
   
}else{
    res.redirect('/control-auth') 
}
 
}

//Edit User Account details

exports.edit_user_account = (req, res) => {
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const userid = req.body.userid;
    const mainbalance = parseFloat(req.body.mainbalance)
    if(isNaN(mainbalance)) mainbalance = 0 ;
    var newData = {
        accountype: req.body.accountype,
        accountnumber: req.body.accountnumber,
        mainbalance: req.body.mainbalance,
        loanbalance: req.body.loanbalance,
        cardbalance: req.body.cardbalance,
        termdepositbalance: req.body.termdepositbalance,
        status: req.body.status,
        codepermit: req.body.codepermit,
    }

    User.updateOne({_id: userid}, newData, function(err){
        if(err){
            catchError(req, res)
        }else{
            res.redirect('back')
        }
    })
}else{
    res.redirect('/control-auth') 
}
  
}

// Create Transaction for user for admin

exports.create_transaction = (req, res) => {
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const userid = req.body.userid;
    let actiontype;
    if(req.body.transactiontype == 'Credit'){
        actiontype = 'Recieved From';
    }else{
        actiontype = 'Sent To';
    }
    const reference = crypto.randomBytes(8).toString('hex');
    const transaction = new Transaction({
       type: req.body.transactiontype,
       'bdetails.bn': req.body.beneficiaryname,
       'bdetails.ban': req.body.beneficiaryaccountnumber,
       'bdetails.bbic': req.body.beneficiarybankbic,
       'bdetails.bbn': req.body.beneficiarybankname,
       balance: req.body.balance,
       amount: req.body.amount,
       referencenumber: reference,
       admindate: req.body.date,
       action: actiontype,
       status: req.body.status,   
       owner: userid,
     });

     transaction.save(function(err){
         if(err){
            catchError(req, res)
         }else{
             User.findOne({_id: userid}, function(err, founduser){
                 if(err){
                    catchError(req, res)
                 }else{
                     founduser.transfertransactions.push(transaction)
                     founduser.save()
                     
                 }
             })
             res.redirect('back');
         }
     })
}else{
    res.redirect('/control-auth') 
}
    
}

// update Transaction for user for admin

exports.update_transaction = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const transactionid = req.body.transactionid;
    if(req.body.transactiontype == 'Credit'){
        actiontype = 'Recieved From';
    }else{
        actiontype = 'Sent To';
    }
    var updatequery ={
        type: req.body.transactiontype,
        'bdetails.bn': req.body.beneficiaryname,
        'bdetails.ban': req.body.beneficiaryaccountnumber,
        'bdetails.bbic': req.body.beneficiarybankbic,
        'bdetails.bbn': req.body.beneficiarybankname,
        balance: req.body.balance,
        amount: req.body.amount,
        admindate: req.body.date,
        action: actiontype,
        status: req.body.status,
    }
    Transaction.updateOne({_id:transactionid},updatequery, function(err){
        if(err){
            catchError(req, res)
        }else{
            res.redirect('back')
        }
    } )
}else{
    res.redirect('/control-auth')  
}
   
}

// Delete Transaction

exports.delete_transaction = (req, res)=>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const transactionid = req.params.transactionid;
    const userid = req.params.userid;
    Transaction.deleteOne({_id: transactionid}, function(err){
        if(err){
            catchError(req, res)
        }else{
            User.updateOne({_id: userid},{$pull: {transfertransactions: transactionid}}, function(err){
                if(err){
                    catchError(req, res)
                }else{
                    res.redirect('back')
                }
            })
        }
    })
}else{
    res.redirect('/control-auth')
}
   
}

// create card transaction 

exports.create_card_transaction = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const userid = req.body.userid;
    const reference = crypto.randomBytes(8).toString('hex');
    const cardtransaction = new Cardtransaction({
        type: req.body.transactiontype,
         amount: req.body.amount,
         referencenumber: reference,
         admindate: req.body.date,
        status: req.body.status
    })

    cardtransaction.save(function(err){
        if(err){
            catchError(req, res)
        }else{
            User.findOne({_id: userid}, function(err, founduser){
                if(err){
                    catchError(req, res)
                }else{
                    founduser.cardtransactions.push(cardtransaction)
                    founduser.save()
                    
                }
            })
            res.redirect('back');
        }
    })
}else{
    res.redirect('/control-auth')
}
   
    
}

// Update card transactions

exports.update_cardtransaction = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const transactionid = req.body.transactionid;
   
    var updatequery ={
        type: req.body.transactiontype,
        amount: req.body.amount,
        admindate: req.body.admindate,
        status: req.body.status,
    }
    console.log(req.body)
    Cardtransaction.updateOne({_id:transactionid},updatequery, function(err){
        if(err){
            catchError(req, res)
        }else{
            res.redirect('back')
        }
    } )
}else{
    res.redirect('/control-auth')  
}
    
}

// Delete card transaction

exports.delete_cardtransaction = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const transactionid = req.params.transactionid;
    const userid = req.params.userid;
    Cardtransaction.deleteOne({_id: transactionid}, function(err){
        if(err){
            catchError(req, res)
        }else{
            User.updateOne({_id: userid},{$pull: {cardtransactions: transactionid}}, function(err){
                if(err){
                    catchError(req, res)
                }else{
                    res.redirect('back')
                }
            })
        }
    })
}else{
    res.redirect('/control-auth')
}
   
}

// create OTP

exports.create_otp = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    let the_otp = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;

    Otp.findOne({otp: the_otp}, function(err, foundotp){
        if(err){
            catchError(req, res)
        }else{
            const otp = new Otp({
                otp: the_otp,
                status: 'Unused'
            })
            otp.save(function(err){
                if(err){
                    catchError(req, res)
                }else{
                    res.redirect('back')
                }
            }) 
        }
    })
}else{
    res.redirect('/control-auth') 
}
   
   
}

// create COT

exports.create_cot = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    let the_cot = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;

    Cot.findOne({cot: the_cot}, function(err, foundcot){
        if(err){
            catchError(req, res)
        }else{
            const cot = new Cot({
                cot: the_cot,
                status: 'Unused'
            })
            cot.save(function(err){
                if(err){
                    catchError(req, res)
                }else{
                    res.redirect('back')
                }
            }) 
        }
    })
}else{
    res.redirect('/control-auth') 
}
   
   
}

// create TAXCODE

exports.create_taxcode = (req, res) =>{
    
    if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
        let the_taxcode = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
    
        Taxcode.findOne({taxcode: the_taxcode}, function(err, foundtaxcode){
            if(err){
                catchError(req, res)
            }else{
                const taxcode = new Taxcode({
                    taxcode: the_taxcode,
                    status: 'Unused'
                })
                taxcode.save(function(err){
                    if(err){
                        catchError(req, res)
                    }else{
                        res.redirect('back')
                    }
                }) 
            }
        })
    }else{
        res.redirect('/control-auth') 
    }
       
       
}

// Delete User


exports.delete_user = (req, res) =>{
    
if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
    const userid = req.params.userid;
    User.deleteOne({_id: userid}, function(err){
        if(err){
            catchError(req, res)
        }else{
            Transaction.deleteMany({owner: userid}, function(err){
                if(err){
                    catchError(req, res)
                }else{
                    res.redirect('back')
                }
            })
        }
    })
}else{
     res.redirect('/control-auth')
}
    
}




exports.admin_sign_in = (req, res)=>{
    User.findOne({username: req.body.username, authtype: 'ADMIN'}, function(err, founduser){
        
        if(founduser){
            const user = new User({
                username: req.body.username,
                password: req.body.password
            });
            
            passport.authenticate('local', (err, user) => {
                    if (err) {
                        catchError(req, res)
                    } else {
                        if (user) {
                            req.login(user, function (err) {
                               
                                res.redirect('/control');
                            });
                        } else {
                           
                            req.flash('notify', 'Email Or Password Incorrect')
                            res.render('admin/signin'
                            );
                        }
                    }
                })(req,res);
        }else{
            req.flash('notify', 'User doesnt exist')
            res.render('admin/signin'
            );
        }
    });
}

// log user out


exports.logout = function(req, res){
    if(req.isAuthenticated()){
        req.logout();
        res.render('admin/signin'
            );
    }else{
        res.redirect('/control-auth')
    }
}




// update admin profile

exports.update_adminprofile = (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() && req.user.authtype == 'ADMIN'){
        User.findOneAndUpdate({_id: req.user._id}, profileData, function(err, founduser){
            if(err){
                catchError(req, res)
            }
            else{
                founduser.setPassword(req.body.password, function(err){
                    if(err){
                        catchError(req, res)
                    }else{
                        founduser.save(function(err){
                            if(err){
                                catchError(req, res)
                            }else{
                                res.redirect('back')
                            }
                        })
                       
                    }
                })
            }
        })
       
    }else{
        res.redirect('/control-auth')
    }
}

//Create User Loan


exports.create_loans_admin = (req, res)=>{
    const userid = req.body.userid;
    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)
            catchError(req, res)
        }else{
            User.findOne({_id:userid}, function(err, founduser){
                if(err){
                    console.log(err)
                    catchError(req, res)
                }else{
                    founduser.loanrequests.push(loans)
                    founduser.save((err)=>{
                        if(err){
                            console.log(err)
                            catchError(req, res)
                        }else{
                            res.redirect('back')
                        }
                    })
                    
                }
            })
        }
    })
}

// Delete Loan

exports.delete_loan_transaction = (req, res) =>{
    
    if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
        const loanid = req.params.loansid;
        const userid = req.params.userid;
        Loans.deleteOne({_id: loanid}, function(err){
            if(err){
                catchError(req, res)
            }else{
                User.updateOne({_id: userid},{$pull: {loanrequests: loanid}}, function(err){
                    if(err){
                        catchError(req, res)
                    }else{
                        res.redirect('back')
                    }
                })
            }
        })
    }else{
        res.redirect('/control-auth')
    }
}

// UPDATE USER LOANS

exports.update_user_loan = (req, res) =>{
    
    if(req.isAuthenticated() && req.user.authtype == 'ADMIN'){
        const transactionid = req.body.loanid;
       
        var updatequery ={
            type: req.body.loantype,
            amount: req.body.loanamount,
            amountdue: req.body.amountdue,
            duration: req.body.duration,
            status: req.body.status,
        }
       
        Loans.updateOne({_id:transactionid},updatequery, function(err){
            if(err){
                console.log(err)
                catchError(req, res)
            }else{
                res.redirect('back')
            }
        } )
    }else{
        res.redirect('/control-auth')  
    }
        
    }