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



class CITHandler:

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

    # GET ALL CIT RECORDS
    def get_all_cit(self):
        self.cursor.callproc("GetAllCIT")
        records = []

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

        return records

    # GET CIT BY ID
    def get_cit_by_id(self, id):
        self.cursor.callproc("GetCITById", [id])
        records = []

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

        if records:
            return records[0]

        return None

    # INSERT CIT RECORD
    def add_cit(self, data):
        columns = [
            "year", "gross_total_income", "deduction_80ia_business", "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]

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


  
    # UPDATE CIT RECORD
    def update_cit(self, id, data):
        columns = [
            "year", "gross_total_income", "deduction_80ia_business",
            "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]

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



    # DELETE CIT RECORD
    def delete_cit(self, id):
        self.cursor.callproc("DeleteCITById", [id])
        self.conn.commit()

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


    def cit_report_download(self, selected_year):
            try:
                # Call stored procedure
                self.cursor.callproc("GetCITByYear", [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:

                    for i, (_, row) in enumerate(df.iterrows(), start=1):
                        # Convert row to vertical format
                        vertical_df = pd.DataFrame(row).reset_index()
                        vertical_df.columns = ['Field', 'Value']

                        start_row = (i - 1) * (len(vertical_df) + 3)  # gap between blocks
                        vertical_df.to_excel(
                            writer,
                            sheet_name='CIT_Report',
                            index=False,
                            startrow=start_row
                        )

                output.seek(0)
                return output

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