from appservices.common.util import *

frontend_reports = Blueprint("frontend_reports",__name__)

@frontend_reports.route("/generate_payout_download_report",methods=["POST"])
@user_required
def generate_payout_download_report():
    data_status = {"responseStatus":0,"result":""}
    userId = request.json.get("userId","")
    reportType = request.json.get("reportType","")
    dateRange = request.json.get("dateRange","") # "one_day" or "last_7_days" or "last_30_days" or "custom" custom means custom_start_date and custom_end_date
    custom_start_date = request.json.get("custom_start_date","")
    custom_end_date = request.json.get("custom_end_date","")
    walletType = request.json.get("walletType","")

    try:
        if userId and reportType and dateRange and walletType:
            if dateRange in ["one_day","last_7_days","last_30_days","custom"]:
                payout_report_table = PayoutDownloadReports(
                    userId=userId,
                    reportType=reportType,
                    dateRange=dateRange,
                    walletType=walletType,
                    userType="user",
                    createdOn=datetime.datetime.now(),
                    status=0
                    )
                save_table=payout_report_table.save()

                if dateRange == "one_day":
                    startDate = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                    endDate = startDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                    # print(startDate,endDate,"START DATE AND END DATE")
                    endDate = startDate + datetime.timedelta(days=1) - datetime.timedelta(microseconds=1)
                    print(startDate,endDate,"START DATE AND END DATE")
                
                elif dateRange == "last_7_days":
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
                    startDate = endDate - datetime.timedelta(days=7) + datetime.timedelta(microseconds=1)
                    print(startDate,endDate,"START DATE last_7_days AND END DATE")

                elif dateRange == "last_30_days":
                    endDate = datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=999999)
                    startDate = endDate - datetime.timedelta(days=30) + datetime.timedelta(microseconds=1)

                elif dateRange == "custom":
                    customstartDateObject = datetime.datetime.strptime(custom_start_date, "%d-%m-%Y")
                    customendDateObject = datetime.datetime.strptime(custom_end_date, "%d-%m-%Y")
                    startDate = customstartDateObject  
                    endDate = customendDateObject 

                save_table.update(startDate = startDate,endDate = endDate)

                data_status["responseStatus"]=1
                data_status["result"]="Generate payout download report successfully!"
                return data_status
            else:
                data_status["result"]="Please select proper daterange!!"
                return data_status
        else:
            data_status["result"]="Required fields are missing!!"
            return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"]="Unable to generate payout download report!!"
        return data_status

# def download_payout_csv_report_data(each_report):
#     downloadPayoutCSVReportsList = []
#     temp_csv_file_name = ""
#     try:
#         startDate = each_report.startDate
#         endDate = each_report.endDate  # corrected to use endDate
#         print(startDate, endDate, "START AND END DATE")

#         reportType = each_report.reportType
#         start_date_str = startDate.strftime("%d-%m-%Y")
#         end_date_str = endDate.strftime("%d-%m-%Y")

#         fileName = reportType+"_"+start_date_str+"_"+end_date_str+".csv"
#         merchantReferenceNumber = str(each_report.userId.merchantUniqueNumber)

#         fund_transfer_queryset = FundTransfers.objects(
#             # createdOn__gte=startDate,
#             # createdOn__lte=endDate,
#             userId=str(each_report.userId.id),
#             status__in=[0, 1, 2]
#         ).order_by("-id").all()
#         for each_payout_report in fund_transfer_queryset:
#             payoutCSVReportDict = fetching_payout_csv_download_reports(each_payout_report)
#             downloadPayoutCSVReportsList.append(payoutCSVReportDict)

#         fieldnames = ['Account Number', 'Account IFSCCode', 'Beneficiary Name', 'Beneficiary Mail', 'Beneficiary Phone', 'Amount', 'Payment Mode', 'Comment', 'Order Id', 'Bank Branch', 'Transfer Type', 'Transaction UniqueId', 'Txn Date', 'Transaction Status']
#         # temp_csv_file_name = "/media/payout_download_csv_reports_list/" + "payout_download_report_"+ str(get_epoch_milli_time()) + ".csv"
#         temp_csv_file_name = "media/reports/"+merchantReferenceNumber+"/payout/"+fileName

#         if not os.path.exists(os.path.join(app.config['SITE_ROOT'], "media/reports/"+merchantReferenceNumber+"/payout/")):
#             os.makedirs(os.path.join(app.config['SITE_ROOT'], "media/reports/"+merchantReferenceNumber+"/payout/"))

#         fileSize = os.path.getsize(temp_csv_file_name)
#         print(fileSize,"FILE SIZE")

#         full_file_name = app.config['SITE_ROOT'] + temp_csv_file_name
#         with open(full_file_name, 'w', encoding='UTF8', newline='') as f:
#             writer = csv.DictWriter(f, fieldnames=fieldnames)
#             writer.writeheader()
#             writer.writerows(downloadPayoutCSVReportsList)

#         return temp_csv_file_name
#     except Exception as e:
#         app.logger.error(traceback.format_exc())
#     return temp_csv_file_name


def download_auto_collect_csv_report_data(each_report):
    downloadAutocollectCSVReportsList = []
    relative_temp_csv_file_name = ""
    fileSize = 0
    try:
        startDate = each_report.startDate
        endDate = each_report.endDate
        # print(startDate, endDate, "START AND END DATE")

        reportType = each_report.reportType
        start_date_str = startDate.strftime("%d-%m-%Y")
        end_date_str = endDate.strftime("%d-%m-%Y")

        fileName = f"{reportType}_{start_date_str}_{end_date_str}.csv"
        merchantReferenceNumber = str(each_report.userId.merchantUniqueNumber)

        credit_notification_queryset = CreditNotifications.objects(
            createdOn__gte = startDate,
            createdOn__lte = endDate,
            userId=str(each_report.userId.id),
            status__in=[0, 1, 2]
        ).order_by("-id").all()

        if reportType == "ledger":
            for each_credit_notify_report in credit_notification_queryset:
                autocollectCSVReportDict = fetching_auto_collect_csv_download_reports(each_credit_notify_report)
                fund_transfer_queryset = FundTransfers.objects(transactionUniqueId=each_credit_notify_report.transactionUniqueId).first()

                if fund_transfer_queryset.previousBalance:
                    autocollectCSVReportDict["Opening Balance"] = "{:.2f}".format(float(fund_transfer_queryset.previousBalance))
                else:
                    autocollectCSVReportDict["Opening Balance"] = "0.00"

                if fund_transfer_queryset.currentBalance:
                    autocollectCSVReportDict["Closing Balance"] = "{:.2f}".format(float(fund_transfer_queryset.currentBalance))
                else:
                    autocollectCSVReportDict["Closing Balance"] = "0.00"
                downloadAutocollectCSVReportsList.append(autocollectCSVReportDict)
            fieldnames = [
                'Account Number', 'Account IFSCCode', 'Beneficiary Name', 'Amount','Grand Total','Virtual Account Number', 'Comment', 'Transaction UniqueId', 
                'Transfer Type', 'Txn Date', 'Response Status','Opening Balance','Closing Balance'
            ]
        elif reportType == "transactions":
            for each_credit_notify_report in credit_notification_queryset:
                autocollectCSVReportDict = fetching_auto_collect_csv_download_reports(each_credit_notify_report)
                downloadAutocollectCSVReportsList.append(autocollectCSVReportDict)

            fieldnames = [
                'Account Number', 'Account IFSCCode', 'Beneficiary Name', 'Amount','Grand Total','Virtual Account Number', 'Comment', 'Transaction UniqueId', 
                'Transfer Type', 'Txn Date', 'Response Status'
            ]

        # Define the base directory and the relative file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/reports", merchantReferenceNumber, "autocollect")
        relative_temp_csv_file_name = os.path.join("media/reports", merchantReferenceNumber, "autocollect", fileName)

        # Ensure the base directory exists
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        # Full file name for writing
        full_file_name = os.path.join(app.config['SITE_ROOT'], relative_temp_csv_file_name)
        with open(full_file_name, 'w', encoding='UTF8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(downloadAutocollectCSVReportsList)

        fileSize = os.path.getsize(full_file_name)

        return relative_temp_csv_file_name, fileSize
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_csv_file_name, fileSize



@frontend_reports.route("/payout_download_reports_list",methods=["POST"])
@user_required
def payout_download_reports_list():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId", "")
    walletType = request.json.get("walletType", "")
    startDate = request.json.get("startDate", "")
    endDate = request.json.get("endDate", "")
    selectType = request.json.get("selectType", "")
    downloadReportsList = []
    
    date_format = "%d-%m-%Y"
    try:
        if walletType in ["payin","payout","auto_collect"]:
            try:
                if startDate and endDate:
                    startDate = datetime.datetime.strptime(startDate, date_format)
                    startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)
                    
                    endDate = datetime.datetime.strptime(endDate, date_format)
                    endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
                else:
                    startDate = None
                    endDate = None
            except Exception as e:
                app.logger.error(traceback.format_exc())
                data_status["result"] = "Invalid date format!!"
                return data_status

            payout_download_reports_queryset = PayoutDownloadReports.objects(
                userId=userId,walletType=walletType,userType="user",
                createdOn__gte = startDate,createdOn__lte=endDate,
                status__in=[0,1,2]).order_by("-id").all()

            if selectType in ["ledger","transactions",""]:

                if selectType == "ledger":
                    payout_download_reports_queryset = payout_download_reports_queryset.filter(reportType=selectType)
                elif selectType == "transactions":
                    payout_download_reports_queryset = payout_download_reports_queryset.filter(reportType=selectType)


            for each_report in payout_download_reports_queryset:
                downloadReportDict = fetching_payout_download_reports(each_report)
                downloadReportsList.append(downloadReportDict)

            data_status["responseStatus"] = 1
            data_status["result"] = "Payout download reports fetched successfully!"
            data_status["downloadReportsList"] = downloadReportsList
            return data_status
        else:
            data_status["result"]="Wallet type is required!!"
            return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch payout download reports!"
        return data_status


@frontend_reports.route("/testing_payout_download_reports_list", methods=["POST"])
@user_required
def testing_payout_download_reports_list():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId", "")
    startDate = request.json.get("startDate", "")
    endDate = request.json.get("endDate", "")
    downloadReportsList = []

    date_format = "%d-%m-%Y"
    try:
        if startDate and endDate:
            startDate = datetime.datetime.strptime(startDate, date_format)
            startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)

            endDate = datetime.datetime.strptime(endDate, date_format)
            endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
        else:
            startDate = None
            endDate = None
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Invalid date format!!"
        return data_status

    print(startDate,"START DATE FOR PAYOUT")
    print(endDate,"END DATE FOR PAYOUT")

    try:
        payoutData = testing_download_payout_csv_report_data(userId, startDate, endDate)
        data_status["responseStatus"] = 1
        data_status["result"] = "Payout download reports fetched successfully!"
        data_status["payoutData"] = domain + payoutData
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch payout download reports!"
        return data_status

def testing_download_payout_csv_report_data(userId, startDate, endDate):
    downloadPayoutCSVReportsList = []
    relative_temp_csv_file_name = ""
    try:
        fileName = "payout"+"_"+ str(get_epoch_milli_time()) + ".csv"
        fund_transfer_queryset = FundTransfers.objects(createdOn__gte=startDate,createdOn__lte=endDate,userId=userId,status__in=[0, 1, 2,3,4,5]).order_by("-id").all()
        for each_payout_report in fund_transfer_queryset:
            payoutCSVReportDict = fetching_payout_csv_download_reports(each_payout_report)
            downloadPayoutCSVReportsList.append(payoutCSVReportDict)

        fieldnames = [
            'Account Number', 'Account IFSCCode', 'Beneficiary Name', 'Beneficiary Mail',
            'Beneficiary Phone', 'Amount','Grand Total','Payment Mode', 'Comment', 'Order Id',
            'Bank Branch', 'Transfer Type', 'Transaction UniqueId', 'Pg OrderId','Txn Date', 'Transaction Status'
        ]

        # Define the base directory and the relative file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/testing_reports")
        relative_temp_csv_file_name = os.path.join("media/testing_reports", fileName)

        # Ensure the base directory exists
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        # Full file name for writing
        full_file_name = os.path.join(base_dir, fileName)
        with open(full_file_name, 'w', encoding='UTF8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(downloadPayoutCSVReportsList)

        return relative_temp_csv_file_name
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_csv_file_name


@frontend_reports.route("/testing_payin_download_reports_list", methods=["POST"])
@user_required
def testing_payin_download_reports_list():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId", "")
    startDate = request.json.get("startDate", "")
    endDate = request.json.get("endDate", "")
    downloadReportsList = []

    date_format = "%d-%m-%Y"
    try:
        if startDate and endDate:
            startDate = datetime.datetime.strptime(startDate, date_format)
            startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)

            endDate = datetime.datetime.strptime(endDate, date_format)
            endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
        else:
            startDate = None
            endDate = None
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Invalid date format!!"
        return data_status

    try:
        payinData = testing_download_payin_csv_report_data(userId, startDate, endDate)
        print(payinData,"((((((((((((PAYIN ADMIN REPORT TESTING DATA))))))))))))")
        data_status["responseStatus"] = 1
        data_status["result"] = "Payin download reports fetched successfully!"
        data_status["payinData"] = domain + payinData
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch payin download reports!"
        return data_status

# def testing_download_payin_csv_report_data(userId, startDate, endDate):
#     downloadPayinCSVReportsList = []
#     relative_temp_csv_file_name = ""
#     try:
#         fileName = "payin"+"_"+ str(get_epoch_milli_time()) + ".csv"
#         payins_queryset = WalletTransactions.objects(createdOn__gte = startDate,createdOn__lte = endDate,userId=userId,status__in=[0,1,4,5,6]).order_by("-id").all()

#         for each_payin_report in payins_queryset:
#             payinCSVReportDict = fetching_payin_csv_download_reports(each_payin_report)
#             downloadPayinCSVReportsList.append(payinCSVReportDict)

#         fieldnames = [
#                 'Customer Name', 'Customer Email', 'Customer Mobile Number','Customer Account' ,'Amount','Charge Amount','Grand Total','Opening Balance','Closing Balance','Order Id','Bank RefId','Transaction UniqueId','Payment Type', 'Txn Date', 'Transaction Status','User Type','Reference Id','Comment','Remarks'
#             ]

#         # Define the base directory and the relative file path
#         base_dir = os.path.join(app.config['SITE_ROOT'], "media/testing_payin_reports")
#         relative_temp_csv_file_name = os.path.join("media/testing_payin_reports", fileName)

#         # Ensure the base directory exists
#         if not os.path.exists(base_dir):
#             os.makedirs(base_dir)

#         # Full file name for writing
#         full_file_name = os.path.join(base_dir, fileName)
#         with open(full_file_name, 'w', encoding='UTF8', newline='') as f:
#             writer = csv.DictWriter(f, fieldnames=fieldnames)
#             writer.writeheader()
#             writer.writerows(downloadPayinCSVReportsList)

#         return relative_temp_csv_file_name
#     except Exception as e:
#         app.logger.error(traceback.format_exc())
#         return relative_temp_csv_file_name


def testing_download_payin_csv_report_data(userId, startDate, endDate):
    downloadPayinCSVReportsList = []
    relative_temp_csv_file_name = ""
    try:
        fileName = "payin_" + str(get_epoch_milli_time()) + ".csv"
        # Convert startDate and endDate to datetime objects if they are not already
        # startDate = datetime.datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S')
        # endDate = datetime.datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')

        query = {
            'createdOn': {'$gte': startDate, '$lte': endDate},
            'userId': userId,
            'status': {'$in': [0, 1, 2, 4, 5]}
        }

        payins_queryset = WalletTransactions.objects(createdOn__gte = startDate,createdOn__lte = endDate,userId=userId,status__in=[0,1,2,4,5]).order_by('-id')

        for each_payin_report in payins_queryset:
            payinCSVReportDict = fetching_payin_csv_download_reports(each_payin_report)
            if each_payin_report.previousBalance:
                payinCSVReportDict["Opening Balance"] = "{:.2f}".format(float(each_payin_report.previousBalance))
            else:
                payinCSVReportDict["Opening Balance"] = "0.00"

            if each_payin_report.currentBalance:
                payinCSVReportDict["Closing Balance"] = "{:.2f}".format(float(each_payin_report.currentBalance))
            else:
                payinCSVReportDict["Closing Balance"] = "0.00"
            downloadPayinCSVReportsList.append(payinCSVReportDict)

        fieldnames = [
            'Customer Name', 'Customer Email', 'Customer Mobile Number', 'Customer Account', 'Amount', 'Charge Amount', 'Grand Total', 'Opening Balance', 'Closing Balance', 'Order Id', 'Bank RefId', 'Transaction UniqueId', 'Payment Type', 'Txn Date', 'Transaction Status', 'User Type', 'Reference Id', 'Comment', 'Remarks'
        ]

        # Define the base directory and the relative file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/testing_payin_reports")
        relative_temp_csv_file_name = os.path.join("media/testing_payin_reports", fileName)

        # Ensure the base directory exists
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        # Full file name for writing
        full_file_name = os.path.join(base_dir, fileName)
        with open(full_file_name, 'w', encoding='UTF8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(downloadPayinCSVReportsList)

        return relative_temp_csv_file_name
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_csv_file_name

######################################### Customer VPA CSV Code ###################################################################
def fetching_customervpa_payin_csv_download_reports(each_payin_report):
    payinCSVReportDict = {}
    try:
        if each_payin_report.customerName:
            payinCSVReportDict["Customer Name"] = each_payin_report.customerName
        else:
            payinCSVReportDict["Customer Name"] = ""

        if each_payin_report.customerEmail:
            payinCSVReportDict["Customer Email"] = each_payin_report.customerEmail
        else:
            payinCSVReportDict["Customer Email"] = ""

        if each_payin_report.userId:
            payinCSVReportDict["Merchant Name"] = each_payin_report.userId.fullName
        else:
            payinCSVReportDict["Merchant Name"] = ""

        if each_payin_report.amount:
            payinCSVReportDict["Amount"] = "{:.2f}".format(float(each_payin_report.amount))
        else:
            payinCSVReportDict["Amount"] = ""

        if each_payin_report.grandTotal:
            payinCSVReportDict["Grand Total"] = "{:.2f}".format(float(each_payin_report.grandTotal))
        else:
            payinCSVReportDict["Grand Total"] = ""

        if each_payin_report.orderId:
            payinCSVReportDict["Order Id"] = each_payin_report.orderId
        else:
            payinCSVReportDict["Order Id"] = ""

        if each_payin_report.createdOn:
            payinCSVReportDict["Txn Date"] = each_payin_report.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
        else:
            payinCSVReportDict["Txn Date"] = ""

        if each_payin_report.status == 1:
            payinCSVReportDict["Transaction Status"]="Success"
        elif each_payin_report.status == 2:
            payinCSVReportDict["Transaction Status"]="Processing"
        else:
            payinCSVReportDict["Transaction Status"]="Failed"

        if each_payin_report.customerVpa:
            payinCSVReportDict["Customer VPA"] = each_payin_report.customerVpa
        else:
            payinCSVReportDict["Customer VPA"] = ""

    except Exception as e:
        app.logger.error(traceback.format_exc())
    return payinCSVReportDict

def customer_vpa_download_payin_csv_report_data(userId, startDate, endDate):
    downloadPayinCSVReportsList = []
    relative_temp_csv_file_name = ""
    try:
        fileName = "customer_vpa_payin"+"_"+str(get_epoch_milli_time()) + ".csv"
        payins_queryset = WalletTransactions.objects(createdOn__gte = startDate,createdOn__lte = endDate,userType="user",userId=userId,status__in=[0,1,4]).order_by("-id").all()
        for each_payin_report in payins_queryset:
            payinCSVReportDict = fetching_customervpa_payin_csv_download_reports(each_payin_report)
            downloadPayinCSVReportsList.append(payinCSVReportDict)

        fieldnames = ['Customer Name', 'Customer Email', 'Merchant Name', 'Amount','Grand Total','Order Id', 'Txn Date', 'Transaction Status','Customer VPA']

        # Define the base directory and the relative file path
        base_dir = os.path.join(app.config['SITE_ROOT'], "media/testing_payin_reports")
        relative_temp_csv_file_name = os.path.join("media/testing_payin_reports", fileName)

        # Ensure the base directory exists
        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        # Full file name for writing
        full_file_name = os.path.join(base_dir, fileName)
        with open(full_file_name, 'w', encoding='UTF8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(downloadPayinCSVReportsList)

        return relative_temp_csv_file_name
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return relative_temp_csv_file_name

@frontend_reports.route("/customer_vpa_payin_download_reports_list", methods=["POST"])
@user_required
def customer_vpa_payin_download_reports_list():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId", "")
    startDate = request.json.get("startDate", "")
    endDate = request.json.get("endDate", "")

    date_format = "%d-%m-%Y"
    try:
        if startDate and endDate:
            startDate = datetime.datetime.strptime(startDate, date_format)
            startDate = startDate.replace(hour=0, minute=0, second=0, microsecond=0)

            endDate = datetime.datetime.strptime(endDate, date_format)
            endDate = endDate.replace(hour=23, minute=59, second=59, microsecond=999999)
        else:
            startDate = None
            endDate = None
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Invalid date format!!"
        return data_status

    try:
        payinData = customer_vpa_download_payin_csv_report_data(userId, startDate, endDate)
        data_status["responseStatus"] = 1
        data_status["result"] = "Customer vpa payin download reports fetched successfully!"
        data_status["payinData"] = domain + payinData
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch customer vpa payin download reports!"
        return data_status



@frontend_reports.route("/charge_back_reports_list",methods=["POST"])
@user_required
def charge_back_reports_list():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId", "")
    rrn = request.json.get("rrn", "")
    pageLimit = request.json.get("pageLimit","20")
    pageOffset = request.json.get("pageOffset","0")
    chargeBackList = []
    
    try:
        page_start=int(pageOffset)
        page_end=int(pageOffset)+int(pageLimit)

        chargebacks_reports_queryset = ChargeBacks.objects(userId=userId).order_by("-id").all()
        if rrn:
            chargebacks_reports_queryset = chargebacks_reports_queryset.filter(rrn__icontains=rrn)
            
        for each_charge_back in chargebacks_reports_queryset[page_start:page_end]:
            chargebackDict = fetching_charge_backs_reports(each_charge_back)
            chargeBackList.append(chargebackDict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Charge backs reports fetched successfully!"
        data_status["chargeBackList"] = chargeBackList
        data_status["totalchargeBacksCount"]=chargebacks_reports_queryset.count()
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch charge backs reports data!!"
        return data_status

@frontend_reports.route("/usdt_transactions_list",methods=["POST"])
# @user_required
def usdt_transactions_list():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId","")
    pageLimit = request.json.get("pageLimit","20")
    pageOffset = request.json.get("pageOffset","0")
    usdtTransactionsList = []
    try:
        page_start=int(pageOffset)
        page_end=int(pageOffset)+int(pageLimit)

        usdt_transactions_queryset = UsdtTransactions.objects(userId=userId).order_by("-id").all()
            
        for each_usdt in usdt_transactions_queryset[page_start:page_end]:
            usdtDict = fetching_usdt_transactions(each_usdt)
            usdtTransactionsList.append(usdtDict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Usdt transactions data fetched successfully!"
        data_status["usdtTransactionsList"] = usdtTransactionsList
        data_status["totalusdtTransactionsCount"]=usdt_transactions_queryset.count()
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch usdt transactions data!!"
        return data_status


# document_content = "<p> Dear $$NAME$$,</p> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p> Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of 'de Finibus Bonorum et Malorum' (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, 'Lorem ipsum dolor sit amet..', comes from a line in section 1.10.32.</p>"


# @frontend_reports.route("/merchant_agreement",methods=["POST"])
# # @user_required
# def merchant_agreement():
#     data_status = {"responseStatus": 0, "result": ""}
#     userId = request.json.get("userId","")
#     signatureImage = request.json.get("signatureImage","")
#     agreementAutherized = request.json.get("agreementAutherized")
#     try:
#         merchant_queryset = Users.objects(id=userId,status=1).first()

#         if signatureImage:
#             save_file = upload_file_image(signatureImage, "merchantSignatures", str(userId), ".png")
#             merchant_queryset.update(signatureImage=save_file,agreementAutherized=agreementAutherized)

#             merchantName = merchant_queryset.fullName

#             signatureImage = domain+merchant_queryset.signatureImage
#             print(signatureImage,"signatureImage")

#             # document_queryset = Documents.objects(status=1).order_by("-id").first()

#             # documentContent = document_queryset.documentContent

#             # Replace placeholders with actual data
#             content = remove_html_tags(document_content).replace("$$NAME$$", merchantName)

#             # Check whether the 'media' folder exists, if not create one
#             expected_media_folder = os.path.join(site_root_directory, "media")
#             if not os.path.exists(expected_media_folder):
#                 os.makedirs(expected_media_folder)

#             print(expected_media_folder,"expected_media_folder")

#             # Check whether the 'merchantAgreements' folder exists, if not create a new one
#             expected_signature_folder = os.path.join(expected_media_folder, "merchantSignatures")
#             if not os.path.exists(expected_signature_folder):
#                 os.makedirs(expected_signature_folder)

#             # Check whether the 'merchantAgreements' folder exists, if not create a new one
#             expected_folder = os.path.join(expected_media_folder, "merchantAgreements")
#             if not os.path.exists(expected_folder):
#                 os.makedirs(expected_folder)

#             # Create PDF using FPDF
#             pdf = FPDF()
#             pdf.add_page()
#             pdf.set_font("Arial", size=12)

#             # Get page dimensions
#             pdf_width = pdf.w - 10  # PDF width minus margins
#             pdf_height = pdf.h - 20  # PDF height minus margins

#             # Define the width of the text area
#             text_width = 190  # Adjust as needed (PDF width - margins)

#             # Add text content
#             pdf.set_x(10)  # Set starting x position (left margin)
#             pdf.multi_cell(text_width, 10, txt=content, border=0, align="L")  # Use multi_cell for wrapping text

#             image_expected_signature_folder = os.path.join(expected_signature_folder, str(userId)+".png")

#             print(image_expected_signature_folder,"(((((((image_expected_signature_folder)))))))")
#             # Add the signature image at the bottom right
#             if os.path.exists(image_expected_signature_folder):
#                 print("IFFFFFFFFFFFF")
#                 pdf.ln(3)  # Move down by 10 units (adjust as needed)

#                 # Image dimensions
#                 img_w = 120
#                 img_h = 40

#                 # Calculate x position: PDF width minus image width and margin
#                 x_pos = pdf_width - img_w - 2
#                 # Calculate y position: PDF height minus image height and margin
#                 y_pos = pdf_height - img_h - 2

#                 pdf.image(image_expected_signature_folder, x=x_pos, w=img_w, h=img_h)

#                 # Add static text signature at the bottom right
#                 signature_text = "Authorized Signature"
#                 pdf.set_font("Arial", size=10)
#                 # Calculate text width and height
#                 txt_w = pdf.get_string_width(signature_text)
#                 txt_h = pdf.font_size

#                 # Position for static text signature
#                 x_text_pos = pdf_width - txt_w - 10
#                 y_text_pos = pdf_width - txt_h + 25

#                 pdf.text(x_text_pos, y_text_pos, signature_text)

            

#             print(expected_folder,"expected_folder")
#             corresponding_folder_name = os.path.join(expected_media_folder, "merchantAgreements/")
#             print(corresponding_folder_name,"corresponding_folder_name")

#             if not os.path.exists(corresponding_folder_name):
#                 os.makedirs(corresponding_folder_name)

#             pdf_file_path = os.path.join(corresponding_folder_name, f"{userId}.pdf")
#             print(pdf_file_path,"????????????????????")

#             savePath = "media/merchantAgreements/"+str(userId)+".pdf"

#             merchant_queryset.update(agreementDocument=savePath)

#         data_status["responseStatus"] = 1
#         data_status["result"] = "Merchant agreement successful!"
#         data_status["pdf_file_path"] = domain+savePath
#         data_status["signatureImage"] = signatureImage
#         return data_status
#     except Exception as e:
#         app.logger.error(traceback.format_exc())
#         data_status["result"] = "Unable to agreement for merchant!!"
#         return data_status



@frontend_reports.route("/merchant_agreement", methods=["POST"])
@user_required
def merchant_agreement():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId", "")
    signatureImage = request.json.get("signatureImage", "")
    agreementAutherized = request.json.get("agreementAutherized")
    try:
        merchant_queryset = Users.objects(id=userId, status=1).first()

        if signatureImage:
            save_file = upload_file_image(signatureImage, "merchantSignatures", str(userId), ".png")
            merchant_queryset.update(signatureImage=save_file, agreementAutherized=agreementAutherized)

            merchantName = merchant_queryset.fullName
            if merchant_queryset.signatureImage:
                signatureImage = domain + merchant_queryset.signatureImage
                print(signatureImage, "signatureImage")

                documentContent = ""
                document_queryset = Documents.objects(status=1).order_by("-id").first()

                documentContent = document_queryset.documentContent

                content = remove_html_tags(documentContent).replace("$$NAME$$", merchantName)

                # Define media directories
                media_dir = os.path.join(app.config['SITE_ROOT'], "media")
                signature_dir = os.path.join(media_dir, "merchantSignatures")
                agreements_dir = os.path.join(media_dir, "merchantAgreements")

                # Create directories if they don't exist
                os.makedirs(signature_dir, exist_ok=True)
                os.makedirs(agreements_dir, exist_ok=True)

                # Create PDF using FPDF
                pdf = FPDF()
                pdf.add_page()
                pdf.set_font("Arial", size=12)

                #Get page dimensions
                pdf_width = pdf.w - 10  # PDF width minus margins
                pdf_height = pdf.h - 20  # PDF height minus margins

                # Define the width of the text area
                text_width = 190  # Adjust as needed (PDF width - margins)

                # Add text content
                pdf.set_x(10)  # Set starting x position (left margin)
                pdf.multi_cell(text_width, 10, txt=content, border=0, align="L")  # Use multi_cell for wrapping text

                image_path = os.path.join(signature_dir, f"{userId}.png")
                print(image_path, "(((((image_path)))))")

                # Add the signature image at the bottom right
                if os.path.exists(image_path):
                    print("IFFFFFFFFFFFF")
                    pdf.ln(3)  # Move down by 10 units (adjust as needed)

                    # Image dimensions
                    img_w = 85
                    img_h = 40

                    # Calculate x position: PDF width minus image width and margin
                    x_pos = pdf_width - img_w - 2
                    # Calculate y position: PDF height minus image height and margin
                    y_pos = pdf_height - img_h - 2

                    pdf.image(image_path, x=x_pos, w=img_w, h=img_h)

                    # Add static text signature at the bottom right
                    signature_text = "Authorized Signature"
                    pdf.set_font("Arial", size=10)
                    # Calculate text width and height
                    txt_w = pdf.get_string_width(signature_text)
                    txt_h = pdf.font_size

                    # Position for static text signature
                    x_text_pos = pdf_width - txt_w - 10
                    y_text_pos = pdf_width - txt_h + 25
                    pdf.text(x_text_pos, y_text_pos, signature_text)

                # Define the path to save the PDF
                pdf_file_path = os.path.join(agreements_dir, f"{userId}.pdf")
                print(pdf_file_path, "????????????????????")

                # Save the PDF file
                pdf.output(pdf_file_path)
                print(f"PDF saved at {pdf_file_path}")

                savePath = f"media/merchantAgreements/{userId}.pdf"
                merchant_queryset.update(agreementDocument=savePath)

        data_status["responseStatus"] = 1
        data_status["result"] = "Merchant agreement successful!"
        # data_status["pdf_file_path"] = domain + savePath
        # data_status["signatureImage"] = signatureImage
        return jsonify(data_status)
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to generate agreement for merchant!"
        return jsonify(data_status)