import config
import mysql.connector

class GSTReleasemodel:

    @staticmethod
    def get_connection():
        connection = config.get_db_connection()
        if not connection:
            return None
        return connection

    @staticmethod
    def fetch_all_gst_releases():
        connection = GSTReleasemodel.get_connection()
        gst_releases = []
        if connection:
            cursor = connection.cursor(dictionary=True)

            try:
                cursor.callproc('GetAllGSTReleases')

                gst_releases = []
                for result in cursor.stored_results():                              # change to procedure
                    gst_releases = result.fetchall()

            except mysql.connector.Error as e:
                print(f"Error fetching GST releases: {e}")
            finally:
                cursor.close()
                connection.close()
        return gst_releases

    @staticmethod
    def insert_gst_release(pmc_no, invoice_no, basic_amount, final_amount, total_amount, utr, contractor_id):
        connection = GSTReleasemodel.get_connection()
        if not connection:
            return False
        try:
            cursor = connection.cursor()

            # Insert into gst_release
            cursor.callproc(
                'InsertGSTReleaseOnly',
                [pmc_no, invoice_no, basic_amount, final_amount, total_amount, utr, contractor_id]
            )

            # Insert into inpayment
            cursor.callproc(
                'InsertInpaymentOnly',
                [pmc_no, invoice_no, basic_amount, final_amount, total_amount, utr, contractor_id]
            )

            connection.commit()
            return True
        except mysql.connector.Error as e:
            print(f"Error inserting GST release: {e}")
            return False
        finally:
            cursor.close()
            connection.close()

    @staticmethod
    def fetch_gst_release_by_id(gst_release_id):
        connection = GSTReleasemodel.get_connection()
        if not connection:
            return None
        data = {}
        try:
            cursor = connection.cursor(dictionary=True)

            cursor.callproc('GetGSTReleaseById', [gst_release_id])

            for result in cursor.stored_results():
                    data = result.fetchone()
            if data:
                # Convert to array for template
                data = [
                    data.get('GST_Release_Id'),
                    data.get('PMC_No'),
                    data.get('Invoice_No'),
                    data.get('Basic_Amount'),
                    data.get('Final_Amount'),
                    data.get('Total_Amount'),
                    data.get('UTR')
                ]
        except mysql.connector.Error as e:
            print(f"Error fetching GST release by id: {e}")
        finally:
            cursor.close()
            connection.close()
        return data

    @staticmethod
    def update_gst_release(gst_release_id, pmc_no, invoice_no, basic_amount, final_amount, total_amount, utr):
        connection = GSTReleasemodel.get_connection()
        if not connection:
            return False
        try:
            cursor = connection.cursor()
            # Update gst_release
            cursor.callproc(
                'UpdateGSTRelease',
                [pmc_no, invoice_no, basic_amount, final_amount, total_amount, utr, gst_release_id]
            )
            # Update inpayment
            cursor.callproc(
                'UpdateInpaymentByUTR',
                [basic_amount, final_amount, total_amount, utr]
            )
            connection.commit()
            return True
        except mysql.connector.Error as e:
            print(f"Error updating GST release: {e}")
            return False
        finally:
            cursor.close()
            connection.close()

    @staticmethod
    def delete_gst_release(gst_release_id):
        connection = GSTReleasemodel.get_connection()
        if not connection:
            return False, None
        try:
            cursor = connection.cursor(dictionary=True)
            cursor.callproc('GetGSTReleaseUTRById', [gst_release_id])
            record = None
            for result in cursor.stored_results():
                record = result.fetchone()

            if not record:
                return False, None

            utr = record['UTR']

            # Step 1: Delete gst_release
            cursor.callproc('DeleteGSTReleaseById', [gst_release_id])

            # Step 2: Reset inpayment using UTR
            cursor.callproc('ResetInpaymentByUTR', [utr])
            
            connection.commit()
            return True, utr
        except mysql.connector.Error as e:
            print(f"Error deleting GST release: {e}")
            return False, None
        finally:
            cursor.close()
            connection.close()