import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import PatternFill

# Load MomentsPay_Bank_new.xlsx
moments_pay_bank_df = pd.read_excel('hdfcupi24-05.xlsx')

# Load Transaction details as on 14.12.2023
transaction_details_df = pd.read_excel('PineLabTransaction23-05.xlsx')

# Convert relevant columns to a common data type (string)
transaction_details_df['RRN'] = transaction_details_df['RRN'].astype(str).replace(r'\.0$', '', regex=True)
moments_pay_bank_df['Txn ref no.(RRN)'] = moments_pay_bank_df['Txn ref no.(RRN)'].astype(str).replace(r'\.0$', '', regex=True)

# Specify the mapping between fields excluding 'processing_id' and 'transaction_id'
field_mapping = {'RRN': 'Txn ref no.(RRN)'}

# Filter only UPI transactions
transaction_details_df = transaction_details_df[transaction_details_df['Payment Mode'] == 'UPI']
#moments_pay_bank_df = moments_pay_bank_df[moments_pay_bank_df['Payment Mode'] == 'UPI']

# Remove duplicates from moments_pay_bank_df based on 'Txn ref no.(RRN)'
moments_pay_bank_df_dedup = moments_pay_bank_df.drop_duplicates(subset=['Txn ref no.(RRN)'], keep='first')

# Merge dataframes on the specified fields
merged_df = pd.merge(transaction_details_df, moments_pay_bank_df_dedup[list(field_mapping.values())],
                     left_on=list(field_mapping.keys()),
                     right_on=list(field_mapping.values()),
                     how='left')
unmerged_df = pd.merge(transaction_details_df, moments_pay_bank_df_dedup[list(field_mapping.values())],
                       left_on=list(field_mapping.keys()),
                       right_on=list(field_mapping.values()),
                       how='outer')

equal_records = merged_df[~merged_df['Txn ref no.(RRN)'].isnull()]
equal_records.insert(0, 'S.No.', range(1, len(equal_records) + 1))
equal_records['momentpay matched'] = 'YES'

unequal_records = unmerged_df[unmerged_df['Txn ref no.(RRN)'].isnull() & (unmerged_df['Payment Mode'] == 'UPI')]
unequal_records.insert(0, 'S.No.', range(1, len(unequal_records) + 1))
unequal_records['momentpay matched'] = 'NO'

# Function to create or overwrite an Excel sheet
def create_or_overwrite_sheet(sheet_name, data):
    with pd.ExcelWriter('Rela-HISBANK24-05.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
        data.to_excel(writer, sheet_name=sheet_name, index=False)

# Generate sheet names
sheet_name_matched = 'PineBankupi-Matched'
sheet_name_unmatched = 'PineBankupi-Unmatched'
create_or_overwrite_sheet(sheet_name_matched, equal_records)
create_or_overwrite_sheet(sheet_name_unmatched, unequal_records)

wb = load_workbook('Rela-HISBANK24-05.xlsx')
Summary_Sheet = wb['Summary']

transaction_date = moments_pay_bank_df['Transaction Req Date'].mode()[0]
print(transaction_date)

# Update summary sheet with total UPI transaction details
num_rows = len(transaction_details_df)
Summary_Sheet['E16'] = num_rows

total_amount = transaction_details_df['Amount'].astype(float).sum()
Summary_Sheet['F16'] = f"₹{total_amount:,.2f}"

# Update summary sheet with matched UPI transaction details
HIS_Matched_df = pd.read_excel('Rela-HISBANK24-05.xlsx', sheet_name='PineBankupi-Matched')
num_rows = len(HIS_Matched_df)
Summary_Sheet['G16'] = num_rows

total_amount = HIS_Matched_df['Amount'].astype(float).sum()
Summary_Sheet['H16'] = f"₹{total_amount:,.2f}"

# Update summary sheet with unmatched UPI transaction details
HIS_UnMatched_df = pd.read_excel('Rela-HISBANK24-05.xlsx', sheet_name='PineBankupi-Unmatched')
num_rows = len(HIS_UnMatched_df)
Summary_Sheet['I16'] = num_rows

total_amount = HIS_UnMatched_df['Amount'].astype(float).sum()
Summary_Sheet['J16'] = f"₹{total_amount:,.2f}"

# Define the color for the header
header_fill = PatternFill(fgColor='1274bd', fill_type='solid')

for sheet_name in ['PineBankupi-Matched', 'PineBankupi-Unmatched']:
    worksheet = wb[sheet_name]

    # Apply style to the header row
    for row in worksheet.iter_rows(min_row=1, max_row=1):
        for cell in row:
            cell.fill = header_fill

# Save the workbook
wb.save('Rela-HISBANK24-05.xlsx')

# Save matched and unmatched records to separate files
#def save_to_new_excel_file(file_name, sheet_name, data):
#    with pd.ExcelWriter(file_name, engine='openpyxl') as writer:
#        data.to_excel(writer, sheet_name=sheet_name, index=False)

#save_to_new_excel_file('PineBankupi_matched.xlsx', 'Matched', equal_records)
#save_to_new_excel_file('PineBankupi_unmatched.xlsx', 'Unmatched', unequal_records)


