/**
 * Sales Enhancements - Sales Types, Discounts, and Loyalty Points
 * Modular JavaScript for new features
 */

(function() {
    'use strict';

    // ============================================
    // SALES TYPE MANAGEMENT
    // ============================================
    
    const SalesTypeManager = {
        init: function() {
            $('#salesType').on('change', this.handleSalesTypeChange.bind(this));
            // Load sales types
            this.loadSalesTypes();
        },

        loadSalesTypes: function() {
            $.ajax({
                url: 'api/get-sales-types.php',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        console.log('Sales types loaded:', response.salesTypes);
                    }
                }
            });
        },

        handleSalesTypeChange: function() {
            const selectedType = $('#salesType').val();
            const prefix = $('#salesType option:selected').data('prefix');
            
            $('#currentSalesType').val(selectedType);
            
            // Determine if this is a return type
            const isQuotation = selectedType === 'QUOTATION';
            const isReturn = !isQuotation && selectedType.indexOf('-RETURN') !== -1;

            if (isQuotation) {
                $('#salesTypeCategory').val('QUOTE');
            } else {
                $('#salesTypeCategory').val(isReturn ? 'RETURN' : 'SALE');
            }

            $('#salesType').removeClass('bg-warning text-dark bg-info text-white');

            if (isReturn) {
                $('#salesType').addClass('bg-warning text-dark');
                if (typeof showNotification === 'function') {
                    showNotification('Sales Return mode activated - Stock will be added back', 'warning');
                }
            } else if (isQuotation) {
                $('#salesType').addClass('bg-info text-white');
                if (typeof showNotification === 'function') {
                    showNotification('Quotation mode activated - Stock will remain unchanged until converted to a sale', 'info');
                }
            }
            
            // Generate new invoice number for selected type
            this.generateInvoiceNumber(selectedType);
        },

        generateInvoiceNumber: function(salesType) {
            $.ajax({
                url: 'api/get-next-invoice.php',
                method: 'GET',
                data: { salesType: salesType },
                success: function(response) {
                    if (response.success) {
                        $('#invoiceNumber').val(response.invoiceNumber);
                        $('#currentInvoiceNumber').text(response.invoiceNumber);
                    }
                }
            });
        }
    };

    // ============================================
    // PRODUCT DISCOUNT MANAGEMENT
    // ============================================
    
    const ProductDiscountManager = {
        init: function() {
            $('#productDiscount, #productDiscountType, #rate, #quantity').on('input change', this.calculateProductTotal.bind(this));
        },

        calculateProductTotal: function() {
            const rate = parseFloat($('#rate').val()) || 0;
            const quantity = parseFloat($('#quantity').val()) || 0;
            const discount = parseFloat($('#productDiscount').val()) || 0;
            const discountType = $('#productDiscountType').val();

            if (rate === 0 || quantity === 0) {
                $('#currentItemTotal').text('₹0.00');
                $('#productFinalRate').val('0.00');
                return;
            }

            let discountAmount = 0;
            let finalRate = rate;

            if (discount > 0) {
                if (discountType === 'PERCENTAGE') {
                    if (discount > 100) {
                        MsgBox.alert('Discount percentage cannot exceed 100%');
                        $('#productDiscount').val('0');
                        return;
                    }
                    discountAmount = (rate * discount) / 100;
                } else {
                    if (discount > rate) {
                        MsgBox.alert('Discount amount cannot exceed the rate');
                        $('#productDiscount').val('0');
                        return;
                    }
                    discountAmount = discount;
                }
                finalRate = rate - discountAmount;
            }

            const total = finalRate * quantity;

            $('#productFinalRate').val(finalRate.toFixed(2));
            $('#currentItemTotal').text('₹' + total.toFixed(2));
        },

        getDiscountData: function() {
            return {
                discount: parseFloat($('#productDiscount').val()) || 0,
                discountType: $('#productDiscountType').val(),
                discountAmount: parseFloat($('#rate').val()) - parseFloat($('#productFinalRate').val() || 0),
                finalRate: parseFloat($('#productFinalRate').val()) || parseFloat($('#rate').val()) || 0
            };
        },

        resetDiscount: function() {
            $('#productDiscount').val('0');
            $('#productDiscountType').val('PERCENTAGE');
            $('#productFinalRate').val('0.00');
        }
    };

    // ============================================
    // BILL DISCOUNT MANAGEMENT
    // ============================================
    
    const BillDiscountManager = {
        init: function() {
            // Discount type toggle buttons
            $('#billDiscPercent').on('click', () => this.setDiscountType('PERCENTAGE'));
            $('#billDiscAmount').on('click', () => this.setDiscountType('AMOUNT'));
            
            // Set default active
            $('#billDiscPercent').addClass('active');
            
            // Calculate on input
            $('#billDiscount').on('input', this.calculateBillDiscount.bind(this));
        },

        setDiscountType: function(type) {
            $('#billDiscountType').val(type);
            $('#billDiscPercent, #billDiscAmount').removeClass('active');
            
            if (type === 'PERCENTAGE') {
                $('#billDiscPercent').addClass('active');
                $('#billDiscount').attr('placeholder', '0 %');
                $('#billDiscount').attr('max', '100');
            } else {
                $('#billDiscAmount').addClass('active');
                $('#billDiscount').attr('placeholder', '0.00 ₹');
                $('#billDiscount').removeAttr('max');
            }
            
            this.calculateBillDiscount();
        },

        // Distribute bill discount proportionally to all cart items
        distributeBillDiscountToItems: function(totalBillDiscount) {
            if (!window.cart || window.cart.length === 0) {
                return;
            }

            // Calculate total base amount (before any discounts)
            let totalBaseAmount = 0;
            window.cart.forEach(item => {
                totalBaseAmount += item.rate * item.quantity;
            });

            if (totalBaseAmount === 0) {
                return;
            }

            // Distribute discount proportionally to each item
            window.cart.forEach(item => {
                const itemBaseAmount = item.rate * item.quantity;
                const itemProportion = itemBaseAmount / totalBaseAmount;
                item.billDiscountPortion = totalBillDiscount * itemProportion;
            });

            // Trigger cart table update to reflect distributed discounts
            if (typeof window.updateCartTable === 'function') {
                window.updateCartTable();
            }
        },

        // Calculate total bill discount from product-level discounts
        calculateProductDiscountsTotal: function() {
            if (!window.cart || window.cart.length === 0) {
                return 0;
            }

            let totalProductDiscount = 0;

            window.cart.forEach(item => {
                let productDiscountAmount = 0;
                if (item.discount && item.discount > 0) {
                    const itemBaseAmount = item.rate * item.quantity;
                    if (item.discountType === 'PERCENTAGE') {
                        productDiscountAmount = (itemBaseAmount * item.discount) / 100;
                    } else {
                        productDiscountAmount = item.discount;
                    }
                }
                totalProductDiscount += productDiscountAmount;
            });

            return totalProductDiscount;
        },

        calculateBillDiscount: function() {
            // Get base subtotal (sum of rate × quantity for all items + transport)
            let subTotal = 0;
            if (window.cart && window.cart.length > 0) {
                window.cart.forEach(item => {
                    subTotal += item.rate * item.quantity;
                });
            } else {
                subTotal = parseFloat($('#subTotal').text().replace('₹', '').replace(/,/g, '')) || 0;
            }
            
            // Add transport amount to subtotal for bill discount calculation
            const transportGSTAmount = parseFloat($('#transportGSTAmount').val()) || 0;
            if (transportGSTAmount > 0) {
                subTotal += transportGSTAmount;
            }

            const discount = parseFloat($('#billDiscount').val()) || 0;
            const discountType = $('#billDiscountType').val();

            if (subTotal === 0) {
                $('#billDiscountValue').text('-₹0.00');
                this.distributeBillDiscountToItems(0);
                this.updateGrandTotal(0);
                return;
            }

            let billDiscountAmount = 0;

            if (discount > 0) {
                if (discountType === 'PERCENTAGE') {
                    if (discount > 100) {
                        MsgBox.alert('Bill discount percentage cannot exceed 100%');
                        $('#billDiscount').val('0');
                        return;
                    }
                    billDiscountAmount = (subTotal * discount) / 100;
                } else if (discountType === 'AMOUNT') {
                    if (discount > subTotal) {
                        MsgBox.alert('Bill discount amount cannot exceed subtotal');
                        $('#billDiscount').val('0');
                        return;
                    }
                    billDiscountAmount = discount;
                }
            }

            // Distribute bill discount to items
            this.distributeBillDiscountToItems(billDiscountAmount);

            // Also add product-level discounts to total
            const productDiscountsTotal = this.calculateProductDiscountsTotal();
            const totalDiscountAmount = billDiscountAmount + productDiscountsTotal;

            $('#billDiscountValue').text('-₹' + totalDiscountAmount.toFixed(2));
            this.updateGrandTotal(totalDiscountAmount);
        },

        updateGrandTotal: function(billDiscountAmount) {
            // Get GST type (inclusive or exclusive)
            const gstType = window.GSTTypeManager ? window.GSTTypeManager.getGSTType() : 'inclusive';
            
            // Calculate base amounts depending on GST type
            let baseSubTotal = 0;
            let totalGSTAmount = 0;
            let displaySubTotal = 0;
            
            if (window.cart && window.cart.length > 0) {
                window.cart.forEach(item => {
                    const taxRate = item.taxRate || item.taxPercent || 0;
                    const taxMultiplier = 1 + (taxRate / 100);
                    
                    // Calculate basic rate (before discount, without tax)
                    let basicRate = item.rate;
                    if (item.basicRate) {
                        // Use stored basic rate from GSTTypeManager
                        basicRate = item.basicRate;
                    } else {
                        // Calculate basic rate based on GST type
                        if (gstType === 'inclusive' && taxRate > 0) {
                            basicRate = item.rate / taxMultiplier;
                        }
                    }
                    
                    // Calculate product discount amount
                    let productDiscountAmount = 0;
                    if (item.discount && item.discount > 0) {
                        const itemBaseAmount = item.rate * item.quantity;
                        if (item.discountType === 'PERCENTAGE') {
                            productDiscountAmount = (itemBaseAmount * item.discount) / 100;
                        } else {
                            productDiscountAmount = parseFloat(item.discount);
                        }
                    }
                    
                    // Calculate basic rate after product discount
                    const discountPerUnit = productDiscountAmount / item.quantity;
                    let basicRateAfterDiscount = basicRate;
                    
                    if (productDiscountAmount > 0) {
                        if (gstType === 'inclusive' && taxRate > 0) {
                            // For inclusive, extract discount's basic portion
                            const discountBasicPortion = discountPerUnit / taxMultiplier;
                            basicRateAfterDiscount = basicRate - discountBasicPortion;
                        } else {
                            // For exclusive, full discount applies to basic rate
                            basicRateAfterDiscount = basicRate - discountPerUnit;
                        }
                    }
                    
                    // Add to subtotal (basic amount after product discount)
                    const basicAmountAfterProductDiscount = basicRateAfterDiscount * item.quantity;
                    baseSubTotal += basicAmountAfterProductDiscount;
                    
                    // Calculate GST on the discounted basic amount
                    if (taxRate > 0) {
                        const gstAmount = (basicAmountAfterProductDiscount * taxRate) / 100;
                        totalGSTAmount += gstAmount;
                    }
                });
                
                // SubTotal = Sum of basic amounts after product discounts only
                // Bill discount is NOT subtracted from SubTotal, it's applied to Grand Total
                displaySubTotal = baseSubTotal;
            } else {
                displaySubTotal = parseFloat($('#subTotal').text().replace('₹', '').replace(/,/g, '')) || 0;
            }
            
            // Get transport amount and calculate its GST
            const transportGSTAmount = parseFloat($('#transportGSTAmount').val()) || 0;
            const transportGSTPercent = parseFloat($('#transportGSTPercent').val()) || 0;
            const transportGSTType = $('#transportGSTTypeValue').val() || 'inclusive';
            
            let transportBasicAmount = 0;
            let transportGSTTax = 0;
            let transportTotalAmount = 0;
            
            if (transportGSTAmount > 0) {
                if (transportGSTType === 'inclusive' && transportGSTPercent > 0) {
                    // Extract basic amount and GST from inclusive price
                    const taxMultiplier = 1 + (transportGSTPercent / 100);
                    transportBasicAmount = transportGSTAmount / taxMultiplier;
                    transportGSTTax = transportBasicAmount * (transportGSTPercent / 100);
                    transportTotalAmount = transportGSTAmount; // Already includes tax
                } else if (transportGSTType === 'exclusive' && transportGSTPercent > 0) {
                    // Add GST to basic amount
                    transportBasicAmount = transportGSTAmount;
                    transportGSTTax = transportBasicAmount * (transportGSTPercent / 100);
                    transportTotalAmount = transportBasicAmount + transportGSTTax;
                } else {
                    // No GST
                    transportBasicAmount = transportGSTAmount;
                    transportGSTTax = 0;
                    transportTotalAmount = transportGSTAmount;
                }
            }
            
            // Add transport basic amount to SubTotal
            displaySubTotal += transportBasicAmount;
            
            // Add transport GST to total GST
            totalGSTAmount += transportGSTTax;
            
            // Update SubTotal display to include transport basic amount
            $('#subTotal').text('₹' + displaySubTotal.toFixed(2));
            
            // Legacy cooli amount (for backward compatibility - only use if NO transport)
            // Don't add both cooli and transport to avoid double-counting
            const cooliAmount = transportGSTAmount > 0 ? 0 : (parseFloat($('#cooliAmount').val()) || 0);
            
            // Calculate final amount
            // Final = SubTotal (basic after product discounts + transport basic) + GST (products + transport) + Cooli - Bill Discount
            let finalAmount = 0;
            if (gstType === 'inclusive') {
                // For inclusive: Final = Basic (products + transport) + GST + Cooli - Bill Discount
                finalAmount = displaySubTotal + totalGSTAmount + cooliAmount - billDiscountAmount;
            } else {
                // For exclusive: Final = Basic (products + transport) + GST + Cooli - Bill Discount
                finalAmount = displaySubTotal + totalGSTAmount + cooliAmount - billDiscountAmount;
            }
            
            // Calculate round off (to nearest rupee)
            const roundedTotal = Math.round(finalAmount);
            const roundOffAmount = roundedTotal - finalAmount;
            
            // Apply round off to final amount
            finalAmount = roundedTotal;
            
            // Display cooli/transport - show the transport total amount
            const displayCooliAmount = transportTotalAmount > 0 ? transportTotalAmount : cooliAmount;
            $('#cooliDisplay').text('₹' + displayCooliAmount.toFixed(2));
            $('#roundOffDisplay').text((roundOffAmount >= 0 ? '+' : '') + '₹' + roundOffAmount.toFixed(2));
            $('#grandTotal').text('₹' + finalAmount.toFixed(2));
            
            // Auto-update payment amounts when bill discount changes (same logic as cart changes)
            const currentCash = parseFloat($('#cashAmount').val()) || 0;
            const currentUPI = parseFloat($('#upiAmount').val()) || 0;
            const currentTotal = currentCash + currentUPI;
            
            // If payments are empty or match the old total, update to new total
            if (currentTotal === 0) {
                // No payment entered yet - set cash to full amount
                $('#cashAmount').val(finalAmount.toFixed(2));
                $('#upiAmount').val('0.00');
                $('#paymentAmount').val(finalAmount.toFixed(2));
            } else {
                // Payment already entered - update to match new total
                // Keep the ratio if both cash and UPI were used
                if (currentCash > 0 && currentUPI === 0) {
                    // Only cash was used - update cash to new total
                    $('#cashAmount').val(finalAmount.toFixed(2));
                    $('#paymentAmount').val(finalAmount.toFixed(2));
                } else if (currentUPI > 0 && currentCash === 0) {
                    // Only UPI was used - update UPI to new total
                    $('#upiAmount').val(finalAmount.toFixed(2));
                    $('#paymentAmount').val(finalAmount.toFixed(2));
                } else if (currentCash > 0 && currentUPI > 0) {
                    // Both were used - maintain the ratio
                    const ratio = currentCash / currentTotal;
                    const newCash = finalAmount * ratio;
                    const newUPI = finalAmount - newCash;
                    $('#cashAmount').val(newCash.toFixed(2));
                    $('#upiAmount').val(newUPI.toFixed(2));
                    $('#paymentAmount').val(finalAmount.toFixed(2));
                }
            }
            
            // Payment amount field removed - payment registration moved to separate modal
        },

        updateOutstanding: function(finalAmount) {
            // Outstanding calculation removed - now handled by payment registration module
            // Customers can register payments against specific invoices via the Payment Registration modal
        },

        getBillDiscountData: function() {
            const discount = parseFloat($('#billDiscount').val()) || 0;
            const discountType = $('#billDiscountType').val();
            const subTotal = parseFloat($('#subTotal').text().replace('₹', '').replace(/,/g, '')) || 0;
            
            let discountAmount = 0;
            if (discount > 0) {
                if (discountType === 'PERCENTAGE') {
                    discountAmount = (subTotal * discount) / 100;
                } else {
                    discountAmount = discount;
                }
            }

            return {
                billDiscount: discount,
                billDiscountType: discountType,
                discountAmount: discountAmount
            };
        },

        resetDiscount: function() {
            $('#billDiscount').val('0');
            $('#billDiscountType').val('PERCENTAGE');
            $('#billDiscPercent').addClass('active');
            $('#billDiscAmount').removeClass('active');
            $('#billDiscountValue').text('-₹0.00');
        }
    };

    // ============================================
    // LOYALTY POINTS MANAGEMENT
    // ============================================
    
    const LoyaltyPointsManager = {
        currentCustomerId: null,
        currentAction: null,
        loyaltySettings: {},

        init: function() {
            $('#btnLoyaltyPoints').on('click', this.openLoyaltyModal.bind(this));
            $('#btnRedeemPoints').on('click', () => this.showTransactionForm('redeem'));
            $('#btnAdjustPoints').on('click', () => this.showTransactionForm('adjust'));
            $('#btnCancelTransaction').on('click', this.hideTransactionForm.bind(this));
            $('#btnConfirmTransaction').on('click', this.confirmTransaction.bind(this));
            $('#transactionPoints').on('input', this.calculateTransactionValue.bind(this));
        },

        openLoyaltyModal: async function() {
            const customerId = $('#customerSelect').val();
            
            if (!customerId) {
                await MsgBox.alert('Please select a customer first');
                return;
            }

            this.currentCustomerId = customerId;
            $('#loyaltyPointsModal').modal('show');
            this.loadLoyaltyData(customerId);
        },

        loadLoyaltyData: function(customerId) {
            $.ajax({
                url: 'api/get-loyalty-points.php',
                method: 'GET',
                data: { customer_id: customerId },
                success: (response) => {
                    if (response.success) {
                        this.displayLoyaltyData(response);
                    } else {
                        MsgBox.alert('Error loading loyalty points: ' + response.message);
                    }
                },
                error: function() {
                    MsgBox.alert('Error connecting to server');
                }
            });
        },

        displayLoyaltyData: function(data) {
            const customer = data.customer;
            const transactions = data.transactions;
            this.loyaltySettings = data.settings;

            // Update customer info
            $('#loyaltyCustomerName').text(customer.name);
            $('#loyaltyCustomerCode').text(customer.code);
            $('#loyaltyCurrentPoints').text(customer.currentPoints);
            $('#loyaltyTotalEarned').text(customer.totalEarned);
            $('#loyaltyTotalRedeemed').text(customer.totalRedeemed);

            // Calculate redemption value
            const redemptionRate = parseFloat(this.loyaltySettings.redemption_rate || 1);
            const redemptionValue = customer.currentPoints * redemptionRate;
            $('#loyaltyRedemptionValue').text('₹' + redemptionValue.toFixed(2));

            // Update button state
            if (customer.currentPoints > 0) {
                $('#btnLoyaltyPoints').addClass('has-points');
            } else {
                $('#btnLoyaltyPoints').removeClass('has-points');
            }

            // Display transactions
            this.displayTransactions(transactions);
        },

        displayTransactions: function(transactions) {
            const tbody = $('#loyaltyTransactionList');
            tbody.empty();

            if (transactions.length === 0) {
                tbody.html('<tr><td colspan="5" class="text-center text-muted">No transactions found</td></tr>');
                return;
            }

            transactions.forEach(function(tx) {
                const typeClass = tx.type === 'EARNED' ? 'badge-success' : 
                                 tx.type === 'REDEEMED' ? 'badge-danger' : 'badge-warning';
                
                const pointsDisplay = tx.type === 'REDEEMED' ? '-' + Math.abs(tx.points) : '+' + tx.points;
                
                const row = `
                    <tr>
                        <td><small>${new Date(tx.date).toLocaleDateString()}</small></td>
                        <td><span class="badge ${typeClass}">${tx.type}</span></td>
                        <td class="text-right font-weight-bold">${pointsDisplay}</td>
                        <td><small>${tx.invoiceNumber || tx.reference || '-'}</small></td>
                        <td class="text-right">${tx.balance}</td>
                    </tr>
                `;
                tbody.append(row);
            });
        },

        showTransactionForm: async function(action) {
            this.currentAction = action;
            const currentPoints = parseFloat($('#loyaltyCurrentPoints').text());
            
            if (action === 'redeem') {
                const minPoints = parseFloat(this.loyaltySettings.min_redemption_points || 100);
                if (currentPoints < minPoints) {
                    await MsgBox.alert(`Minimum ${minPoints} points required for redemption`);
                    return;
                }
                $('#transactionFormTitle').text('Redeem Points');
                $('#transactionPoints').attr('max', currentPoints);
            } else {
                $('#transactionFormTitle').text('Adjust Points (+ or -)');
                $('#transactionPoints').removeAttr('max');
            }

            $('#transactionPoints').val('');
            $('#transactionValue').val('');
            $('#transactionNotes').val('');
            $('#pointsTransactionForm').slideDown();
        },

        hideTransactionForm: function() {
            $('#pointsTransactionForm').slideUp();
            this.currentAction = null;
        },

        calculateTransactionValue: function() {
            const points = parseFloat($('#transactionPoints').val()) || 0;
            const redemptionRate = parseFloat(this.loyaltySettings.redemption_rate || 1);
            const value = Math.abs(points) * redemptionRate;
            $('#transactionValue').val('₹' + value.toFixed(2));
        },

        confirmTransaction: async function() {
            const points = parseFloat($('#transactionPoints').val()) || 0;
            const notes = $('#transactionNotes').val();

            if (points === 0) {
                await MsgBox.alert('Please enter points amount');
                return;
            }

            const confirmed = await MsgBox.confirm(`Are you sure you want to ${this.currentAction} ${Math.abs(points)} points?`);
            if (!confirmed) {
                return;
            }

            $.ajax({
                url: 'api/manage-loyalty-points.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    action: this.currentAction,
                    customer_id: this.currentCustomerId,
                    points: Math.abs(points),
                    notes: notes
                }),
                success: (response) => {
                    if (response.success) {
                        MsgBox.alert(response.message);
                        this.hideTransactionForm();
                        this.loadLoyaltyData(this.currentCustomerId);
                        
                        // Update customer display
                        this.updateCustomerLoyaltyDisplay(response.newBalance);
                    } else {
                        MsgBox.alert('Error: ' + response.message);
                    }
                },
                error: function() {
                    MsgBox.alert('Error connecting to server');
                }
            });
        },

        updateCustomerLoyaltyDisplay: function(points) {
            $('#customerLoyalty').html(`<i class="fas fa-star"></i> ${points}`);
            const selectedOption = $('#customerSelect option:selected');
            selectedOption.attr('data-loyalty', points);
        }
    };

    // ============================================
    // LOYALTY SETTINGS MANAGEMENT
    // ============================================
    
    const LoyaltySettingsManager = {
        init: function() {
            $('#btnLoyaltySettings').on('click', this.openSettingsModal.bind(this));
            $('#btnSaveLoyaltySettings').on('click', this.saveSettings.bind(this));
            
            // Update example when values change
            $('#settingPointsPer100, #settingRedemptionRate').on('input', this.updateExample.bind(this));
        },

        openSettingsModal: function() {
            $('#loyaltySettingsModal').modal('show');
            this.loadSettings();
        },

        loadSettings: function() {
            $.ajax({
                url: 'api/get-loyalty-settings.php',
                method: 'GET',
                success: (response) => {
                    if (response.success) {
                        const settings = response.settings;
                        
                        $('#settingPointsPer100').val(settings.points_per_100?.value || 1);
                        $('#settingRedemptionRate').val(settings.redemption_rate?.value || 1);
                        $('#settingMinRedemption').val(settings.min_redemption_points?.value || 100);
                        $('#settingPointsExpiry').val(settings.points_expiry_days?.value || 365);
                        
                        this.updateExample();
                    } else {
                        MsgBox.alert('Error loading settings: ' + response.message);
                    }
                },
                error: function() {
                    MsgBox.alert('Error connecting to server');
                }
            });
        },

        updateExample: function() {
            const pointsPer100 = parseFloat($('#settingPointsPer100').val()) || 1;
            const redemptionRate = parseFloat($('#settingRedemptionRate').val()) || 1;
            
            // Example: Purchase of ₹1000
            const exampleAmount = 1000;
            const examplePoints = Math.floor(exampleAmount / 100) * pointsPer100;
            const exampleValue = examplePoints * redemptionRate;
            
            $('#examplePoints').text(examplePoints);
            $('#exampleValue').text(exampleValue.toFixed(2));
        },

        saveSettings: async function() {
            const settings = {
                points_per_100: parseFloat($('#settingPointsPer100').val()),
                redemption_rate: parseFloat($('#settingRedemptionRate').val()),
                min_redemption_points: parseInt($('#settingMinRedemption').val()),
                points_expiry_days: parseInt($('#settingPointsExpiry').val())
            };

            // Validate
            if (settings.points_per_100 < 0 || settings.redemption_rate < 0 || 
                settings.min_redemption_points < 0 || settings.points_expiry_days < 0) {
                await MsgBox.alert('Settings cannot be negative');
                return;
            }

            if (!await MsgBox.confirm('Are you sure you want to update loyalty points settings?')) {
                return;
            }

            $.ajax({
                url: 'api/update-loyalty-settings.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(settings),
                success: async (response) => {
                    if (response.success) {
                        await MsgBox.alert('Loyalty settings updated successfully!\n\n' +
                              'New Settings:\n' +
                              '• Points per ₹100: ' + settings.points_per_100 + '\n' +
                              '• Redemption Rate: ₹' + settings.redemption_rate + ' per point\n' +
                              '• Min Redemption: ' + settings.min_redemption_points + ' points\n' +
                              '• Expiry: ' + (settings.points_expiry_days == 0 ? 'Never' : settings.points_expiry_days + ' days'));
                        
                        $('#loyaltySettingsModal').modal('hide');
                        
                        // Update loyalty manager's settings if loaded
                        if (LoyaltyPointsManager.loyaltySettings) {
                            LoyaltyPointsManager.loyaltySettings = {
                                points_per_100: settings.points_per_100.toString(),
                                redemption_rate: settings.redemption_rate.toString(),
                                min_redemption_points: settings.min_redemption_points.toString(),
                                points_expiry_days: settings.points_expiry_days.toString()
                            };
                        }
                    } else {
                        await MsgBox.alert('Error updating settings: ' + response.message);
                    }
                },
                error: async function() {
                    await MsgBox.alert('Error connecting to server');
                }
            });
        }
    };

    // ============================================
    // POINTS REDEMPTION FOR DISCOUNT
    // ============================================

    const PointsRedemptionManager = {
        currentCustomerId: null,
        availablePoints: 0,
        redemptionRate: 1,
        minRedemption: 100,

        init: function() {
            // Star button click
            $('#billDiscPoints').on('click', this.openRedemptionModal.bind(this));
            
            // Settings button in redemption modal
            $('#btnRedeemSettings').on('click', () => {
                $('#pointsRedemptionModal').modal('hide');
                LoyaltySettingsManager.openSettingsModal();
            });

            // Points input change
            $('#redeemPointsInput').on('input', this.calculateDiscount.bind(this));

            // Apply button
            $('#btnApplyPointsDiscount').on('click', this.applyPointsDiscount.bind(this));

            console.log('Points Redemption Manager initialized');
        },

        openRedemptionModal: async function() {
            const customerId = $('#customerSelect').val();
            
            if (!customerId) {
                await MsgBox.alert('Please select a customer first!');
                return;
            }

            this.currentCustomerId = customerId;
            const customerName = $('#customerSelect option:selected').text();
            
            // Reset form
            $('#redeemPointsInput').val(0);
            $('#redeemCustomerName').text(customerName);
            $('#redeemWarning').hide();
            $('#btnApplyPointsDiscount').prop('disabled', true);

            // Load customer points and settings
            this.loadCustomerPoints(customerId);
            this.loadSettings();

            $('#pointsRedemptionModal').modal('show');
        },

        loadCustomerPoints: function(customerId) {
            $.ajax({
                url: 'api/get-loyalty-points.php',
                method: 'GET',
                data: { customer_id: customerId },
                success: (response) => {
                    if (response.success) {
                        this.availablePoints = response.customer.currentPoints;
                        $('#redeemAvailablePoints').text(this.availablePoints.toFixed(0));
                        $('#redeemPointsRemaining').text(this.availablePoints.toFixed(0));
                        
                        // Set max attribute
                        $('#redeemPointsInput').attr('max', this.availablePoints);
                    } else {
                        MsgBox.alert('Error loading customer points: ' + response.message);
                    }
                },
                error: function() {
                    MsgBox.alert('Error connecting to server');
                }
            });
        },

        loadSettings: function() {
            $.ajax({
                url: 'api/get-loyalty-settings.php',
                method: 'GET',
                success: (response) => {
                    if (response.success && response.settings) {
                        this.redemptionRate = parseFloat(response.settings.redemption_rate || 1);
                        this.minRedemption = parseInt(response.settings.min_redemption_points || 100);
                        
                        $('#redeemPointValue').text(this.redemptionRate);
                        $('#redeemMinPoints').text(this.minRedemption);
                    }
                },
                error: function() {
                    console.error('Error loading loyalty settings');
                }
            });
        },

        calculateDiscount: function() {
            const pointsToRedeem = parseFloat($('#redeemPointsInput').val()) || 0;
            
            // Validate
            $('#redeemWarning').hide();
            $('#btnApplyPointsDiscount').prop('disabled', false);

            if (pointsToRedeem <= 0) {
                $('#redeemDiscountAmount').text('0.00');
                $('#redeemPointsUsed').text('0');
                $('#redeemPointsRemaining').text(this.availablePoints.toFixed(0));
                $('#btnApplyPointsDiscount').prop('disabled', true);
                return;
            }

            if (pointsToRedeem > this.availablePoints) {
                $('#redeemWarning').show();
                $('#redeemWarningText').text('Points exceed available balance!');
                $('#btnApplyPointsDiscount').prop('disabled', true);
                return;
            }

            if (pointsToRedeem < this.minRedemption) {
                $('#redeemWarning').show();
                $('#redeemWarningText').text(`Minimum ${this.minRedemption} points required for redemption`);
                $('#btnApplyPointsDiscount').prop('disabled', true);
                return;
            }

            // Calculate discount amount
            const discountAmount = pointsToRedeem * this.redemptionRate;
            const remainingPoints = this.availablePoints - pointsToRedeem;

            // Update display
            $('#redeemDiscountAmount').text(discountAmount.toFixed(2));
            $('#redeemPointsUsed').text(pointsToRedeem.toFixed(0));
            $('#redeemPointsRemaining').text(remainingPoints.toFixed(0));
        },

        applyPointsDiscount: async function() {
            const pointsToRedeem = parseFloat($('#redeemPointsInput').val()) || 0;
            const discountAmount = pointsToRedeem * this.redemptionRate;

            if (pointsToRedeem <= 0 || pointsToRedeem > this.availablePoints || pointsToRedeem < this.minRedemption) {
                await MsgBox.alert('Invalid points amount!');
                return;
            }

            if (!await MsgBox.confirm(`Apply ${pointsToRedeem} points as ₹${discountAmount.toFixed(2)} discount?\n\nThis will be deducted from customer's loyalty points balance.`)) {
                return;
            }

            // Set discount type to POINTS
            $('#billDiscountType').val('POINTS');
            $('#redeemedPoints').val(pointsToRedeem);
            
            // Set discount amount
            $('#billDiscount').val(discountAmount);
            
            // Highlight the star button
            $('#billDiscPercent').removeClass('active btn-primary').addClass('btn-outline-secondary');
            $('#billDiscAmount').removeClass('active btn-primary').addClass('btn-outline-secondary');
            $('#billDiscPoints').removeClass('btn-outline-warning').addClass('active btn-warning text-white');
            
            // Trigger discount calculation
            BillDiscountManager.calculateBillDiscount();

            // Show success and close modal
            $('#pointsRedemptionModal').modal('hide');
            
            await MsgBox.alert(`✅ Points Discount Applied!\n\n` +
                  `Points Used: ${pointsToRedeem}\n` +
                  `Discount: ₹${discountAmount.toFixed(2)}\n\n` +
                  `Points will be deducted when invoice is saved.`);
        }
    };

    // ============================================
    // INTEGRATION WITH MAIN SALES.JS
    // ============================================

    // Extend cart item to include discount data
    window.SalesEnhancements = {
        ProductDiscountManager: ProductDiscountManager,
        BillDiscountManager: BillDiscountManager,
        LoyaltyPointsManager: LoyaltyPointsManager,
        LoyaltySettingsManager: LoyaltySettingsManager,
        SalesTypeManager: SalesTypeManager,
        PointsRedemptionManager: PointsRedemptionManager
    };

    // Initialize all managers when document is ready
    $(document).ready(function() {
        SalesTypeManager.init();
        ProductDiscountManager.init();
        BillDiscountManager.init();
        LoyaltyPointsManager.init();
        LoyaltySettingsManager.init();
        PointsRedemptionManager.init();
        
        console.log('Sales Enhancements initialized');
    });

    // Update customer selection to show loyalty points
    $(document).on('change', '#customerSelect', function() {
        const loyaltyPoints = $(this).find('option:selected').data('loyalty') || 0;
        $('#customerLoyalty').html(`<i class="fas fa-star"></i> ${loyaltyPoints}`);
        
        // Enable/disable loyalty button
        if ($(this).val()) {
            $('#btnLoyaltyPoints').prop('disabled', false);
        } else {
            $('#btnLoyaltyPoints').prop('disabled', true);
        }
    });

    // Update cooliAmount changes to recalculate
    $(document).on('input', '#cooliAmount', function() {
        BillDiscountManager.calculateBillDiscount();
    });
    
    // Update transportGSTAmount changes to recalculate
    $(document).on('input', '#transportGSTAmount', function() {
        BillDiscountManager.calculateBillDiscount();
    });
    
    // Update transportGSTPercent changes to recalculate
    $(document).on('input', '#transportGSTPercent', function() {
        BillDiscountManager.calculateBillDiscount();
    });

    // Payment amount field removed - no longer tracking outstanding in sales page
    // Use Payment Registration modal to register payments against invoices

    // Listen for GST type changes and recalculate bill discount
    $(document).on('click', '#btnGSTInclusive, #btnGSTExclusive', function() {
        // Give a small delay to let GSTTypeManager update first
        setTimeout(function() {
            if (window.cart && window.cart.length > 0) {
                // Recalculate bill discount with new GST type
                BillDiscountManager.calculateBillDiscount();
            }
        }, 100);
    });

})();
