
from AppCode.Config import DBConfig
import mysql.connector
import pandas as pd
import io

class ITATHandler:

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

    # GET ALL ITAT RECORDS (PROC)
    def get_all_itat(self):
        self.cursor.callproc("GetAllITAT")
        records = []
        for result in self.cursor.stored_results():
            records = result.fetchall()
        return records


    # GET ITAT BY ID (PROC)
    def get_itat_by_id(self, id):
        self.cursor.callproc("GetITATById", [id])
        records = []
        for result in self.cursor.stored_results():
            records = result.fetchall()
        if records:
            return records[0]
        return None


    # INSERT ITAT (PROC)
    def add_itat(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','sat', 'tax_on_assessment', 'refund', 'Remarks'
                ]
        values = [data.get(col, 0) for col in columns]

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

    # UPDATE ITAT (PROC)
    def update_itat(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', 'sat','tax_on_assessment', 'refund','Remarks'
        ]
        values = [id] + [data.get(col, 0) for col in columns]  

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

    # DELETE ITAT BY ID (PROC)
    def delete_itat_by_id(self, id):
        self.cursor.callproc("DeleteITATById", [id])
        self.conn.commit()


   
    def itat_report_download(self, selected_year):
            try:
                # Call stored procedure
                self.cursor.callproc("GetITATByYear", [selected_year])
                rows = []
                for result in self.cursor.stored_results():
                    rows = result.fetchall()

                if not rows:
                    return None

                df = pd.DataFrame(rows)

                # Excel output
                output = io.BytesIO()
                with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
                    df.T.to_excel(writer, header=False, sheet_name="ITAT_Report")

                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()
