/**
 * GST Type Manager - Handle Inclusive/Exclusive GST Calculations
 * Manages switching between inclusive and exclusive GST modes
 */

(function() {
    'use strict';

    const GSTTypeManager = {
        currentGSTType: 'inclusive', // Default to inclusive
        
        init: function() {
            // Initialize GST type from hidden field or default
            this.currentGSTType = $('#gstType').val() || 'inclusive';
            
            // Set initial button state
            this.updateButtonState();
            
            // Bind button click events
            $('#btnGSTInclusive').on('click', async () => await this.setGSTType('inclusive'));
            $('#btnGSTExclusive').on('click', async () => await this.setGSTType('exclusive'));
            
            console.log('GST Type Manager initialized - Default:', this.currentGSTType);
        },

        setGSTType: async function(type) {
            if (this.currentGSTType === type) {
                return; // No change needed
            }

            this.currentGSTType = type;
            $('#gstType').val(type);
            
            // Update button visual state
            this.updateButtonState();
            
            // Recalculate totals with new GST type
            this.recalculateTotals();
            
            // Show notification
            await this.showNotification(type);
            
            console.log('GST Type changed to:', type);
        },

        updateButtonState: function() {
            if (this.currentGSTType === 'inclusive') {
                $('#btnGSTInclusive').removeClass('btn-outline-success').addClass('btn-success text-white');
                $('#btnGSTExclusive').removeClass('btn-primary text-white').addClass('btn-outline-primary');
                $('#gstTypeDescription').text('Tax Included').attr('data-translate', 'gstInclusiveDesc');
            } else {
                $('#btnGSTInclusive').removeClass('btn-success text-white').addClass('btn-outline-success');
                $('#btnGSTExclusive').removeClass('btn-outline-primary').addClass('btn-primary text-white');
                $('#gstTypeDescription').text('Tax Added').attr('data-translate', 'gstExclusiveDesc');
            }
        },

        showNotification: async function(type) {
            const message = type === 'inclusive' 
                ? '✓ GST is now INCLUSIVE (Tax included in price)'
                : '✓ GST is now EXCLUSIVE (Tax will be added to price)';
            
            await MsgBox.alert(message, 'info');
        },

        recalculateTotals: function() {
            // Check if cart exists and has items
            if (!window.cart || window.cart.length === 0) {
                console.log('Cart is empty, no recalculation needed');
                return;
            }

            console.log('Recalculating cart for GST type:', this.currentGSTType);
            console.log('Cart items before:', window.cart.length);

            // Recalculate each cart item with the new GST type
            window.cart.forEach((item, index) => {
                // Use taxRate field (which comes from product data)
                const taxRate = item.taxRate || item.taxPercent || 0;
                
                if (taxRate > 0) {
                    const taxMultiplier = 1 + (taxRate / 100);
                    
                    if (this.currentGSTType === 'inclusive') {
                        // INCLUSIVE mode: 
                        // If coming from exclusive mode, need to extract basic from current rate
                        // Price column shows the inclusive price
                        // Basic Rate column will show: rate / (1 + tax%)
                        
                        // If item has basicRate stored (from exclusive mode), use it to calculate inclusive price
                        if (item.basicRate) {
                            item.rate = item.basicRate * taxMultiplier;
                        }
                        
                        const itemTotal = item.rate * item.quantity;
                        item.taxableAmount = itemTotal / taxMultiplier;
                        item.taxAmount = itemTotal - item.taxableAmount;
                        item.basicRate = item.taxableAmount / item.quantity; // Store basic rate per unit
                        
                    } else {
                        // EXCLUSIVE mode: 
                        // Current rate in Price column moves to Basic Rate
                        // Price column = Basic Rate + tax%
                        
                        // Extract basic rate from current inclusive price
                        const extractedBasicRate = item.rate / taxMultiplier;
                        item.basicRate = extractedBasicRate;
                        
                        // Now calculate new price with tax added on top
                        item.rate = item.basicRate * taxMultiplier;
                        
                        const itemTotal = item.basicRate * item.quantity;
                        item.taxableAmount = itemTotal;
                        item.taxAmount = (itemTotal * taxRate) / 100;
                    }
                    
                    // Update amount
                    item.amount = item.rate * item.quantity;
                    
                    console.log(`Item ${item.productName}: BasicRate=${item.basicRate ? item.basicRate.toFixed(2) : 'N/A'}, DisplayRate=${item.rate.toFixed(2)}, Tax=${item.taxAmount.toFixed(2)}`);
                } else {
                    // No tax - rate stays the same
                    item.basicRate = item.rate;
                    item.amount = item.rate * item.quantity;
                }
            });

            // Update the cart table display
            if (typeof window.updateCartTable === 'function') {
                window.updateCartTable();
            }

            // Update totals
            if (typeof window.updateTotals === 'function') {
                window.updateTotals();
            } else if (typeof window.updateDisplay === 'function') {
                // Fallback to updateDisplay if updateTotals doesn't exist
                window.updateDisplay();
            }

            console.log('Recalculation complete');
        },

        recalculateItemGST: function(item) {
            if (!item.taxPercent || item.taxPercent === 0) {
                // No tax on this item
                item.taxAmount = 0;
                item.totalAfterTax = item.rate * item.quantity;
                return;
            }

            const baseAmount = item.rate * item.quantity;
            const taxPercent = parseFloat(item.taxPercent);

            if (this.currentGSTType === 'inclusive') {
                // INCLUSIVE: Price already includes tax, extract it
                // Formula: Tax Amount = (Base Amount × Tax%) / (100 + Tax%)
                // Base (without tax) = Base Amount / (1 + Tax%/100)
                
                const taxableAmount = baseAmount / (1 + (taxPercent / 100));
                const taxAmount = baseAmount - taxableAmount;
                
                item.taxableAmount = taxableAmount;
                item.taxAmount = taxAmount;
                item.totalAfterTax = baseAmount; // Total remains same as price includes tax
                
            } else {
                // EXCLUSIVE: Tax needs to be added to the price
                // Formula: Tax Amount = (Base Amount × Tax%) / 100
                
                const taxAmount = (baseAmount * taxPercent) / 100;
                
                item.taxableAmount = baseAmount;
                item.taxAmount = taxAmount;
                item.totalAfterTax = baseAmount + taxAmount; // Total increases with tax
            }

            console.log(`Item recalculated: ${item.productName}, Type: ${this.currentGSTType}, Tax: ${item.taxAmount.toFixed(2)}, Total: ${item.totalAfterTax.toFixed(2)}`);
        },

        calculateGSTForNewItem: function(item) {
            // This method is called when adding a new item to cart
            // It applies the current GST type to the new item
            this.recalculateItemGST(item);
            return item;
        },

        getGSTType: function() {
            return this.currentGSTType;
        },

        getGSTInfo: function() {
            return {
                type: this.currentGSTType,
                isInclusive: this.currentGSTType === 'inclusive',
                isExclusive: this.currentGSTType === 'exclusive',
                description: this.currentGSTType === 'inclusive' 
                    ? 'Tax is included in the displayed prices' 
                    : 'Tax will be added to the displayed prices'
            };
        },

        // Calculate total tax amount from all cart items
        getTotalTaxAmount: function() {
            if (!window.cart || window.cart.length === 0) {
                return 0;
            }

            let totalTax = 0;
            window.cart.forEach(item => {
                totalTax += (item.taxAmount || 0);
            });

            return totalTax;
        },

        // Calculate total taxable amount
        getTotalTaxableAmount: function() {
            if (!window.cart || window.cart.length === 0) {
                return 0;
            }

            let totalTaxable = 0;
            window.cart.forEach(item => {
                totalTaxable += (item.taxableAmount || (item.rate * item.quantity));
            });

            return totalTaxable;
        },

        // Get summary for display
        getGSTSummary: function() {
            const totalTaxable = this.getTotalTaxableAmount();
            const totalTax = this.getTotalTaxAmount();
            const totalWithTax = totalTaxable + (this.currentGSTType === 'exclusive' ? totalTax : 0);

            return {
                gstType: this.currentGSTType,
                taxableAmount: totalTaxable,
                taxAmount: totalTax,
                totalAmount: totalWithTax,
                formatted: {
                    gstType: this.currentGSTType.toUpperCase(),
                    taxableAmount: '₹' + totalTaxable.toFixed(2),
                    taxAmount: '₹' + totalTax.toFixed(2),
                    totalAmount: '₹' + totalWithTax.toFixed(2)
                }
            };
        }
    };

    // Expose GSTTypeManager globally
    window.GSTTypeManager = GSTTypeManager;

    // Initialize when document is ready
    $(document).ready(function() {
        GSTTypeManager.init();
    });

    // Hook into cart operations to apply GST type
    $(document).on('itemAddedToCart', function(event, item) {
        GSTTypeManager.calculateGSTForNewItem(item);
    });

})();
