from appservices.common.util import *
from appservices.common.payment_gateways.wowpe_payment_gateways import *
# from appservices.common.payment_gateways.fstac_payment_gateways import *
from appservices.common.payment_gateways.payaid_payment_gateways import *
from appservices.common.payment_gateways.accurepay_payment_gateways import *
from appservices.common.payment_gateways.setu_payment_gateways import *
from appservices.common.payment_gateways.campuslinkpro_payment_gateway import *

payin_apis = Blueprint("payin_apis",__name__)

# sample_static_wowpe_payin_data = {
#     "api_key":"66a0a4a248eb9192aa9a6794-1da22030ba0ec3d21f69e7afa0a5e032",
#     "order_id":"FSFSfsdfsdfsdfds",
#     "mode":"LIVE",
#     "amount":"101.00",
#     "currency":"INR",
#     "description":"Testing purpose",
#     "name":"sai krishna",
#     "email":"sai.kerla@apptrinity.com",
#     "phone":"9988776655",
#     "address_line_1":"Hyderabad",
#     "address_line_2":"Hyderabad",
#     "city":"Hyderabad",
#     "state":"Telangana",
#     "country":"India",
#     "zip_code":"500081",
#     "udf1":"",
#     "udf2":"",
#     "udf3":"",
#     "udf4":"",
#     "udf5":"",
#     "return_url":"http://3.128.23.101/api/mobile/payin_call_back_url",
# }
# salt = "701853520a2565f50146532b64aaeaac6127a829"
# hashvalue = Sha512Hash(sample_static_wowpe_payin_data,salt)
# print(hashvalue,"*************")
# sample_static_wowpe_payin_data.update({"hash": hashvalue})

# sample_static_accurepay_payin_data = {
# "api_key": "66c43d14b131cbb3c5aba543-8bf0a73fda352bcc0da5509ae4372bd7",
# "address_line_1": "Test Address Line 1",
# "address_line_2": "Test Address Line 2",
# "amount": 101,
# "city": "Bangalore",
# "country": "IND",
# "currency": "INR",
# "description": "Payment Short Description",
# "email": "testing@example.com",
# "mode": "TEST",
# "name": "Test",
# "order_id": "12436rrwed558",
# "phone": "9988776655",
# "return_url":"http://3.128.23.101/api/mobile/payin_call_back_url",
# "state": "Karnataka",
# "udf1": "66c43d14b131cbb3c5aba543",
# "udf2": "",
# "udf3": "",
# "udf4": "",
# "udf5": "",
# "zip_code": "560001"
# }
# salt = "701853520a2565f50146532b64aaeaac6127a829"
# hashvalue = Sha512Hash(sample_static_accurepay_payin_data,salt)
# print(hashvalue,"*************")
# sample_static_accurepay_payin_data.update({"hash": hashvalue}).

sample_static_campus_payin_data = {
    "api_key": "677d26b6b18d235e8b11b575-8bf0a73fda352bcc0da5509ae4372bd7",
    "order_id" : str(random_digit_generate(15)),
    "description" : "Full stack Developer",
    "amount" : 1.00,
    "currency" : "INR",
    "name" : "Sai Krishna",
    "phone" : "9502971443",
    "email" : "saikerla@viyonafintech.com",
    "graampay_check":"Campuslinkpro_Payin"
}

@payin_apis.route("/getintentpaymenturl",methods=["POST"])
# @check_mid_apikey
def getintentpaymenturl():
    data_status = {"responseStatus":0,"result":""}
    if SERVER_STATUS == "DOWN":
        data_status["result"]= SERVER_MAINTAINCE_MESSAGE
        return data_status
    merchant_id = request.headers.get("Merchant-Id","")
    api_key = request.headers.get("Api-Key","")
    encryption_data = request.form.get("encryption_data","")
    iv = request.form.get("iv","")

    location = ""
    agent = ""
    responseDict = {}
    paymentgatewayresponseDict = {}

    # Extracting client IP address
    if request.headers.getlist("X-Forwarded-For"):
        client_ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
        client_ip = request.remote_addr

    loginBrowser = request.headers.get("Sec-Ch-Ua")
    if loginBrowser:
        loginBrowseData = loginBrowser.split(";")
        browser = loginBrowseData[0]
    else:
        loginBrowseData = request.headers.get('User-Agent').split(";")
        browser = loginBrowseData[0]

    # secretKey = "f51085df02812201344f6f0cb6959647"
    # encryption_key = bytes(secretKey, 'utf-8')
    # responseEncrypt = encrypt(sample_static_campus_payin_data,encryption_key)
    # encryption_data = responseEncrypt.get('encryption_data')
    # iv = responseEncrypt.get('iv')

    transactionAPIId = ""
    userId = ""
    requestData = [{"encryption_data":encryption_data,"iv":iv}]

    # Here Create Client Logs Table
    save_client_table = save_client_logs_data(userId,"payin","intent","getintentpaymenturl",None,requestData,client_ip,"api")

    try:
        if encryption_data and iv and merchant_id and api_key:
            merchant_queryset = Users.objects(merchantUniqueNumber=merchant_id,status=1).first()
            if not merchant_queryset:
                data_status["result"]="Invalid merchant id!!"
                return data_status

            check_kyc_status = merchant_kyc_status(str(merchant_queryset.id))
            if check_kyc_status.get("responseStatus") != 1:
                data_status["result"]="Merchant KYC is not completed please contact to admin!!"
                return data_status
            kycStatus = check_kyc_status.get("merchantKycDetails", {}).get("kycStatus")
            if kycStatus == False:
                data_status["result"]="Merchant KYC is not completed please contact to admin!!"
                return data_status

            if not merchant_queryset.patternId.payInPaymentGatewayId or merchant_queryset.enablePayin == False:
                data_status["result"]="Payin option is disabled please contact to admin!!"
                return data_status

            print("(((((((apikey)))))))",api_key)
            print("(((((((userId)))))))",merchant_queryset.id)

            api_security_queryset = ApiSecurities.objects(apiKey=api_key,apiType="payment_gateway",userId=str(merchant_queryset.id),status=1).first()
            if not api_security_queryset:
                data_status["result"]="Invalid api key!!"
                return data_status

            if client_ip not in api_security_queryset.ipAddressList:
                data_status["result"]="Your ip adress is not whitelisted please contact admin!!"
                return data_status

            try:
                secretKey = api_security_queryset.secretKey
                encryption_key = bytes(secretKey, 'utf-8')

                jsonData = decrypt(encryption_data,encryption_key,iv)
                print(jsonData,"JSON DATA")
                decryptResponse = json.loads(jsonData)
            except Exception as e:
                app.logger.error(traceback.format_exc())
                data_status["result"]="Invalid encryption data!!"
                return data_status
            
            graampay_check = decryptResponse.get("graampay_check")
            payinPaymentGatewaysList = [str(each_payout_pg.id) for each_payout_pg in merchant_queryset.patternId.payinPaymentGatewaysList]

            print("(((((((payinPaymentGatewaysList)))))))",payinPaymentGatewaysList)
            print("(((((((graampay_check)))))))",graampay_check)

            payin_gate_way_queryset = TransactionAPI.objects(id__in=payinPaymentGatewaysList,code=graampay_check,status=1).first()
            if not payin_gate_way_queryset:
                data_status["result"]="Payin option is disabled please contact to admin!!"
                return data_status

            transactionAPIId = str(payin_gate_way_queryset.id)

            # requestData=[decryptResponse]
            userId = str(merchant_queryset.id)

            # Here Update some data in Client Logs Table
            save_client_table.update(userId=ObjectId(userId),transactionAPIId=ObjectId(transactionAPIId))
        
            payInPaymentGatewayId = str(payin_gate_way_queryset.id)
            
            paymentGateWayCode = payin_gate_way_queryset.code

            api_key = decryptResponse.get("api_key")
            name = decryptResponse.get("name")
            phone = decryptResponse.get("phone")
            email = decryptResponse.get("email")
            amount = decryptResponse.get("amount")
            note = decryptResponse.get("description")
            currency=decryptResponse.get("currency")
            orderId = decryptResponse.get("order_id")

            # Accurepay extra request data
            mode = decryptResponse.get("mode")
            address_line_1 = decryptResponse.get("address_line_1")
            address_line_2 = decryptResponse.get("address_line_2")
            city = decryptResponse.get("city")
            state = decryptResponse.get("state")
            country = decryptResponse.get("country")
            zip_code = decryptResponse.get("zip_code")
            udf1 = decryptResponse.get("udf1","")
            udf2 = decryptResponse.get("udf2","")
            udf3 = decryptResponse.get("udf3","")
            udf4 = decryptResponse.get("udf4","")
            udf5 = decryptResponse.get("udf5","")
            return_url = domain+"/api/mobile/payin_call_back_url"

            if not api_key and not orderId and not name and not phone and not email and not amount and not currency and not city and not state and not zip_code:
                data_status['result']="Required Fields are missing!!"
                return data_status

            # if float(amount)<100:
            #     data_status['result']="Amount should be greater than or equals to 100.00"
            #     return data_status

            check_transaction_limits = merchant_transaction_limit_settings("Payin",payInPaymentGatewayId,userId,amount)
            if check_transaction_limits.get("responseStatus") == 0:
                data_status['result']=check_transaction_limits.get("result")
                return data_status

            merchantUniqueNumber=str(merchant_queryset.merchantUniqueNumber)
            mid_extracted = merchantUniqueNumber[1:].lstrip("0")
            pgOrderId=transaction_id_prefix+str(mid_extracted)+str(orderId)
            # pgOrderId = merchant_queryset.merchantUniqueNumber+"-"+decryptResponse.get("order_id")
            if api_key == api_security_queryset.apiKey:

                check_order = WalletTransactions.objects(orderId=orderId,userId=str(userId)).first()
                if check_order:
                    data_status["result"]="This order id is already exisit!!"
                    return data_status

                save_api_request_data_table = ApiRequestData(
                    userId=userId,
                    userOrderId=orderId,
                    orderId=merchant_queryset.merchantUniqueNumber+"-"+orderId,
                    requestData=[decryptResponse],
                    createdOn=datetime.datetime.now(),
                    status=1
                    )
                save_table=save_api_request_data_table.save()

                currentDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                routing_switch_counts_queryset = RoutingSwitchCounts.objects(userId=userId,transactionAPIId=payInPaymentGatewayId,createdOn=currentDate).first()
                if routing_switch_counts_queryset:
                    numberOfFails = routing_switch_counts_queryset.numberOfFails
                    numberOfSuccess = routing_switch_counts_queryset.numberOfSuccess
                else:
                    save_routing_switch_table=save_routing_switch_logs_data(userId,"payin",transactionAPIId)

                apiType="api"
                if paymentGateWayCode == "AccurePay_PayIn":
                    get_api_key = ""
                    get_salt = ""
                    get_base_url = ""
                    for each_key in payin_gate_way_queryset.paramsList:
                        get_key = each_key.get("key")
                        if get_key == "api_key":
                            get_api_key = each_key.get("value")
                        if get_key == "salt":
                            get_salt = each_key.get("value")
                        if get_key == "base_url":
                            get_base_url = each_key.get("value")
                    ###################################################### Accurepay Payin Code #########################################################################
                    paymentgatewayresponseDict = accure_payin_payment_intent(get_api_key,get_salt,get_base_url,name,phone,email,amount,pgOrderId,userId,currency,orderId,mode,address_line_1,address_line_2,city,state,country,zip_code,udf1,udf2,udf3,udf4,udf5,return_url,transactionAPIId,client_ip,note,apiType)
                    #################################################################################################################################################
                elif paymentGateWayCode == "WowPe_Payin":
                    get_client = ""
                    get_secret = ""
                    get_base_url = ""
                    for each_key in payin_gate_way_queryset.paramsList:
                        get_key = each_key.get("key")
                        if get_key == "api_key":
                            get_client = each_key.get("value")
                        if get_key == "secret_key":
                            get_secret = each_key.get("value")
                        if get_key == "base_url":
                            get_base_url = each_key.get("value")
                    

                    ###################################################### Wowpe Payin Code #########################################################################
                    paymentgatewayresponseDict = wowpe_payin_payment_intent(get_client,get_secret,get_base_url,name,phone,email,amount,pgOrderId,userId,payInPaymentGatewayId,client_ip,note,apiType)
                    ################################################################################################################################################
                elif paymentGateWayCode == "Campuslinkpro_Payin":
                    print("((((((((((((((((((Campuslinkpro_Payin))))))))))))))))))")
                    get_base_url = ""
                    api_key = ""
                    secret_key = ""
                    graampay_check = ""
                    for each_key in payin_gate_way_queryset.paramsList:
                        get_key = each_key.get("key")
                        if get_key == "get_base_url":
                            get_base_url = each_key.get("value")
                        if get_key == "api_key":
                            api_key = each_key.get("value")
                        if get_key == "secret_key":
                            secret_key = each_key.get("value")
                        if get_key == "graampay_check":
                            graampay_check = each_key.get("value")
                   
                    transactionType="SALE"
                    # pgOrderId = merchant_queryset.merchantUniqueNumber+"-"+"TPSL"+str(orderId)
                    # pgOrderId = merchant_queryset.merchantUniqueNumber+"-"+str(orderId)
                    ###################################################### Wowpe Payin Code #########################################################################
                    paymentgatewayresponseDict = create_campuslinkpro_payment_link(get_base_url,api_key,secret_key,graampay_check,pgOrderId,note,amount,currency,name,phone,email,payInPaymentGatewayId,client_ip,apiType,userId)
                    ###############################################################################################################################################

                elif paymentGateWayCode == "Fstac_Payin":
                    get_client = ""
                    get_secret = ""
                    get_base_url = ""
                    for each_key in payin_gate_way_queryset.paramsList:
                        get_key = each_key.get("key")
                        if get_key == "api_key":
                            get_client = each_key.get("value")
                        if get_key == "secret_key":
                            get_secret = each_key.get("value")
                        if get_key == "base_url":
                            get_base_url = each_key.get("value")
                    

                    ###################################################### Fstac Payin Code ##################################################################################################
                    paymentgatewayresponseDict = fstac_payin_payment_intent(get_client,get_secret,get_base_url,name,phone,email,amount,pgOrderId,userId,payInPaymentGatewayId,client_ip,note,apiType)
                    ##########################################################################################################################################################################

                elif paymentGateWayCode == "Setu_Payin":
                    get_client = ""
                    get_secret = ""
                    get_base_url = ""
                    grant_type = ""
                    merchant_id = ""
                    get_auth_url = ""
                    merchantVpa = "jiocinema-uat@setuaxis"
                    for each_key in payin_gate_way_queryset.paramsList:
                        get_key = each_key.get("key")
                        if get_key == "api_key":
                            get_client = each_key.get("value")
                        if get_key == "secret_key":
                            get_secret = each_key.get("value")
                        if get_key == "base_url":
                            get_base_url = each_key.get("value")
                        if get_key == "grant_type":
                            grant_type = each_key.get("value")
                        if get_key == "merchant_id":
                            merchant_id = each_key.get("value")
                        if get_key == "auth_url":
                            get_auth_url = each_key.get("value")

                    ###################################################### Setu Payin Code ##################################################################################################
                    paymentgatewayresponseDict = setu_payin_payment_sqr(get_client,get_secret,get_base_url,get_auth_url,grant_type,merchant_id,merchantVpa,note,orderId,amount,userId,payInPaymentGatewayId,client_ip,apiType)
                    ##########################################################################################################################################################################
                else:
                    data_status["result"]="Please contact to admin to enable payin option!!"
                    save_client_table.update(responseData=[data_status],responseDate=datetime.datetime.now())
                    # For count update number of failures in routing switch counts table
                    if routing_switch_counts_queryset:
                        existingFailuresCount = routing_switch_counts_queryset.numberOfFails
                        updateFailuresCount = existingFailuresCount+1
                        routing_switch_counts_queryset.update(numberOfFails=updateFailuresCount)
                    else:
                        save_routing_switch_table.update(numberOfFails=1)
                    return data_status

                print("((((((((((paymentgatewayresponseDict))))))))))",paymentgatewayresponseDict)

                if paymentgatewayresponseDict.get("responseStatus") == 1:
                    wallet_transaction_table = WalletTransactions(
                        userId = userId,
                        amount = round(float(amount),2),
                        grandTotal=round(float(amount),2),
                        paymentGatewayId = payInPaymentGatewayId,
                        currency=currency,
                        paymentType = "UPI",
                        creditType = "Credit",
                        transactionId = "",
                        transactionData = paymentgatewayresponseDict.get("transactionData"),
                        orderId = orderId,
                        walletLog="",
                        userType="user",
                        createdBy = None,
                        createdOn = datetime.datetime.now(),
                        location = location,
                        platform = "api",
                        agent = agent,
                        customerEmail = email,
                        customerName = name,
                        customerPhonenumber = phone,
                        previousBalance=0,
                        currentBalance=0,
                        paymentLinkId = None,
                        PaymentButtonId = None,
                        paymentPageId = None,
                        errorMessage = "",
                        paymentChannel = paymentgatewayresponseDict.get("paymentChannel"),
                        bankRefId="",
                        cardmasked="",
                        pgOrderId=paymentgatewayresponseDict.get("pgOrderId"),
                        customerVpa="",
                        udf1=udf1,
                        udf2=udf2,
                        udf3=udf3,
                        udf4=udf4,
                        udf5=udf5,
                        clientIp=client_ip,
                        commissionCharges={},
                        status = 3
                        ).save()
                    save_table.update(reponseData=paymentgatewayresponseDict.get("transactionData"))
                    responseDict={
                    "order_id":orderId,
                    "payment_request_id":paymentgatewayresponseDict.get("payment_request_id"),
                    "upi_intent_url":paymentgatewayresponseDict.get("upi_intent_url")
                    }
                    data_status["responseStatus"]=1
                    data_status["result"]="Success"
                    data_status["responseBody"]=responseDict
                    save_client_table.update(responseData=[data_status],responseDate=datetime.datetime.now())

                    # For count update number of success in routing switch counts table
                    # if routing_switch_counts_queryset:
                    #     existingSuccessCount = routing_switch_counts_queryset.numberOfSuccess
                    #     updateSuccessCount = existingSuccessCount+1

                    #     existingSuccessAmount = float(routing_switch_counts_queryset.maxVolume)
                    #     updateSuccessAmount = float(existingSuccessAmount)+float(amount)

                    #     routing_switch_counts_queryset.update(numberOfSuccess=updateSuccessCount,maxVolume=updateSuccessAmount)
                    # else:
                    #     save_routing_switch_table.update(numberOfSuccess=1,maxVolume=float(amount))
                    return data_status

                else:
                    data_status["responseStatus"]=paymentgatewayresponseDict.get("responseStatus")
                    data_status["result"]=paymentgatewayresponseDict.get("result")
                    save_client_table.update(responseData=[data_status],responseDate=datetime.datetime.now())
                    # For count update number of failures in routing switch counts table
                    if routing_switch_counts_queryset:
                        existingFailuresCount = routing_switch_counts_queryset.numberOfFails
                        updateFailuresCount = existingFailuresCount+1

                        routing_switch_counts_queryset.update(numberOfFails=updateFailuresCount)
                    else:
                        save_routing_switch_table.update(numberOfFails=1)
                    return data_status

            else:
                data_status["result"]="Mis-matched api keys!!"
                save_client_table.update(responseData=[data_status],responseDate=datetime.datetime.now())
                # For count update number of failures in routing switch counts table
                if routing_switch_counts_queryset:
                    existingFailuresCount = routing_switch_counts_queryset.numberOfFails
                    updateFailuresCount = existingFailuresCount+1

                    routing_switch_counts_queryset.update(numberOfFails=updateFailuresCount)
                else:
                    save_routing_switch_table.update(numberOfFails=1)
                return data_status
        else:
            data_status["result"]="Required fields are missing!!"
            save_client_table.update(responseData=[data_status],responseDate=datetime.datetime.now())
            return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"]="Unable to get intent data!!"
        save_client_table.update(responseData=[data_status],responseDate=datetime.datetime.now())
        exceptionData = [traceback.format_exc()]
        exception_log_table = save_exception_logs_data(None,"payin","intent","getintentpaymenturl",exceptionData,client_ip,"api")
        return data_status


@payin_apis.route("/getpayinpaymentstatus", methods=["POST"])
def getpayinpaymentstatus():
    print(request.headers,'*****request.headers******')
    data_status = {"responseStatus":0,"result":""}
    if SERVER_STATUS == "DOWN":
        data_status["result"]= SERVER_MAINTAINCE_MESSAGE
        return data_status
        
    merchant_id = request.headers.get("Merchant-Id","")
    api_key = request.headers.get("Api-Key","")
    order_id = request.form.get("order_id","")

    # Extracting client IP address
    if request.headers.getlist("X-Forwarded-For"):
        client_ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
        client_ip = request.remote_addr

    loginBrowser = request.headers.get("Sec-Ch-Ua")
    if loginBrowser:
        loginBrowseData = loginBrowser.split(";")
        browser = loginBrowseData[0]
    else:
        loginBrowseData = request.headers.get('User-Agent').split(";")
        browser = loginBrowseData[0]
        
    responseDict = {}
    payinPaymentstatusResponseDict = {}
    try:
        if not order_id and not merchant_id and not api_key:
            data_status["result"] = "Required fields are missing!!"
            return data_status

        merchant_queryset = Users.objects(merchantUniqueNumber=merchant_id,status=1).first()
        if not merchant_queryset:
            data_status["result"]="Invalid merchant id!!"
            return data_status

        check_kyc_status = merchant_kyc_status(str(merchant_queryset.id))
        if check_kyc_status.get("responseStatus") != 1:
            data_status["result"]="Merchant KYC is not completed please contact to admin!!"
            return data_status
        kycStatus = check_kyc_status.get("merchantKycDetails", {}).get("kycStatus")
        if kycStatus == False:
            data_status["result"]="Merchant KYC is not completed please contact to admin!!"
            return data_status

        api_security_queryset = ApiSecurities.objects(apiKey=api_key,apiType="payment_gateway",userId=str(merchant_queryset.id),status=1).first()
        if not api_security_queryset:
            data_status["result"]="Invalid api key!!"
            return data_status

        if client_ip not in api_security_queryset.ipAddressList:
            data_status["result"]="Your ip adress is not whitelisted please contact admin!!"
            return data_status
        
        wallet_transactions_queryset = WalletTransactions.objects(orderId=order_id,userId=str(merchant_queryset.id)).first()
        if not wallet_transactions_queryset:
            data_status["result"]="Invalid Order Id"
            return data_status

        pgOrderId = str(wallet_transactions_queryset.pgOrderId)
        payInPaymentGatewayId = str(wallet_transactions_queryset.paymentGatewayId.id)
        payin_gate_way_queryset = TransactionAPI.objects(id=str(payInPaymentGatewayId)).first()
        if not payin_gate_way_queryset:
            data_status["result"]="Invalid request found"
            return data_status
        paymentGateWayCode = payin_gate_way_queryset.code
        paramsList = payin_gate_way_queryset.paramsList

        ############################################## Slab Calculation for Payin #########################################################################
        payment_mode_queryset = PaymentMode.objects(paymentMode="UPI").first()
        paymentModeId = str(payment_mode_queryset.id)
        sub_payment_mode_queryset = SubPaymentModes.objects(paymentModeId=paymentModeId,subPaymentModeType="UPI").first()
        subPaymentModeId = str(sub_payment_mode_queryset.id)
        patternId = str(merchant_queryset.patternId.id)

        ###################################################################################################################################################
        
        if paymentGateWayCode == "AccurePay_PayIn":
            get_api_key = ""
            get_salt = ""
            get_base_url=''
            for each_key in paramsList:
                
                get_key = each_key.get("key")
                
                if get_key == "api_key":
                    get_api_key = each_key.get("value")
                    
                if get_key == "salt":
                    get_salt = each_key.get("value")

                if get_key == "base_url":
                    get_base_url = each_key.get("value")
            
            ######################################################### Check Accurepay Payin Payment Status #############################################################
            payinPaymentstatusResponseDict = check_accurepay_payin_paymentstatus(get_api_key,get_salt,get_base_url,pgOrderId)
            ########################################################################################################################################################

        elif paymentGateWayCode == "WowPe_Payin":
            get_api_key = ""
            get_secret_key = ""
            get_base_url=''
            for each_key in paramsList:
                
                get_key = each_key.get("key")
                
                if get_key == "api_key":
                    get_api_key = each_key.get("value")
                    
                if get_key == "secret_key":
                    get_secret_key = each_key.get("value")

                if get_key == "base_url":
                    get_base_url = each_key.get("value")


            ######################################################### Check Wowpe Payin Payment Status #############################################################
            payinPaymentstatusResponseDict = check_wowpe_payin_paymentstatus(get_api_key,get_secret_key,get_base_url,pgOrderId)
            ########################################################################################################################################################

        elif paymentGateWayCode == "Fstac_Payin":
            get_api_key = ""
            get_secret_key = ""
            get_base_url=''
            for each_key in paramsList:
                
                get_key = each_key.get("key")
                
                if get_key == "api_key":
                    get_api_key = each_key.get("value")
                    
                if get_key == "secret_key":
                    get_secret_key = each_key.get("value")

                if get_key == "base_url":
                    get_base_url = each_key.get("value")


            ######################################################### Check Fstac Payin Payment Status #############################################################
            payinPaymentstatusResponseDict = check_fstac_payin_paymentstatus(get_api_key,get_secret_key,get_base_url,pgOrderId)
            ########################################################################################################################################################

        elif paymentGateWayCode == "Setu_Payin":
            get_client = ""
            get_secret = ""
            get_base_url = ""
            grant_type = ""
            merchant_id = ""
            get_auth_url = ""
            for each_key in payin_gate_way_queryset.paramsList:
                get_key = each_key.get("key")
                if get_key == "api_key":
                    get_client = each_key.get("value")
                if get_key == "secret_key":
                    get_secret = each_key.get("value")
                if get_key == "base_url":
                    get_base_url = each_key.get("value")
                if get_key == "grant_type":
                    grant_type = each_key.get("value")
                if get_key == "merchant_id":
                    merchant_id = each_key.get("value")
                if get_key == "auth_url":
                    get_auth_url = each_key.get("value")

            ###################################################### Setu Payin Payment Status ##################################################################################################
            paymentgatewayresponseDict = check_setu_payin_paymentstatus(get_client,get_secret,get_base_url,get_auth_url,grant_type,merchant_id,payInPaymentGatewayId,client_ip,apiType,userId,pgOrderId)
            ##########################################################################################################################################################################
        elif paymentGateWayCode == "Campuslinkpro_Payin":
            print("((((((((((((((((((Campuslinkpro_Payin status CHECK))))))))))))))))))")
            get_base_url = ""
            api_key = ""
            secret_key = ""
            graampay_check = ""
            for each_key in payin_gate_way_queryset.paramsList:
                get_key = each_key.get("key")
                if get_key == "get_base_url":
                    get_base_url = each_key.get("value")
                if get_key == "api_key":
                    api_key = each_key.get("value")
                if get_key == "secret_key":
                    secret_key = each_key.get("value")
                if get_key == "graampay_check":
                    graampay_check = each_key.get("value")
           
            # transactionType="SALE"
            # # pgOrderId = merchant_queryset.merchantUniqueNumber+"-"+"TPSL"+str(orderId)
            # pgOrderId = merchant_queryset.merchantUniqueNumber+"-"+str(orderId)
            transactionDate = wallet_transactions_queryset.createdOn.strftime("%d-%m-%Y")
            ###################################################### Wowpe Payin Code #########################################################################
            payinPaymentstatusResponseDict = campuslinkpro_status(get_base_url,api_key,secret_key,pgOrderId,transactionDate,graampay_check)
            print(payinPaymentstatusResponseDict,"(((((((((((((paymentgatewayresponseDict)))))))))))))")
            ###############################################################################################################################################
       

        else:
            data_status["result"]="Please contact to admin to enable payin option!!"
            return data_status

        if payinPaymentstatusResponseDict.get("responseStatus") == 1:
            if payinPaymentstatusResponseDict.get("bankRefNo"):
                bank_reference_number = payinPaymentstatusResponseDict.get("bankRefNo")
            else:
                bank_reference_number = wallet_transactions_queryset.bankRefId

            if payinPaymentstatusResponseDict.get("paymentStatus") == 1:
                order_queryset = WalletTransactions.objects(orderId=order_id).first()
                amount=float(order_queryset.amount)
                transactionAmount = float(order_queryset.amount)
                errorMessage=""
                if (float(payinPaymentstatusResponseDict.get("orderAmount")) >= float(amount)) and order_queryset.status!=6:
                    amountstatus = 1
                    errorMessage = "Success"
                else:
                    amountstatus = 6
                    errorMessage = "Insufficient amount credited!!"
                
                if order_queryset.status!=1 and amountstatus==1:
                    commissionCharges = slab_calculation_for_payin(amount,paymentModeId,subPaymentModeId,patternId,payInPaymentGatewayId)
                    if commissionCharges.get("transactionAmount"):
                        transactionAmount=commissionCharges.get("transactionAmount")
                    else:
                        transactionAmount=transactionAmount

                    pgOrderId = str(order_queryset.pgOrderId)
                    payInPaymentGatewayId = str(order_queryset.paymentGatewayId.id)
                    
                    transaction_id=str(order_queryset.transactionId)

                    balanceResult=user_payin_balance_update(str(order_queryset.userId.id),float(transactionAmount),"Credit",str(payInPaymentGatewayId))
                    if balanceResult.get('responseStatus')==0:
                        data_status["result"]="Unable to connect with server. Please Try again."
                        return data_status
                                
                    # userbalance_queryset = Users.objects(id=str(order_queryset.userId.id)).modify(inc__walletBalance=float(transactionAmount),new=True)
                    # updateAmount = userbalance_queryset.walletBalance
                    # actuallBalance = float(updateAmount)-float(transactionAmount)

                    # payin_balance_queryset1 = PayinBalances.objects(userId=str(order_queryset.userId.id),transactionAPIId=str(payInPaymentGatewayId)).first()
                    # if payin_balance_queryset1:
                    #     payin_balance_queryset = PayinBalances.objects(userId=str(order_queryset.userId.id),transactionAPIId=str(payInPaymentGatewayId)).modify(inc__currentBalance=float(transactionAmount),new=True)
                    #     currentBalance=payin_balance_queryset.currentBalance
                    #     previousBalance=float(currentBalance)-float(transactionAmount)

                    #     payin_balance_queryset.update(previousBalance=round(float(previousBalance),2),updatedOn=datetime.datetime.now())

                        # previousBalance=payin_balance_queryset.currentBalance
                        # currentBalance=float(previousBalance)+float(transactionAmount)
                        # payin_balance_queryset.update(previousBalance = round(float(previousBalance),2),currentBalance=round(float(currentBalance),2),updatedOn=datetime.datetime.now())
                        
                    payinbalancelogs_queryset=PayinBalanceLogs(
                        transactionAPIId=str(payInPaymentGatewayId),
                        userId=str(order_queryset.userId.id),
                        previousBalance=round(float(balanceResult.get('transactionPreviousBalance')),2),
                        currentBalance=round(float(balanceResult.get('transactionCurrentBalance')),2),
                        orderId=order_queryset.orderId,
                        amount=round(float(amount),2),
                        grandTotal=round(float(transactionAmount),2),
                        transferType="Credit",
                        userType="user",
                        transactionId=transaction_id,
                        createdOn=datetime.datetime.now(),
                        status=1
                        ).save()
                    # else:
                    #     payin_balance_save=PayinBalances(
                    #         transactionAPIId=str(payInPaymentGatewayId),
                    #         userId = str(userbalance_queryset.id),
                    #         previousBalance=0,
                    #         currentBalance=round(float(transactionAmount),2),
                    #         createdOn=datetime.datetime.now(),
                    #         status=1
                    #         ).save()
                    #     payinbalancelogs_queryset=PayinBalanceLogs(
                    #         transactionAPIId=str(payInPaymentGatewayId),
                    #         userId=str(userbalance_queryset.id),
                    #         previousBalance=0,
                    #         currentBalance=round(float(transactionAmount),2),
                    #         orderId=order_queryset.orderId,
                    #         amount=round(float(amount),2),
                    #         grandTotal=round(float(transactionAmount),2),
                    #         transferType="Credit",
                    #         userType="user",
                    #         transactionId=transaction_id,
                    #         createdOn=datetime.datetime.now(),
                    #         status=1
                    #         ).save()
                    order_queryset.update(
                        status=1,payInResponseCallBackData=payinPaymentstatusResponseDict.get("transactionData"),
                        responseCallBackTime=datetime.datetime.now(),
                        transactionId=transaction_id,bankRefId=bank_reference_number,
                        currency=payinPaymentstatusResponseDict.get("currency"),errorMessage=payinPaymentstatusResponseDict.get("message"),grandTotal=round(float(transactionAmount),2),walletLog="Wallet Balance is added with the amount of " + str(amount) + ".",previousBalance=round(float(balanceResult.get('userPreviousBalance')),2),currentBalance=round(float(balanceResult.get('userCurrentBalance')),2),commissionCharges=commissionCharges)
                else:
                    order_queryset.update(status=amountstatus,payInResponseCallBackData=payinPaymentstatusResponseDict.get("transactionData"),responseCallBackTime=datetime.datetime.now(),transactionId=order_queryset.transactionId,bankRefId=bank_reference_number,currency=payinPaymentstatusResponseDict.get("currency"),errorMessage=errorMessage,grandTotal=round(float(transactionAmount),2),walletLog="Wallet Balance is added with the amount of " + str(amount) + ".")

            elif payinPaymentstatusResponseDict.get("paymentStatus")==0 or payinPaymentstatusResponseDict.get("paymentStatus")==4:
                order_queryset = WalletTransactions.objects(orderId=order_id).first()
                amount=float(order_queryset.amount)
                if order_queryset.status==1:
                    amount=float(order_queryset.amount)
                    transactionAmount = float(order_queryset.grandTotal)
                    transaction_id=order_queryset.transactionId
                    
                    balanceResult=user_payin_balance_update(str(order_queryset.userId.id),float(order_queryset.grandTotal),"Debit",str(payInPaymentGatewayId))
                    if balanceResult.get('responseStatus')==0:
                        data_status["result"]="Unable to connect with server. Please Try again."
                        return data_status

                    # latest_user_queryset = Users.objects(id=str(order_queryset.userId.id)).modify(dec__walletBalance=float(order_queryset.grandTotal),new=True)
                    # updateAmount = latest_user_queryset.walletBalance
                    # actuallBalance = float(updateAmount)+float(transactionAmount)

                    # latest_user_queryset = Users.objects(id=str(order_queryset.userId.id)).first()
                    # actuallBalance = latest_user_queryset.walletBalance
                    # updateAmount = float(actuallBalance)-float(order_queryset.grandTotal)
                    # latest_user_queryset.update(walletBalance = round(float(updateAmount),2))

                    # latest_payin_balance_queryset1 = PayinBalances.objects(userId=str(order_queryset.userId.id),transactionAPIId=str(payInPaymentGatewayId)).first()
                    # if latest_payin_balance_queryset1:

                    #     latest_payin_balance_queryset = PayinBalances.objects(userId=str(order_queryset.userId.id),transactionAPIId=str(payInPaymentGatewayId)).modify(dec__currentBalance=float(transactionAmount),new=True)

                    #     currentBalance=latest_payin_balance_queryset.currentBalance
                    #     previousBalance=float(currentBalance)+float(order_queryset.grandTotal)

                    #     latest_payin_balance_queryset.update(previousBalance = round(float(previousBalance),2),updatedOn=datetime.datetime.now())
                        
                    payinbalancelogs_queryset=PayinBalanceLogs(
                        transactionAPIId=str(payInPaymentGatewayId),
                        userId=str(order_queryset.userId.id),
                        previousBalance=float(balanceResult.get('transactionPreviousBalance')),
                        currentBalance=float(balanceResult.get('transactionCurrentBalance')),
                        orderId=order_queryset.orderId,
                        amount=round(float(amount),2),
                        grandTotal=round(float(order_queryset.grandTotal),2),
                        transferType="Debit",
                        userType="user",
                        transactionId=transaction_id,
                        createdOn=datetime.datetime.now(),
                        status=1
                        ).save()
                    # else:
                    #     payin_balance_save=PayinBalances(
                    #         transactionAPIId=str(payInPaymentGatewayId),
                    #         userId = str(latest_user_queryset.id),
                    #         previousBalance=0,
                    #         currentBalance=0,
                    #         createdOn=datetime.datetime.now(),
                    #         status=1
                    #         ).save()

                    #     payinbalancelogs_queryset=PayinBalanceLogs(
                    #         transactionAPIId=str(payInPaymentGatewayId),
                    #         userId=str(latest_user_queryset.id),
                    #         previousBalance=0,
                    #         currentBalance=0,
                    #         orderId=order_queryset.orderId,
                    #         amount=round(float(amount),2),
                    #         grandTotal=round(float(transactionAmount),2),
                    #         transferType="Debit",
                    #         userType="user",
                    #         transactionId=transaction_id,
                    #         createdOn=datetime.datetime.now(),
                    #         status=1
                    #         ).save()
                    rorderId = random_digit_generate(16)
                    wallet_transaction_table = WalletTransactions(
                        userId = str(order_queryset.userId.id),
                        amount = round(float(order_queryset.amount),2),
                        grandTotal=round(float(order_queryset.grandTotal),2),
                        paymentGatewayId = str(payInPaymentGatewayId),
                        currency=order_queryset.currency,
                        paymentType = order_queryset.paymentType,
                        creditType = "Debit",
                        transactionId = transaction_id,
                        transactionData = payinPaymentstatusResponseDict.get("transactionData"),
                        orderId = str(rorderId),
                        walletLog="Wallet Balance is refunded with the amount of " + str(order_queryset.amount) + ".",
                        userType="user",
                        createdBy = None,
                        createdOn = datetime.datetime.now(),
                        location = "",
                        platform = "api",
                        agent = "",
                        customerEmail = order_queryset.customerEmail,
                        customerName = order_queryset.customerName,
                        customerPhonenumber = order_queryset.customerPhonenumber,
                        previousBalance=round(float(balanceResult.get('userPreviousBalance')),2),
                        currentBalance=round(float(balanceResult.get('userCurrentBalance')),2),
                        paymentLinkId = None,
                        PaymentButtonId = None,
                        paymentPageId = None,
                        errorMessage = "Refunded",
                        paymentChannel = "Wowpe",
                        bankRefId=order_queryset.bankRefId,
                        cardmasked="",
                        pgOrderId=order_queryset.pgOrderId,
                        slabId=str(order_queryset.slabId.id),
                        walletTransactionId=str(order_queryset.id),
                        commissionCharges=order_queryset.commissionCharges,
                        customerVpa="",
                        clientIp=client_ip,
                        status = 5
                        ).save()

                    order_queryset.update(status=payinPaymentstatusResponseDict.get("paymentStatus"),payInResponseCallBackData=payinPaymentstatusResponseDict.get("transactionData"),responseCallBackTime=datetime.datetime.now(),transactionId=wallet_transactions_queryset.transactionId,bankRefId=bank_reference_number,currency=payinPaymentstatusResponseDict.get("currency"),errorMessage=payinPaymentstatusResponseDict.get("message"),walletLog="Wallet Balance is added with the amount of " + str(amount) + ".")
                else:
                    order_queryset.update(status=payinPaymentstatusResponseDict.get("paymentStatus"),payInResponseCallBackData=payinPaymentstatusResponseDict.get("transactionData"),responseCallBackTime=datetime.datetime.now(),transactionId=order_queryset.transactionId,bankRefId=bank_reference_number,currency=payinPaymentstatusResponseDict.get("currency"),errorMessage=payinPaymentstatusResponseDict.get("message"),walletLog="Wallet Balance is added with the amount of " + str(amount) + ".")

            responseDict={
            'order_id':order_id,
            'amount':float(wallet_transactions_queryset.amount),
            'message':payinPaymentstatusResponseDict.get("message"),
            'payment_mode':payinPaymentstatusResponseDict.get("payment_mode"),
            'response_code':payinPaymentstatusResponseDict.get("response_code"),
            'transaction_id':wallet_transactions_queryset.transactionId,
            "bank_reference_number":bank_reference_number,
            "status":payinPaymentstatusResponseDict.get("status")
            }
            data_status["responseStatus"]=1
            data_status['result']=responseDict
            return data_status
        else:
            responseDict={
            "order_id":order_id,
            "status":"failed",
            "message":payinPaymentstatusResponseDict.get("message")
            }
            data_status["result"]=responseDict
            return data_status

    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"]="Unable to get payin payment status data!!"
        return data_status