from appservices.common.util import *

def generate_iv():
    iv_length = 16
    iv = os.urandom(iv_length)
    return iv

def axis_encrypt(data_to_encrypt, secret_hex_key):
    final_encrypted_payload_base64 = ""
    try:
        raw_data_to_encrypt = json.dumps(data_to_encrypt)
        final_encrypted_payload = b''
        secret_key_hex_bytes = unhexlify(secret_hex_key)
        iv = generate_iv()
        # print("Dynamic IV: ", hexlify(iv).decode())
        cipher = AES.new(secret_key_hex_bytes, AES.MODE_CBC, iv=iv)
        encrypted_bytes = cipher.encrypt(pad(raw_data_to_encrypt.encode('utf-8'), AES.block_size))
        final_encrypted_payload = iv + encrypted_bytes
        final_encrypted_payload_base64 = base64.b64encode(final_encrypted_payload).decode()
        return final_encrypted_payload_base64
    except Exception as e:
        print(traceback.format_exc())
        return final_encrypted_payload_base64

def axis_decrypt(encrypted, secret_key):
    decrypted_text = ''
    try:
        secret_key_hex_bytes = unhexlify(secret_key)
        encrypted_combined_bytes = base64.b64decode(encrypted)
        iv = encrypted_combined_bytes[:16]
        encrypted_payload = encrypted_combined_bytes[16:]
        cipher = AES.new(secret_key_hex_bytes, AES.MODE_CBC, iv=iv)
        decrypted_bytes = unpad(cipher.decrypt(encrypted_payload), AES.block_size)
        decrypted_text = decrypted_bytes.decode()
        return decrypted_text
    except Exception as e:
        print(traceback.format_exc())
        return decrypted_text

def validate_info(value):
    """Ensure the value is valid for inclusion in checksum."""
    return value.strip() if value and value != "null" and value != "None" else ""

def concatenate_values_for_checksum(data):
    """
    Recursively extract and concatenate all values from the JSON-like dictionary,
    excluding any 'checksum' key, to create a checksum string.
    """
    checksum_str = ""
    
    if isinstance(data, dict):
        for key, value in data.items():
            if key != "checksum":
                checksum_str += concatenate_values_for_checksum(value)
    elif isinstance(data, list):
        for item in data:
            checksum_str += concatenate_values_for_checksum(item)
    else:
        checksum_str += validate_info(str(data))
    
    return checksum_str


def encode_checksum_with_md5(data):
    # print("concatinated values for checksum",data)
    try:
        # Initialize the MD5 hash object and update it with UTF-8 encoded data
        md5_hash = hashlib.md5(data.encode('utf-8'))
        
        # Generate the MD5 checksum in hexadecimal format
        response = md5_hash.hexdigest()
        
        return response
    except Exception as e:
        raise RuntimeError("Internal server error") from e


def axis_beneficiary_registration(client_id, client_secret, get_api_key, channelId, 
    serviceRequestId, serviceRequestVersion, corpCode, userId, get_base_url, requestUUID,apiVersion, beneCode, beneName, beneAccNum, beneIfscCode="", beneBankName="",  beneEmailAddr1="", beneMobileNo=""):
    # Standardized response dictionary
    beniCreationDict = {"responseStatus": 0, "result": ""}
    key = get_api_key
    try:
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path ,key_path)
        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "userId": "",   #User who is initiating the transaction in corporate system, This is required when validation on initator userid need to incorporate
            "beneinsert": [{
                "apiVersion": apiVersion,
                "beneLEI": "",
                "beneCode": beneCode,
                "beneName": beneName,
                "beneAccNum": beneAccNum,
                "beneIfscCode": beneIfscCode,
                "beneAcType": "",
                "beneBankName": beneBankName,
                "beneAddr1": "",
                "beneAddr2": "",
                "beneAddr3": "",
                "beneCity": "",
                "beneState": "",
                "benePincode": "",
                "beneEmailAddr1": beneEmailAddr1,
                "beneMobileNo": beneMobileNo,
            }]
        }

        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        hash_value = encode_checksum_with_md5(concatenated_values)
        axis_request_body["checksum"] = hash_value

        print("Request Body before encrypt",axis_request_body)

        axis_request_body = axis_encrypt(axis_request_body, key)


        try:
            url = get_base_url + "/txb/v1/payee-mgmt/beneficiary-registration"
            print(url, "Bulk Registration URL")
            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": str(client_id),
                "X-IBM-Client-Secret": str(client_secret)
            }
            axis_payload = {
                "BeneficiaryRegistrationRequest": {
                    "SubHeader": {
                        "requestUUID": str(requestUUID), 
                        "serviceRequestId": str(serviceRequestId),
                        "serviceRequestVersion": str(serviceRequestVersion),
                        "channelId": str(channelId)
                    },
                    "BeneficiaryRegistrationRequestBodyEncrypted": str(axis_request_body)
                }
            }

            print(axis_payload, "Encrypted Beneficiary Registration Request body")
            print(headers, "Bulk Registration Headers")

            # API Logs
            # save_axis_api_log_table = save_api_logs_data(userId,"benecreation","",url,payinPaymentGatewayId,axis_payload,client_ip,apiType)

            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)
            print(axisResponseData.status_code, "Response status code")
            axis_response_json = axisResponseData.json()

            # API Logs
            # save_axis_api_log_table.update(responseData=[axis_response_json],responseDate=datetime.datetime.now())

            print(axis_response_json, "Encrypted Beneficiary Registration Response")

            encrypted_bene_resp_body  = axis_response_json.get("BeneficiaryRegistrationResponse", {}).get("BeneficiaryRegistrationResponseBodyEncrypted", {})

            if not axisResponseData:
                app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") +" status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                beniCreationDict["responseStatus"] = 0
                beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                return beniCreationDict

            decrypted_text = axis_decrypt(encrypted_bene_resp_body, key)

            jsondecryptResponse = json.loads(decrypted_text)
            print(jsondecryptResponse, "Decrypted Beneficiary Registration Response Body")

            # changing BeneficiaryRegistrationResponseBodyEncrypted to BeneficiaryRegistrationResponseBody coz we decrypted so making key similar 
            beneficiary_response = {
                "BeneficiaryRegistrationResponse": {
                    "SubHeader": axis_response_json.get("BeneficiaryRegistrationResponse", {}).get("SubHeader", {}),
                    "BeneficiaryRegistrationResponseBody": jsondecryptResponse
                }
            }
            transactionData = [beneficiary_response]

            print(beneficiary_response, "Decrypted Beneficiary Registration Response")

            response_body = beneficiary_response.get("BeneficiaryRegistrationResponse", {}).get("BeneficiaryRegistrationResponseBody", {})
            subheaders = beneficiary_response.get("BeneficiaryRegistrationResponse", {}).get("SubHeader", {})


            ##extract requestuuid and channelid to validate and check if we got results for same fields we sent
            response_requestUUID= subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            data = response_body.get("data", {})
            status = response_body.get("status", "")
            message = response_body.get("message", "")
            if requestUUID == response_requestUUID and channelId  == response_channelId:
                if status == "S":
                    response_checksum = data.get("checksum",{})
                    # for response the checksum is calculated not for the body but for the data attribute within it
                    concatenated_response_values = concatenate_values_for_checksum(data)
                    # Generate the checksum for the response and check with given from bank
                    response_checksum_hash = encode_checksum_with_md5(concatenated_response_values)

                    if response_checksum_hash == response_checksum: # hash_value has the checksum value which we send  i.e request
                        beneList = []
                        bene_details = data.get("beneDetails", [])
                        if bene_details:
                            bene_name = bene_details[0].get("beneName")
                            # bene_code = bene_details[0].get("beneCode")
                            bene_ifsc_code = bene_details[0].get("beneIfscCode")
                            bene_acc_no = bene_details[0].get("beneAccNum")

                            bene_dct={
                                # "beneCode": bene_code,
                                "beneName":bene_name,
                                "beneIFSC": bene_ifsc_code,
                                "beneAccNum": beneAccNum,
                                "Status": "Pending"
                            }
                            beneList.append(bene_dct)

                        beniCreationDict.update({
                            "responseStatus": 1,
                            "result": "Success",
                            "beneList": beneList,
                            "responseList": bene_details,
                            "transactionData":transactionData,
                            "message": message,
                        })
                    else:
                        app.logger.error("Checksum mismatch with request and reponse data: ")
                        beniCreationDict.update({
                        "responseStatus": 0,
                        "result": "Failure",
                        "message": message,
                    })
                else:
                    beniCreationDict.update({
                        "responseStatus": 0,
                        "result": "Failure",
                        "message": message,
                    })
                    
            else:
                beniCreationDict.update({
                        "responseStatus": 0,
                        "result": "Failure",
                        "message": message,
                    })
                app.logger.error("RequestUUID or channelId mismatch with request and reponse data: ")
            return beniCreationDict

        except Exception as e:
            app.logger.error("Error during POST request or response processing: " + traceback.format_exc())
            beniCreationDict["result"] = "Failed to connect to the banking partner. Please try again later."

    except Exception as e:
        app.logger.error("Error during request preparation: " + traceback.format_exc())
        beniCreationDict["result"] = "Our banking partner server is down, please try again later."
    
    return beniCreationDict


def axis_beneficiary_enquiry(client_id, client_secret, key, channelId, get_base_url,apiVersion,requestUUID, serviceRequestId, serviceRequestVersion, corpCode,userId,fromDate,toDate,emailId,status,beneCode):
    axisResponseData = {}
    beniCreationDict = {}

    try:
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path, key_path)

        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "fromDate": fromDate,
            "toDate": toDate,
            "emailId": emailId,
            "status": status,   # /All , Inactive Active
            "beneCode": beneCode
            }
        
        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        
        hash_value = encode_checksum_with_md5(concatenated_values)

        axis_request_body["checksum"] = hash_value
        print(axis_request_body, "((((((((AXIS REQUEST BODY with beneficiary_enquiry checksum))))))))\n")

        axis_request_body = axis_encrypt(axis_request_body, key)

        try:
            url = get_base_url + "/txb/v1/payee-mgmt/beneficiary-enquiry"

            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": client_id,
                "X-IBM-Client-Secret": client_secret
            }

            axis_payload = {
            "BeneficiaryEnquiryRequest": {
                "SubHeader": {
                    "requestUUID": str(requestUUID),
                    "serviceRequestId": str(serviceRequestId),
                    "serviceRequestVersion": str(serviceRequestVersion),
                    "channelId": str(channelId)
                },
                "BeneficiaryEnquiryRequestBodyEncrypted": str(axis_request_body)
            }
        }
            print(url, "beneficiary enquiry AXIS")
            print(axis_payload, "AXIS payout READY TO SEND\n")

            try:
                axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)

                print(axisResponseData.status_code, "Response status code")
                

                axis_response_json = axisResponseData.json()
                print(axis_response_json, "AXIS PAYOUT beneficiary enquiry TEXT RESPONSE\n")

                encrypted_bene_resp_body  = axis_response_json.get("BeneficiaryEnquiryResponse", {}).get("BeneficiaryEnquiryResponseBodyEncrypted", {})

                if not encrypted_bene_resp_body:
                    app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") +" status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                    beniCreationDict["responseStatus"] = 0
                    beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                    return beniCreationDict
            except Exception as e:
                app.logger.error(traceback.format_exc())
                beniCreationDict["responseStatus"] = 0
                beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                return beniCreationDict

            # Decrypt the response
            decrypted_text = axis_decrypt(encrypted_bene_resp_body, key)
            print(decrypted_text,"decrypted_text check")
            jsondecryptResponse = json.loads(decrypted_text)

            print(jsondecryptResponse,"((((((((((((((((jsondecryptResponse AXIS))))))))))))))))")

            status_response = {
            "BeneficiaryEnquiryResponse": {
                "SubHeader": axis_response_json.get("BeneficiaryEnquiryResponse", {}).get("SubHeader", {}),
                "BeneficiaryEnquiryResponseBodyEncrypted": jsondecryptResponse
            }
            }       

            transactionData=[status_response]

            print(status_response, "Decrypted Status Registration Response\n")

            response_body = status_response.get("BeneficiaryEnquiryResponse", {}).get("BeneficiaryEnquiryResponseBodyEncrypted", {})
            subheaders = status_response.get("BeneficiaryEnquiryResponse", {}).get("SubHeader", {})


            response_requestUUID= subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            # Extract relevant fields from the response
            status = response_body.get("status", "")
            message = response_body.get("message", "")
            data = response_body.get("data", {})


            if requestUUID == response_requestUUID and channelId  == response_channelId:

                if status == "S":

                    response_checksum = data.get("checksum",{})
                    concatenated_response_values = concatenate_values_for_checksum(data)
                    response_checksum_hash = encode_checksum_with_md5(concatenated_response_values)

                    print(data,"((((((((((data))))))))))")
                    print(response_checksum_hash,"((((((((((response_checksum_hash))))))))))")
                    print(response_checksum,"((((((((((response_checksum))))))))))")

                    if response_checksum_hash == response_checksum:
                        beneList = []
                        bene_details = data.get("beneDetails", [])
                        if bene_details:
                            for bene_data in bene_details:
                                bene_name = bene_data.get("beneName")
                                # bene_code = bene_data.get("beneCode")
                                bene_ifsc_code = bene_data.get("beneIfscCode")
                                bene_acc_no = bene_data.get("beneAccNum")
                                status = bene_data.get("status")

                                bene_dct={
                                    # "beneCode": bene_code,
                                    "beneName":bene_name,
                                    "beneIFSC": bene_ifsc_code,
                                    "beneAccNum": bene_acc_no,
                                    "status": status
                                }
                                beneList.append(bene_dct)

                        beniCreationDict={
                            "responseStatus": 1,
                            "result": "Success",
                            "beneList": beneList,
                            "responseList": bene_details,
                            "transactionData":transactionData,
                            "jsondecryptResponse":jsondecryptResponse,
                            "message": message,
                        }
                        return beniCreationDict
                    else:
                        app.logger.error("Checksum mismatch with request and reponse data: ")
                        beniCreationDict["responseStatus"] = 0
                        beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                        return beniCreationDict
                elif status == "F":
                    beniCreationDict["responseStatus"] = 0
                    beniCreationDict["result"] = message
                    return beniCreationDict
                else:
                    beniCreationDict["responseStatus"] = 0
                    beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                    app.logger.error("Unknown status from bank")
                    return beniCreationDict
            else:
                beniCreationDict["responseStatus"] = 0
                beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                app.logger.error("RequestUUID or channelId mismatch with request and reponse data: ")

            return beniCreationDict

        except Exception as e:
            app.logger.error(traceback.format_exc())
            beniCreationDict["responseStatus"] = 0
            beniCreationDict["result"] = "Our banking partner server is down, please try again later."
            return beniCreationDict

    except Exception as e:
        app.logger.error(traceback.format_exc())
        beniCreationDict["responseStatus"] = 0
        beniCreationDict["result"] = "Our banking partner server is down, please try again later."
        return beniCreationDict


def axis_payout_fundtransfer(client_id, client_secret, key, channelId, get_base_url, requestUUID,serviceRequestId, serviceRequestVersion, corpCode,corpAccNum,  amount,beneficiaryName,userId, accountIFSCCode,txnPaymode, beneCode,custUniqRef, beneAccNum, beneBankName=""):
    axisResponseData = {}
    paymentgatewayresponseDict = {}
    if txnPaymode.lower() == "neft":
        txnPaymode = "NE"
    elif txnPaymode.lower() == "rtgs":
        txnPaymode = "RT"
    elif txnPaymode.lower() == "imps":
        txnPaymode = "PA"
    try:
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path ,key_path)
        axis_request_body = {
                    "channelId": channelId,
                    "corpCode": corpCode,
                    "paymentDetails": [{
                        "txnPaymode": txnPaymode,
                        "custUniqRef": custUniqRef,
                        "corpAccNum": corpAccNum,
                        "valueDate": datetime.datetime.now().strftime("%Y-%m-%d"),
                        "txnAmount": str(float(amount)),
                        "beneLEI": "",
                        "beneName": "",
                        "beneCode": beneCode,
                        "beneAccNum": "",
                        "beneAcType": "",
                        "beneAddr1": "",
                        "beneAddr2": "",
                        "beneAddr3": "",
                        "beneCity": "",
                        "beneState": "",
                        "benePincode": "",
                        "beneIfscCode": "",
                        "beneBankName": "",
                        "baseCode": "",
                        "chequeNumber": "",
                        "chequeDate": "",
                        "payableLocation": "",
                        "printLocation": "",
                        "beneEmailAddr1": "",
                        "beneMobileNo":"",
                        "productCode": "",
                        "txnType": "",
                        "invoiceDetails": [{
                            "invoiceAmount": "",
                            "invoiceNumber": "",  # You might want to pass clientOrderId here
                            "invoiceDate": "",
                            "cashDiscount": "",
                            "tax": "",
                            "netAmount": ""
                        }],
                        "enrichment1":"",
                        "enrichment2":"",
                        "enrichment3":"",
                        "enrichment4":"",
                        "enrichment5":"",
                        "senderToReceiverInfo": ""
                    }]
                }
        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        hash_value = encode_checksum_with_md5(concatenated_values)
        axis_request_body["checksum"] = hash_value
 
        print("(((((((Fund Transfer Axis request body WITH CHECKSUM)))))))",axis_request_body)
        axis_request_body = axis_encrypt(axis_request_body, key)
 
        try:
            url = get_base_url+"/txb/v1/payments/transfer-payment"
            print(url,"((((((((((Fund Transfer Axis Bank URL))))))))))")
            # url = "https://saksham.axisbank.co.in/gateway/api/txb/v1/payments/transfer-payment" UAT
            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": str(client_id),
                "X-IBM-Client-Secret": str(client_secret)
            }
            axis_payload = {
            "TransferPaymentRequest": {
                "SubHeader": {
                    "requestUUID": str(requestUUID), 
                    "serviceRequestId": str(serviceRequestId),
                    "serviceRequestVersion": str(serviceRequestVersion),
                    "channelId": str(channelId)
                },
                "TransferPaymentRequestBodyEncrypted": str(axis_request_body)
            }
            }  
            print(axis_payload, "AXIS payout READY TO SEND ")
            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)
            axis_response_json = axisResponseData.json()
 
            print(axis_response_json,"(((((((JSON AXIS RESPONSE)))))))")
            encrypted_fund_transfer_resp_body  = axis_response_json.get("TransferPaymentResponse", {}).get("TransferPaymentResponseBodyEncrypted", {})
 
            if not encrypted_fund_transfer_resp_body:
                app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") +" status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                return paymentgatewayresponseDict
 
 
            decrypted_text = axis_decrypt(encrypted_fund_transfer_resp_body, key)
 
            jsondecryptResponse = json.loads(decrypted_text)
 
            fund_transfer_response = {
                "TransferPaymentResponse": {
                    "SubHeader": axis_response_json.get("TransferPaymentResponse", {}).get("SubHeader", {}),
                    "TransferPaymentResponseBody": jsondecryptResponse
                }
            }
            print(fund_transfer_response,"(((((((JSON AXIS decrypted response)))))))")
 
            response_body = fund_transfer_response.get("TransferPaymentResponse", {}).get('TransferPaymentResponseBody',{})
            subheaders = fund_transfer_response.get("TransferPaymentResponse", {}).get("SubHeader", {})
 
            ##extract requestuuid and channelid to validate and check if we got results for same fields we sent
            response_requestUUID= subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")
 
            res_status = response_body.get("status", "")
            message = response_body.get("message", "")
            data = response_body.get("data", {})
            error = response_body.get("error", {})
 
            transactionstatus=2
            bank_reference_number=''
            transaction_id=''
            messages=""
            status="PROCESSING"
 
            if requestUUID == response_requestUUID and channelId  == response_channelId:
 
                if res_status == "S":
 
                    transactionstatus=1
                    status="SUCCESS"
 
                    paymentgatewayresponseDict={
                    "responseStatus":1,
                    'transactionstatus':transactionstatus,
                    'status':status,
                    "messages":message,
                    "bank_reference_number":"",
                    "transaction_id":custUniqRef,
                    "transactionData": [fund_transfer_response],
                    }
                elif res_status == "F":
 
                    transactionstatus=2
                    status="PROCESSING"
 
                    paymentgatewayresponseDict={
                    "responseStatus":1,
                    'transactionstatus':transactionstatus,
                    'status':status,
                    "messages":message,
                    "bank_reference_number":"",
                    "transaction_id":custUniqRef,
                    "transactionData": [fund_transfer_response],
                    }
 
                return paymentgatewayresponseDict
            else:
                app.logger.error("RequestUUID or channelId mismatch with request and reponse data: ")
                paymentgatewayresponseDict["responseStatus"] = 2
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                return paymentgatewayresponseDict
 
                # API Logs Table Saving Here
                # requestData = [axis_request_body]
                # save_axis_api_log_table = save_api_logs_data(userId, "payout", "fund_transfer", url, payOutPaymentGatewayId, requestData, client_ip, apiType)
 
                # save_wowpe_link_api_log_table.update(responseData=[axisResponseData.json()], responseDate=datetime.datetime.now())
        except Exception as e:
            app.logger.error(traceback.format_exc())
            paymentgatewayresponseDict["responseStatus"] = 0
            paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
            return paymentgatewayresponseDict
 
 
    except Exception as e:
        app.logger.error(traceback.format_exc())
        paymentgatewayresponseDict["responseStatus"] = 0
        paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
    return paymentgatewayresponseDict


def axis_payout_fundtransfer_check_status(client_id, client_secret, key, channelId, get_base_url, requestUUID, serviceRequestId, serviceRequestVersion, corpCode,crn,fund_transfer_queryset):
    axisResponseData = {}
    paymentgatewayresponseDict = {}

    try:
        # Paths to certificate and key (unchanged as per request)
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path, key_path)

        # Prepare the request body
        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "crn": crn  # Assuming a sample CRN, replace as required
        }
        
        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        
        # Generate SHA-256 hash
        hash_value = encode_checksum_with_md5(concatenated_values)

        # Update the request body with the hash (checksum)
        axis_request_body["checksum"] = hash_value
        print(axis_request_body, "((((((((AXIS REQUEST BODY))))))))")

        axis_request_body = axis_encrypt(axis_request_body, key)

        print("Request Body after encrypt",axis_request_body)

        try:
            # API call to Axis Bank
            url = get_base_url + "/txb/v1/acct-recon/get-status"

            print(url,"((((((((((URL))))))))))")
            # Headers for the request
            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": client_id,
                "X-IBM-Client-Secret": client_secret
            }
            print(headers,"(((((((headers)))))))")
            axis_payload = {
            "GetStatusRequest": {
                "SubHeader": {
                    "requestUUID": str(requestUUID),
                    "serviceRequestId": str(serviceRequestId),
                    "serviceRequestVersion": str(serviceRequestVersion),
                    "channelId": str(channelId)
                },
                "GetStatusRequestBodyEncrypted": str(axis_request_body)
            }
        }
            print(axis_payload, "AXIS payout READY TO SEND")

            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)
            

            axis_response_json = axisResponseData.json()
            print(axis_response_json, "AXIS PAYOUT TEXT RESPONSE")

            encrypted_fund_transfer_resp_body  = axis_response_json.get("GetStatusResponse", {}).get("GetStatusResponseBodyEncrypted", {})

            if not encrypted_fund_transfer_resp_body:
                app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") + " status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                return paymentgatewayresponseDict

            print(encrypted_fund_transfer_resp_body, "AXIS status check TEXT RESPONSE")
            # Decrypt the response
            decrypted_text = axis_decrypt(encrypted_fund_transfer_resp_body, key)
            jsondecryptResponse = json.loads(decrypted_text)
            print(jsondecryptResponse, "(((((((JSON AXIS RESPONSE)))))))")

            # Parse the response
            status_response = {
            "GetStatusResponse": {
                "SubHeader": axis_response_json.get("GetStatusResponse", {}).get("SubHeader", {}),
                "GetStatusResponseBodyEncrypted": jsondecryptResponse
                }
            }   
            print(status_response, "Decrypted Status check Response")
            response_body = status_response.get("GetStatusResponse", {}).get("GetStatusResponseBodyEncrypted", {})
            subheaders = status_response.get("GetStatusResponse", {}).get("SubHeader", {})


            response_requestUUID= subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            # Extract relevant fields from the response
            status = response_body.get("status", "")
            message = response_body.get("message", "")
            data = response_body.get("data", {})

            if requestUUID == response_requestUUID and channelId  == response_channelId:
                if status == "S":
                    response_checksum = data.get("checksum",{})
                    concatenated_response_values = concatenate_values_for_checksum(data)
                    response_checksum_hash = encode_checksum_with_md5(concatenated_response_values)
                    if response_checksum_hash == response_checksum:
                        print("checksum passed++++++++++++++++++++++++")
                        transactions = data.get('CUR_TXN_ENQ', [])
                        if len(transactions) > 0:
                            successful_transaction = None
                            for transaction in transactions:
                                if transaction.get("transactionStatus") == "PROCESSED":
                                    successful_transaction = transaction
                                    break  # Stop searching as we found a successful transaction

                            transactionstatus = 2
                            textStatus = "PROCESSING"
                            bankReferenceNumber=""
                            message=""
                            transactionData = [status_response]
                            responseStatus = transaction.get("transactionStatus")

                            if responseStatus == "PROCESSED":
                                transactionstatus = 1
                                textStatus="SUCCESS"
                            elif responseStatus == "REJECTED":
                                transactionstatus = 0
                                textStatus="FAILED"
                            elif responseStatus == "RETURN":
                                transactionstatus = 4
                                textStatus="REVERSAL"
                            else:
                                transactionstatus = 2
                                textStatus="PROCESSING"

                            if transaction.get("transactionStatus") == "PROCESSED":
                                bankReferenceNumber = transaction.get("utrNo")
                            else:
                                bankReferenceNumber = fund_transfer_queryset.bankReferenceNumber

                            message = transaction.get("statusDescription")

                            paymentgatewayResponseStatusDict ={
                            "responseStatus":1,
                            "transactionStatus":transactionstatus,
                            "bankReferenceNumber":bankReferenceNumber,
                            "textStatus":textStatus,
                            "error_message":message,
                            "transaction_id":transaction.get("crn"),
                            "transactionData":transactionData
                            }
                            return paymentgatewayResponseStatusDict
                        else:
                            paymentgatewayResponseStatusDict = {
                            "responseStatus":2,
                            "result":"No Update!!",
                            "transaction_id":fund_transfer_queryset.transactionUniqueId
                            }
                            return paymentgatewayResponseStatusDict
                    else:
                        app.logger.error("Checksum mismatch with request and reponse data: ")
                        paymentgatewayresponseDict["responseStatus"] = 0
                        paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                        return paymentgatewayresponseDict
                elif status == "F":
                    app.logger.error("Failed status")
                    paymentgatewayresponseDict["responseStatus"] = 0
                    paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                    return paymentgatewayresponseDict
                else:
                    app.logger.error("Unknown status ")
                    paymentgatewayresponseDict["responseStatus"] = 0
                    paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                    return paymentgatewayresponseDict
            else:
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                app.logger.error("RequestUUID or channelId mismatch with request and reponse data: ")

            return paymentgatewayresponseDict

        except Exception as e:
            app.logger.error(traceback.format_exc())
            paymentgatewayresponseDict["responseStatus"] = 0
            paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
            return paymentgatewayresponseDict

    except Exception as e:
        app.logger.error(traceback.format_exc())
        paymentgatewayresponseDict["responseStatus"] = 0
        paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
        return paymentgatewayresponseDict


def axis_payout_get_account_balance(client_id, client_secret, key, channelId, get_base_url, requestUUID, serviceRequestId, serviceRequestVersion, corpCode, corpaccnum):
    axisResponseData = {}
    paymentgatewayresponseDict = {}

    try:
        # Paths to certificate and key (unchanged as per request)
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path, key_path)

        # Prepare the request body
        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "corpAccNum": corpaccnum  # Assuming corpaccnum as the account number parameter
        }
        
        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        
        # Generate SHA-256 hash
        hash_value = encode_checksum_with_md5(concatenated_values)

        # Update the request body with the hash (checksum)
        axis_request_body["checksum"] = hash_value
        print(axis_request_body, "((((((((AXIS REQUEST BODY))))))))")

        axis_request_body = axis_encrypt(axis_request_body, key)
        print("Request Body after encrypt", axis_request_body)

        try:
            # API call to Axis Bank for account balance
            # url = "https://sakshamuat.axisbank.co.in/gateway/api/txb/v1/acct-recon/get-balance"
                     
            url = get_base_url+"/txb/v1/acct-recon/get-balance"

            # Headers for the request
            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": client_id,
                "X-IBM-Client-Secret": client_secret
            }

            axis_payload = {
                "GetAccountBalanceRequest": {
                    "SubHeader": {
                        "requestUUID": str(requestUUID),
                        "serviceRequestId": str(serviceRequestId),
                        "serviceRequestVersion": str(serviceRequestVersion),
                        "channelId": str(channelId)
                    },
                    "GetAccountBalanceRequestBodyEncrypted": str(axis_request_body)
                }
            }
            print(axis_payload, "AXIS payout READY TO SEND")
            print("get status url",url)

            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)

            axis_response_json = axisResponseData.json()
            print(axis_response_json, "AXIS GET BALANCE TEXT RESPONSE")

            encrypted_resp_body = axis_response_json.get("GetAccountBalanceResponse", {}).get("GetAccountBalanceResponseBodyEncrypted", {})
            if not encrypted_resp_body:
                app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") +" status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                return paymentgatewayresponseDict

            print(encrypted_resp_body, "AXIS GET BALANCE TEXT RESPONSE")

            # Decrypt the response
            decrypted_text = axis_decrypt(encrypted_resp_body, key)
            jsondecryptResponse = json.loads(decrypted_text)
            print(jsondecryptResponse, "(((((((JSON AXIS RESPONSE)))))))")

            # Parse the response
            balance_response = {
                "GetAccountBalanceResponse": {
                    "SubHeader": axis_response_json.get("GetAccountBalanceResponse", {}).get("SubHeader", {}),
                    "GetAccountBalanceResponseBodyEncrypted": jsondecryptResponse
                }
            }

            print(balance_response, "Decrypted Account Balance Response")

            response_body = balance_response.get("GetAccountBalanceResponse", {}).get("GetAccountBalanceResponseBodyEncrypted", {})
            subheaders = balance_response.get("GetAccountBalanceResponse", {}).get("SubHeader", {})

            response_requestUUID = subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            # Extract relevant fields from the response
            status = response_body.get("status", "")
            message = response_body.get("message", "")
            data = response_body.get("data", {})

            if requestUUID == response_requestUUID and channelId == response_channelId:
                if status == "S":
                    response_checksum = data.get("checksum", {})
                    concatenated_response_values = concatenate_values_for_checksum(data)
                    response_checksum_hash = encode_checksum_with_md5(concatenated_response_values)
                    if response_checksum_hash == response_checksum:
                        account_balance = data.get("Balance")
                        paymentgatewayresponseDict = {
                            "status": data.get("status", ""),
                            "availableBalance": account_balance,
                            "responseStatus": 1,
                            "result": message
                        }
                    else:
                        app.logger.error("Checksum mismatch with request and response data.")
                        paymentgatewayresponseDict["responseStatus"] = 0
                        paymentgatewayresponseDict["result"] = "Checksum mismatch."
                elif status == "F":
                    paymentgatewayresponseDict["responseStatus"] = 0
                    paymentgatewayresponseDict["result"] = "Invalid Request."
                else:
                    paymentgatewayresponseDict["responseStatus"] = 0
                    paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
            else:
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                app.logger.error("RequestUUID or channelId mismatch with request and response data.")

            return paymentgatewayresponseDict

        except Exception as e:
            app.logger.error(traceback.format_exc())
            paymentgatewayresponseDict["responseStatus"] = 0
            paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
            return paymentgatewayresponseDict

    except Exception as e:
        app.logger.error(traceback.format_exc())
        paymentgatewayresponseDict["responseStatus"] = 0
        paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
        return paymentgatewayresponseDict


def axis_bulk_beneficiary_registration(client_id, client_secret, get_api_key, channelId, 
    serviceRequestId, serviceRequestVersion, corpCode, userId, get_base_url, requestUUID, apiVersion,beneficiaries):
    
    # Standardized response dictionary
    beniCreationDict = {"responseStatus": 0, "result": ""}
    key = get_api_key
    cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
    key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
    cert = (cert_path, key_path)

    try:
        # Iterate through each beneficiary in the list
                # Initialize the request body with channelId, corpCode, and userId
        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "userId": "",
            "beneinsert": []  # This will be a list of beneficiaries
        }

        # Iterate through each beneficiary and append to beneinsert list
        for beneficiary in beneficiaries:
            print("eeeeeeeeeeeeeeeeeeeeeee",beneficiary)
            beneficiary_data = {
                "apiVersion": apiVersion,  # Default to "1.0"
                "beneLEI": "",
                "beneCode": beneficiary.get("beneficiaryCode", ""), ########## Original Benecode ###########
                "beneName": beneficiary.get("req_account_name", ""),
                "beneAccNum": beneficiary.get("req_account_number", ""),
                "beneIfscCode": beneficiary.get("req_ifsc_code", ""),
                "beneBankName": beneficiary.get("bank_name", ""),
                "beneAcType": "",
                "beneAddr1": "",
                "beneAddr2": "",
                "beneAddr3": "",
                "beneCity": "",
                "beneState": "",
                "benePincode": "",
                "beneEmailAddr1": "",
                "beneMobileNo": ""
            }
            # Add each beneficiary's data to the beneinsert list
            axis_request_body["beneinsert"].append(beneficiary_data)
        

        print("after adding bene details",axis_request_body)

        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        hash_value = encode_checksum_with_md5(concatenated_values)
        axis_request_body["checksum"] = hash_value

        print("Request Body before encrypt", axis_request_body)

        # Encrypt the request body
        encrypted_request_body = axis_encrypt(axis_request_body, key)
        try:
            url = get_base_url + "/txb/v1/payee-mgmt/beneficiary-registration"
            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": str(client_id),
                "X-IBM-Client-Secret": str(client_secret)
            }
            axis_payload = {
                "BeneficiaryRegistrationRequest": {
                    "SubHeader": {
                        "requestUUID": str(requestUUID),
                        "serviceRequestId": str(serviceRequestId),
                        "serviceRequestVersion": str(serviceRequestVersion),
                        "channelId": str(channelId)
                    },
                    "BeneficiaryRegistrationRequestBodyEncrypted": str(encrypted_request_body)
                }
            }

            # print("Sending request for beneficiary:", beneficiary["beneName"])
            
            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)

            # Check if the response was successful
            print(axisResponseData.status_code, "Response status code")
            axis_response_json = axisResponseData.json()

            # Log and handle the encrypted response
            print(axis_response_json, "Encrypted Beneficiary Registration Response")

            encrypted_bene_resp_body = axis_response_json.get("BeneficiaryRegistrationResponse", {}).get("BeneficiaryRegistrationResponseBodyEncrypted", {})

            # Decrypt the response body
            decrypted_text = axis_decrypt(encrypted_bene_resp_body, key)
            jsondecryptResponse = json.loads(decrypted_text)
            print(jsondecryptResponse, "Decrypted Beneficiary Registration Response Body")

            # Process decrypted response by mapping fields accordingly
            beneficiary_response = {
                "BeneficiaryRegistrationResponse": {
                    "SubHeader": axis_response_json.get("BeneficiaryRegistrationResponse", {}).get("SubHeader", {}),
                    "BeneficiaryRegistrationResponseBody": jsondecryptResponse
                }
            }
            transactionData = [beneficiary_response]

            print(beneficiary_response, "Decrypted Beneficiary Registration Response")

            # Extract fields to validate response
            response_body = beneficiary_response.get("BeneficiaryRegistrationResponse", {}).get("BeneficiaryRegistrationResponseBody", {})
            subheaders = beneficiary_response.get("BeneficiaryRegistrationResponse", {}).get("SubHeader", {})

            response_requestUUID = subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            data = response_body.get("data", {})
            status = response_body.get("status", "")
            message = response_body.get("message", "")

            # Validate response UUID and channel ID against the request
            if requestUUID == response_requestUUID and channelId == response_channelId:
                if status == "S":
                    response_checksum = data.get("checksum", {})
                    concatenated_response_values = concatenate_values_for_checksum(data)
                    response_checksum_hash = encode_checksum_with_md5(concatenated_response_values)
                    if response_checksum_hash == response_checksum:

                        beneList = []
                        bene_details = data.get("beneDetails", [])
                        if bene_details:
                            for bene_data in bene_details:
                                bene_name = bene_data.get("beneName")
                                # bene_code = bene_data.get("beneCode")
                                bene_ifsc_code = bene_data.get("beneIfscCode")
                                bene_acc_no = bene_data.get("beneAccNum")

                                bene_dct={
                                    # "beneCode": bene_code,
                                    "beneName":bene_name,
                                    "beneIFSC": bene_ifsc_code,
                                    "beneAccNum": bene_acc_no,
                                    "status": "Pending"
                                }
                                beneList.append(bene_dct)

                        beniCreationDict.update({
                            "responseStatus": 1,
                            "result": "Success",
                            "beneList": beneList,
                            "responseList": bene_details,
                            "transactionData":transactionData,
                            "message": message,
                        })

                    else:
                        beniCreationDict.update({
                        "responseStatus": 0,
                        "result": "Failure",
                        "message": "Our banking partner server is down, please try again later.",
                    })
                        app.logger.error("Checksum mismatch between request and response data.")
                else:
                    beniCreationDict.update({
                        "responseStatus": 0,
                        "result": "Failure",
                        "message": "Our banking partner server is down, please try again later.",
                    })
            else:
                beniCreationDict.update({
                    "responseStatus": 0,
                    "result": "Failure",
                    "message": "Our banking partner server is down, please try again later.",
                })
                app.logger.error("RequestUUID or channelId mismatch between request and response data.")

            return beniCreationDict
        except Exception as e:
            app.logger.error(traceback.format_exc())
            beniCreationDict["responseStatus"] = 0
            beniCreationDict["result"] = "Our banking partner server is down, please try again later."
            return beniCreationDict
    except Exception as e:
        app.logger.error(traceback.format_exc())
        beniCreationDict["responseStatus"] = 0
        beniCreationDict["result"] = "Our banking partner server is down, please try again later."
        return beniCreationDict

def axis_payout_bulk_fundtransfer(
    client_id, client_secret, key, channelId, get_base_url, requestUUID, serviceRequestId,
    serviceRequestVersion, corpCode,corpAccNum, bulk_transfer_list,bulk_transactionId):

    axisResponseData = {}
    paymentgatewayresponseDict = {}

    try:
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path, key_path)

        # Constructing the axis_request_body with multiple payment details
        payment_details = []
        print(bulk_transfer_list,"(((((((((((bulk_transfer_list AXIS)))))))))))")
        for each_transfer in bulk_transfer_list:
            print(each_transfer.get("beneCode", ""),"Bulk BENE CODES")
            if each_transfer.get("txnPaymode").lower() == "neft":
                txnPaymode = "NT"
            elif each_transfer.get("txnPaymode").lower() == "rtgs":
                txnPaymode = "RT"
            elif each_transfer.get("txnPaymode").lower() == "imps":
                txnPaymode = "PA"
            payment_details.append({
                "txnPaymode": txnPaymode,
                "custUniqRef": each_transfer.get("custUniqRef", ""),
                "corpAccNum": corpAccNum,
                "valueDate": datetime.datetime.now().strftime("%Y-%m-%d"),
                "txnAmount": each_transfer.get("amount", ""),
                "beneLEI": "",
                "beneName": "",
                "beneCode": each_transfer.get("beneCode", ""),
                "beneAccNum": "",
                "beneAcType": "",
                "beneAddr1": "", 
                "beneAddr2": "",  
                "beneAddr3": "",  
                "beneCity": "",
                "beneState": "",
                "benePincode": "",
                "beneIfscCode": "",
                "beneBankName": "",
                "baseCode": "", 
                "chequeNumber": "", 
                "chequeDate": "",   
                "payableLocation": "",  
                "printLocation": "",   
                "beneEmailAddr1": "",
                "beneMobileNo": "",
                "productCode": "", 
                "txnType": "",
                "invoiceDetails": [{
                    "invoiceAmount": "", 
                    "invoiceNumber": "", 
                    "invoiceDate": "", 
                    "cashDiscount": "", 
                    "tax": "", 
                    "netAmount": "", 
                }],
                "enrichment1": "",
                "enrichment2": "",
                "enrichment3": "",
                "enrichment4": "",
                "enrichment5": "",
                "senderToReceiverInfo": ""  
            })

        # Main request body
        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "paymentDetails": payment_details
        }

        # Checksum calculation and addition to request body
        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        hash_value = encode_checksum_with_md5(concatenated_values)
        axis_request_body["checksum"] = hash_value

        print("Axis request body WITH CHECKSUM:", axis_request_body)

        # Encrypting the request body
        axis_request_body = axis_encrypt(axis_request_body, key)

        try:
            url = get_base_url + "/txb/v1/payments/transfer-payment"
            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": str(client_id),
                "X-IBM-Client-Secret": str(client_secret)
            }
            axis_payload = {
                "TransferPaymentRequest": {
                    "SubHeader": {
                        "requestUUID": str(requestUUID), 
                        "serviceRequestId": str(serviceRequestId),
                        "serviceRequestVersion": str(serviceRequestVersion),
                        "channelId": str(channelId)
                    },
                    "TransferPaymentRequestBodyEncrypted": str(axis_request_body)
                }
            }
            print("AXIS Bulk payout ready to send:", axis_payload)

            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)
            axis_response_json = axisResponseData.json()

            encrypted_fund_transfer_resp_body = axis_response_json.get("TransferPaymentResponse", {}).get("TransferPaymentResponseBodyEncrypted", {})

            if not encrypted_fund_transfer_resp_body:
                app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") + 
                                 " status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
                return paymentgatewayresponseDict

            decrypted_text = axis_decrypt(encrypted_fund_transfer_resp_body, key)
            jsondecryptResponse = json.loads(decrypted_text)

            fund_transfer_response = {
                "TransferPaymentResponse": {
                    "SubHeader": axis_response_json.get("TransferPaymentResponse", {}).get("SubHeader", {}),
                    "TransferPaymentResponseBody": jsondecryptResponse
                }
            }
            print("Bulk Decrypted Axis response:", fund_transfer_response)

            response_body = fund_transfer_response.get("TransferPaymentResponse", {}).get("TransferPaymentResponseBody", {})
            subheaders = fund_transfer_response.get("TransferPaymentResponse", {}).get("SubHeader", {})

            response_requestUUID = subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            res_status = response_body.get("status", "")
            message = response_body.get("message", "")

            transactionstatus=2
            bank_reference_number=''
            transaction_id=''
            messages=""
            status="PROCESSING"

            if requestUUID == response_requestUUID and channelId == response_channelId:
                if res_status == "S":
                    status="SUCCESS"
                    transactionstatus=1
                    paymentgatewayresponseDict = {
                        "responseStatus": 1,
                        'transactionstatus':transactionstatus,
                        "status": status,
                        "merchant_reference_number": "",
                        "transaction_id": "",
                        "transactionData": [fund_transfer_response],
                        "result": message
                    }
                elif res_status == "F":
                    paymentgatewayresponseDict["responseStatus"] = 0
                    paymentgatewayresponseDict["result"] = message
            else:
                app.logger.error("RequestUUID or channelId mismatch with request and response data.")
                paymentgatewayresponseDict["responseStatus"] = 0
                paymentgatewayresponseDict["result"] = message
            return paymentgatewayresponseDict

        except Exception as e:
            app.logger.error(traceback.format_exc())
            paymentgatewayresponseDict["responseStatus"] = 0
            paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
            return paymentgatewayresponseDict

    except Exception as e:
        app.logger.error(traceback.format_exc())
        paymentgatewayresponseDict["responseStatus"] = 0
        paymentgatewayresponseDict["result"] = "Our banking partner server is down, please try again later."
        return paymentgatewayresponseDict

def axis_bulk_beneficiary_enquiry(client_id, client_secret, key, channelId, get_base_url,apiVersion,requestUUID, serviceRequestId, serviceRequestVersion, corpCode,userId,fromDate,toDate,emailId,status,benecodesList):
    axisResponseData = {}
    beniCreationDict = {}

    try:
        cert_path = os.path.join(app.config["SITE_ROOT"], "static", "client-cert.pem")
        key_path = os.path.join(app.config["SITE_ROOT"], "static", "client-key.pem")
        cert = (cert_path, key_path)

        axis_request_body = {
            "channelId": channelId,
            "corpCode": corpCode,
            "fromDate": fromDate,
            "toDate": toDate,
            "emailId": emailId,
            "status": status,   # /All , Inactive Active
            "beneCode": benecodesList
            }
        
        concatenated_values = concatenate_values_for_checksum(axis_request_body)
        
        hash_value = encode_checksum_with_md5(concatenated_values)

        axis_request_body["checksum"] = hash_value
        print(axis_request_body, "((((((((AXIS REQUEST BODY with checksum))))))))\n")

        axis_request_body = axis_encrypt(axis_request_body, key)

        try:
            url = get_base_url + "/txb/v1/payee-mgmt/beneficiary-enquiry"

            headers = {
                "Content-type": "application/json",
                "X-IBM-Client-Id": client_id,
                "X-IBM-Client-Secret": client_secret
            }

            axis_payload = {
            "BeneficiaryEnquiryRequest": {
                "SubHeader": {
                    "requestUUID": str(requestUUID),
                    "serviceRequestId": str(serviceRequestId),
                    "serviceRequestVersion": str(serviceRequestVersion),
                    "channelId": str(channelId)
                },
                "BeneficiaryEnquiryRequestBodyEncrypted": str(axis_request_body)
            }
        }
            print(axis_payload, "AXIS payout READY TO SEND\n")

            axisResponseData = requests.post(url, cert=cert, json=axis_payload, headers=headers)

            print(axisResponseData.status_code, "Response status code")
            

            axis_response_json = axisResponseData.json()
            print(axis_response_json, "AXIS PAYOUT TEXT RESPONSE\n")

            encrypted_bene_resp_body  = axis_response_json.get("BeneficiaryEnquiryResponse", {}).get("BeneficiaryEnquiryResponseBodyEncrypted", {})

            if not encrypted_bene_resp_body:
                app.logger.error(axis_response_json.get("moreInformation", "No additional info provided") +" status Code " + str(axis_response_json.get("httpCode", "Unknown")))
                beniCreationDict["responseStatus"] = 0
                beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                return beniCreationDict

            # Decrypt the response
            decrypted_text = axis_decrypt(encrypted_bene_resp_body, key)
            print(decrypted_text,"decrypted_text check")
            jsondecryptResponse = json.loads(decrypted_text)

            status_response = {
            "BeneficiaryEnquiryResponse": {
                "SubHeader": axis_response_json.get("BeneficiaryEnquiryResponse", {}).get("SubHeader", {}),
                "BeneficiaryEnquiryResponseBodyEncrypted": jsondecryptResponse
            }
        }       

            transactionData=[status_response]

            print(status_response, "Decrypted Status Registration Response\n")

            response_body = status_response.get("BeneficiaryEnquiryResponse", {}).get("BeneficiaryEnquiryResponseBodyEncrypted", {})
            subheaders = status_response.get("BeneficiaryEnquiryResponse", {}).get("SubHeader", {})


            response_requestUUID= subheaders.get("requestUUID", "")
            response_channelId = subheaders.get("channelId", "")

            # Extract relevant fields from the response
            status = response_body.get("status", "")
            message = response_body.get("message", "")
            data = response_body.get("data", {})
            print(data,"DATA IN GRAAMPAY Bulk ENQUIRY STATUS CHECK")

            if requestUUID == response_requestUUID and channelId  == response_channelId:

                if status == "S":
                    response_checksum = data.get("checksum",{})
                    concatenated_response_values = concatenate_values_for_checksum(data)
                    response_checksum_hash = encode_checksum_with_md5(concatenated_response_values)

                    if response_checksum_hash == response_checksum:
                        beneList = []
                        client_benecode = ""
                        bene_details = data.get("beneDetails", [])
                        if bene_details:
                            for bene_data in bene_details:
                                bene_code = bene_data.get("beneCode") ####### Original Benecode ###########
                                print(bene_code,"((((((((((bene_code in Axis))))))))))")
                                bene_data_queryset = Beneficiaries.objects(beneCodeList__beneCode=bene_code).first()
                                if bene_data_queryset:
                                    print("IF")
                                    client_benecode = bene_data_queryset.beneficiaryId
                                else:
                                    print("ELSE")
                                    thirdparty_bene_data_queryset = ThirdPartyBeneficiaries.objects(beneCodeList__beneCode=bene_code).first()
                                    print(thirdparty_bene_data_queryset,"((((((((thirdparty_bene_data_queryset))))))))")
                                    if thirdparty_bene_data_queryset:
                                        client_benecode = thirdparty_bene_data_queryset.beneficiaryId

                                bene_name = bene_data.get("beneName")
                                bene_ifsc_code = bene_data.get("beneIfscCode")
                                bene_acc_no = bene_data.get("beneAccNum")
                                status = bene_data.get("status")

                                bene_dct={
                                    "beneCode": client_benecode,
                                    "beneName":bene_name,
                                    "beneIFSC": bene_ifsc_code,
                                    "beneAccNum": bene_acc_no,
                                    "status": status
                                }
                                beneList.append(bene_dct)
                        print(beneList,"IN GRAAMPAY Bulk ENQUIRY STATUS CHECK")
                        beniCreationDict={
                            "responseStatus": 1,
                            "result": "Success",
                            "beneList": beneList,
                            "responseList": bene_details,
                            "transactionData":transactionData,
                            "jsondecryptResponse":jsondecryptResponse,
                            "message": message,
                        }
                        return beniCreationDict
                    else:
                        app.logger.error("Checksum mismatch with request and reponse data: ")
                        beniCreationDict["responseStatus"] = 0
                        beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                        return beniCreationDict
                elif status == "F":
                    beniCreationDict["responseStatus"] = 0
                    beniCreationDict["result"] = message
                    return beniCreationDict
                else:
                    beniCreationDict["responseStatus"] = 0
                    beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                    app.logger.error("Unknown status from bank")
                    return beniCreationDict
            else:
                beniCreationDict["responseStatus"] = 0
                beniCreationDict["result"] = "Our banking partner server is down, please try again later."
                app.logger.error("RequestUUID or channelId mismatch with request and reponse data: ")
            return beniCreationDict
        except Exception as e:
            app.logger.error(traceback.format_exc())
            beniCreationDict["responseStatus"] = 0
            beniCreationDict["result"] = "Our banking partner server is down, please try again later."
            return beniCreationDict

    except Exception as e:
        app.logger.error(traceback.format_exc())
        beniCreationDict["responseStatus"] = 0
        beniCreationDict["result"] = "Our banking partner server is down, please try again later."
        return beniCreationDict