import config
import mysql.connector

class Paymentmodel:

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

    @staticmethod
    def fetch_all_payments():
        connection = Paymentmodel.get_connection()
        payments = []
        if connection:
            cursor = connection.cursor(dictionary=True)
            try:
                cursor.callproc('GetAllPayments')
                for result in cursor.stored_results():
                    payments = result.fetchall()
            except mysql.connector.Error as e:
                print(f"Error fetching payment history: {e}")
            finally:
                cursor.close()
                connection.close()
        return payments

    @staticmethod
    def insert_payment(pmc_no, invoice_no, amount, tds_amount, total_amount, utr):
        connection = Paymentmodel.get_connection()
        if not connection:
            return False
        try:
            cursor = connection.cursor()
            cursor.callproc('InsertPayments', [pmc_no, invoice_no, amount, tds_amount, total_amount, utr])
            connection.commit()
            return True
        except mysql.connector.Error as e:
            print(f"Error inserting payment: {e}")
            return False
        finally:
            cursor.close()
            connection.close()

    @staticmethod
    def update_inpayment(subcontractor_id, pmc_no, invoice_no, amount, tds_amount, total_amount, utr):
        connection = Paymentmodel.get_connection()
        if not connection:
            return False
        try:
            cursor = connection.cursor()
            cursor.callproc('UpdateInpaymentRecord', [
                    subcontractor_id,
                    pmc_no,
                    invoice_no,
                    amount,
                    tds_amount,
                    total_amount,
                    utr
                ])
            connection.commit()
            return True
        except mysql.connector.Error as e:
            print(f"Error updating inpayment: {e}")
            return False
        finally:
            cursor.close()
            connection.close()

    @staticmethod
    def fetch_payment_by_id(payment_id):
        connection = Paymentmodel.get_connection()
        if not connection:
            return None
        payment_data = {}
        try:
            cursor = connection.cursor(dictionary=True)
            cursor.callproc("GetPaymentById", (payment_id,))
            for result in cursor.stored_results():
                payment_data = result.fetchone()
            # Convert to array for template
            if payment_data:
                payment_data = [
                    payment_data.get('Payment_Id'),
                    payment_data.get('PMC_No'),
                    payment_data.get('Invoice_No'),
                    payment_data.get('Payment_Amount'),
                    payment_data.get('TDS_Payment_Amount'),
                    payment_data.get('Total_Amount'),
                    payment_data.get('UTR')
                ]
        except mysql.connector.Error as e:
            print(f"Error fetching payment data: {e}")
        finally:
            cursor.close()
            connection.close()
        return payment_data

    @staticmethod
    def call_update_payment_proc(payment_id, pmc_no, invoice_no, amount, tds_amount, total_amount, utr):
        connection = Paymentmodel.get_connection()
        if not connection:
            return False
        try:
            cursor = connection.cursor()
            cursor.callproc("UpdatePayment", (payment_id, pmc_no, invoice_no, amount, tds_amount, total_amount, utr))
            connection.commit()
            return True
        except mysql.connector.Error as e:
            print(f"Error updating payment: {e}")
            return False
        finally:
            cursor.close()
            connection.close()

    @staticmethod
    def delete_payment(payment_id):
        """
        Deletes a payment and resets the related inpayment fields in one go.
        Returns (success, pmc_no, invoice_no)
        """
        connection = Paymentmodel.get_connection()
        if not connection:
            return False, None, None

        try:
            cursor = connection.cursor(dictionary=True)

            cursor.callproc('GetPaymentPMCInvoiceById', [payment_id])

            record = {}
            for result in cursor.stored_results():
                record = result.fetchone() or {}
            if not record:
                return False, None, None

            pmc_no = record['PMC_No']
            invoice_no = record['Invoice_No']

            # Step 2: Delete the payment using the stored procedure
            cursor.callproc("DeletePayment", (payment_id,))
            connection.commit()

            # Step 3: Reset inpayment fields using the stored procedure
            cursor.callproc("ResetInpayment", [pmc_no, invoice_no])
            connection.commit()

            return True, pmc_no, invoice_no

        except mysql.connector.Error as e:
            print(f"Error deleting payment: {e}")
            return False, None, None

        finally:
            cursor.close()
            connection.close()