const express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({ limit: '100mb' }));
const mongoose = require("mongoose");
app.use(bodyParser.urlencoded({ limit: '500mb', extended: true, parameterLimit: 100000 }));
const { catchErrors } = require("../handlers/errorHandlers");

const axios = require("axios");
const uniqid = require("uniqid");
const qs = require('qs');
const { LocalStorage } = require('node-localstorage');

const localStorage = new LocalStorage('../scratch');

const router = express.Router();
var cron = require('node-cron');

// const client = require("../controllers/phonepeClient");
const paymentGateway = mongoose.model("paymentGateway")
const BillHistory = mongoose.model("BillHistorys")
const User = mongoose.model("User")

let token_url = '';
let config_url = '';
let client_id = '';
let client_secret = '';
if(process.env.USE_PHONEPE==0){
    token_url = process.env.SANDBOX_PHONEPE_URL+'/v1/oauth/token';
    config_url = process.env.SANDBOX_PHONEPE_URL
    client_id = process.env.SANDBOX_CLIENT_ID
    client_secret = process.env.SANDBOX_CLIENT_SECRET
}else{
    token_url = process.env.LIVE_PHONEPE_AUTHORIZATION_URL
    config_url = process.env.LIVE_PHONEPE_URL
    client_id = process.env.LIVE_CLIENT_ID
    client_secret = process.env.LIVE_CLIENT_SECRET
}

const getAuthToken = async () => {
    let resToken = {};
    
    let data = qs.stringify({
        'client_id': client_id,
        'client_version': '1',
        'client_secret': client_secret,
        'grant_type': 'client_credentials' 
      });
      
      let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: token_url,
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data : data
      };
      
      await axios.request(config)
      .then((response) => {
        // console.log(JSON.stringify(response.data));
        resToken = response.data.access_token;
      })
      .catch((error) => {
        console.log(error);
      });
    
    return resToken;

};

router.post("/planpay", async (req, res) => {
    
    // console.log(req.body)

    const checkExist = await User.find({ email: req.body.email });
    
    let userId = '';
    if(checkExist.length==0){
        console.log(req.get('host'));
        if(req.get('host')=='https://dropshipper.shopperr.in/'){
            const newUser = new User({
                'email' : req.body.email
            });
    
            newUser.save();
    
            const getUser = await User.findOne({ email: req.body.email });
            if(getUser){
                userId = getUser._id;
            }
        }else{
            return res.status(200).send({"error":1, "message": "Email Not Exists."});
        }

    }else{
        userId = checkExist[0]._id;
    }

    const fullURL = req.protocol + '://' + req.get('host') + req.originalUrl; // Full URL
    // console.log(req.headers.origin)
    // console.log(fullURL)

    if(req.body.shopperr==2){
        localStorage.setItem('hostname', 'https://dropshipper.shopperr.in');
    }else{
        localStorage.setItem('hostname', req.headers.origin);
    }

    localStorage.setItem('fullURL', fullURL);
    localStorage.setItem('shopperr', req.body.shopperr);

    const amount = parseInt(req.body.amount) * 100; // Convert to paise
    const merchantTransactionId = uniqid();
    const accessToken = await getAuthToken();

    localStorage.setItem('merchantTransactionId', merchantTransactionId);
    localStorage.setItem('accessToken', accessToken);

    const paymentGatewayData = new paymentGateway({
        'merchantTransactionId': merchantTransactionId,
        'userId' : userId,
    });

    paymentGatewayData.save();

    let data = JSON.stringify({
        "merchantOrderId": merchantTransactionId,
        'merchantUserId': userId,
        'name': 'Minakshi',
        "amount": amount,
        "paymentFlow": {
          "type": "PG_CHECKOUT",
          "message": "Payment message used for collect requests",
          "merchantUrls": {
            "redirectUrl": `${process.env.APP_URL}/pg/PGIntegration/`
          }
        }
    });

    let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: config_url+'/checkout/v2/pay',
        headers: {
          'Content-Type': 'application/json', 
          'Authorization': `O-Bearer ${accessToken}`
        },
        data : data
      };
      
    axios.request(config)
    .then((response) => {
    // console.log(JSON.stringify(response.data));
    // console.log(accessToken);
    res.status(200).send(response.data);
    })
    .catch((error) => {
        console.log(error);
    });

});

router.post("/pay", async (req, res) => {
    const fullURL = req.protocol + '://' + req.get('host') + req.originalUrl; // Full URL
    
    localStorage.setItem('fullURL', fullURL);
    localStorage.setItem('hostname', req.headers.origin);

    const amount = parseInt(req.body.amount) * 100; // Convert to paise
    const merchantTransactionId = uniqid();
    const accessToken = await getAuthToken();

    localStorage.setItem('merchantTransactionId', merchantTransactionId);
    localStorage.setItem('accessToken', accessToken);

    const paymentGatewayData = new paymentGateway({
        'merchantTransactionId': merchantTransactionId,
        'userId' : req.body.id
    });

    paymentGatewayData.save();

    let data = JSON.stringify({
        "merchantOrderId": merchantTransactionId,
        'merchantUserId': req.body.id,
        'name': 'Minakshi',
        "amount": amount,
        "paymentFlow": {
          "type": "PG_CHECKOUT",
          "message": "Payment message used for collect requests",
          "merchantUrls": {
            "redirectUrl": `${process.env.APP_URL}/pg/PGIntegration/`
          }
        }
    });

    let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: config_url+'/checkout/v2/pay',
        headers: {
          'Content-Type': 'application/json', 
          'Authorization': `O-Bearer ${accessToken}`
        },
        data : data
      };
      
    axios.request(config)
    .then((response) => {
    // console.log(JSON.stringify(response.data));
    // console.log(accessToken);
    res.status(200).send(response.data);
    })
    .catch((error) => {
        console.log(error);
    });

});

router.get("/PGIntegration", async (req, res) => {
    // console.log('PGIntegration')
    
    const merchantTransactionId = localStorage.getItem('merchantTransactionId');
    const accessToken = localStorage.getItem('accessToken');
    const hostname = localStorage.getItem('hostname');

    let config = {
        method: 'get',
        maxBodyLength: Infinity,
        url: `${config_url}/checkout/v2/order/${merchantTransactionId}/status`,
        headers: { 
            'Content-Type': 'application/json', 
            'Authorization': `O-Bearer ${accessToken}`
        }
    };

    axios.request(config)
    .then(async (response) => {
        // console.log(JSON.stringify(response.data));
        let resp = response.data

        // if(response.state=='COMPLETED')
        let msgStatus = 0;
        const gatewayData = await paymentGateway.find({ merchantTransactionId : merchantTransactionId });
        let amount = resp.amount/100;
        if(gatewayData.length>0){
            const obj = {
                amount: amount,
                orderId: resp.orderId,
                status: resp.state,
                paymentDetails: JSON.stringify(resp.paymentDetails),
                host: hostname
            }

            if(resp.state==='COMPLETED'){
                msgStatus = 1
            }else if(resp.state==='PENDING'){
                msgStatus = 2
            }else if(resp.state==='FAILED'){
                msgStatus = 3
            }

            await paymentGateway.updateOne({ "_id": mongoose.Types.ObjectId(gatewayData[0]._id) }, { $set: obj }, { upsert: false }).then(() => {
                // console.log('done-'+sku+'--'+new_qty)
            });

            if(msgStatus==1){
                const userData = await User.findOne({ _id : mongoose.Types.ObjectId(gatewayData[0].userId) }, {balance:1});
                // console.log(userData.balance)
                if(userData){
                    let balance = 0;
                    if(userData.balance){
                        balance = userData.balance+parseInt(amount)
                    }else{
                        balance = amount
                    }

                    let updateObj = {
                        balance: balance,
                    };

                    await User.updateOne({_id: mongoose.Types.ObjectId(userData._id)}, { $set: updateObj });
                }

                const bill = await BillHistory.findOne({ merchantId : gatewayData[0].userId }).sort({ _id : -1 }).limit(1);
                // console.log(bill)
                let afterAmt = 0;
                if(bill){
                    if(bill.afterAmt){
                        afterAmt = bill.afterAmt
                    }
                }
                
                let billObj = BillHistory({
                    merchantId: gatewayData[0].userId,
                    pgOrderId: resp.orderId,
                    billType: 2,
                    billAmt: amount,
                    beforeAmt: afterAmt,
                    afterAmt: afterAmt+amount,
                    comment: 'PhonePe'
                });

                billObj.save();
            }

            // console.log(billObj)
        }
        
        if(localStorage.getItem('shopperr') && localStorage.getItem('shopperr')==1){
            return res.redirect(`${hostname}/plan?s=${msgStatus}`);
        }else if(localStorage.getItem('shopperr') && localStorage.getItem('shopperr')==2){
            return res.redirect(`https://dropshipper.shopperr.in/balance/rechargeDetail?s=${msgStatus}&orderId=${resp.orderId}&referenceId=${merchantTransactionId}&paymentMode=${resp.paymentDetails[0].paymentMode}&balance=${amount}&payMethod=phoneperesponse`);
        }
        else{
            return res.redirect(`${hostname}/pages/plan?s=${msgStatus}`);
        }
        
        // return res.redirect(`${hostname}/merchant/wallet-summary?s=${msgStatus}`);
        
    })
    .catch((error) => {
        console.log(error);
    });

});

module.exports = router;
