from AppCode.Config import DBConfig
import mysql.connector
from AppCode.YearGet import YearGet

import pandas as pd
import pymysql
import io

# new
from AppCode.Config import DBConfig
import mysql.connector
import pandas as pd
import io
from flask import send_file, render_template, request



class ITRHandler:

    def __init__(self):
        self.conn = DBConfig.get_db_connection()
        self.cursor = self.conn.cursor(dictionary=True)
        

    # GET ALL ITR RECORDS using stored procedure "GetAllItr"
    def get_all_itr(self):
        # self.cursor = conn.cursor(dictionary=True)

        self.cursor.callproc("GetAllItr")
        records = []

        for result in self.cursor.stored_results():
            records = result.fetchall()

        return records


    def get_itr_by_id(self, id):
        # Call stored procedure
        self.cursor.callproc('GetITRById', [id])

        # Fetch result
        records = []
        for result in self.cursor.stored_results():
            records = result.fetchall()

        if records:
            print(records[0])
            return records[0]  # return single record
           
        return None




    # INSERT ITR RECORD using procedure "add_itr"
    def add_itr(self, data):

        columns = [
            'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
            'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other',
            'deduction_sec37_disallowance', 'deduction_80g', 'net_taxable_income',
            'tax_30_percent', 'tax_book_profit_18_5', 'tax_payable', 'surcharge_12',
            'edu_cess_3', 'total_tax_payable', 'mat_credit', 'interest_234c',
            'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund', 'Remarks'
        ]

        values = [data.get(col, 0) for col in columns]

        # Call your stored procedure
        self.cursor.callproc("InsertITR", values)
        self.conn.commit()

    
    def update(self, id, data):
        columns = [
            'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
            'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other',
            'deduction_sec37_disallowance', 'deduction_80g', 'net_taxable_income',
            'tax_30_percent', 'tax_book_profit_18_5', 'tax_payable', 'surcharge_12',
            'edu_cess_3', 'total_tax_payable', 'mat_credit', 'interest_234c',
            'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund','Remarks'
        ]

        values = [id] + [data.get(col, 0) for col in columns]  

        print("Final values:", values)  

        self.cursor.callproc("UpdateITR", values)
        self.conn.commit()


    # DELETE RECORD by ITR id
    def delete_itr_by_id(self, id):
        # Call the stored procedure
        self.cursor.callproc('DeleteITRById', [id])
        self.conn.commit()



    def itr_report_download(self, selected_year):

            try:
                # Call stored procedure
                self.cursor.callproc("GetITRByYear", [selected_year])

                rows = []
                for result in self.cursor.stored_results():
                    rows = result.fetchall()

                if not rows:
                    return None

                # Convert SQL rows to DataFrame
                df = pd.DataFrame(rows)

                # Transpose
                df_transposed = df.transpose()
                df_transposed.insert(0, 'Field', df_transposed.index)

                print("df-->",df_transposed)
            

                record_cols = {
                    i: f"Record {i}"
                    for i in df_transposed.columns if isinstance(i, int)
                }

                df_transposed.rename(columns=record_cols, inplace=True)
                df_transposed.reset_index(drop=True, inplace=True)

                # Save to Excel in memory
                output = io.BytesIO()
                with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
                    df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')
                    worksheet = writer.sheets['ITR_Vertical']
                    worksheet.set_column(0, 0, 30)

                output.seek(0)
                return output

            except mysql.connector.Error as e:
                print("MySQL Error →", e)
                return None


    # CLOSE CONNECTION
    def close(self):
        self.cursor.close()
        self.conn.close()
