
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):
            values = [
                data.get("mat_tax_credit", 0),
                data.get("surcharge", 0),
                data.get("cess", 0),
                data.get("total_credit", 0),
                data.get("year", 0)
            ]
            self.cursor.callproc("InsertITAT", values)
            self.conn.commit()

    # UPDATE ITAT (PROC)
    def update_itat(self, id, data):
        values = [
            id,
            data.get("year"),
            data.get("mat_tax_credit"),
            data.get("surcharge"),
            data.get("cess"),
            data.get("total_credit")
        ]
        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()
