/**
 * GST Details Modal and Functionality
 * Handles GST calculations and display for sales
 */

// Global variable to store current sale's GST data
let currentGSTData = null;

/**
 * Initialize GST Details functionality
 */
function initGSTDetails() {
    // Add click handler for GST Details button
    $(document).on('click', '#btnGSTDetails', function() {
        showGSTDetailsModal();
    });
    
    // Print GST Details
    $(document).on('click', '#btnPrintGST', function() {
        printGSTDetails();
    });
    
    // Export GST Details to Excel
    $(document).on('click', '#btnExportGST', function() {
        exportGSTToExcel();
    });
}

/**
 * Show GST Details Modal
 */
function showGSTDetailsModal() {
    // Check if we have cart items (running invoice)
    if (typeof cart !== 'undefined' && cart.length > 0) {
        // Show GST details from current cart immediately
        $('#gstDetailsModal').modal('show');
        showGSTDetailsFromCart();
        return;
    }
    
    // Otherwise, try to fetch from saved sale
    const invoiceNumber = $('#currentInvoiceNumber').text().trim();
    const editingSaleId = $('#editingSaleId').val();
    
    if (!invoiceNumber && !editingSaleId) {
        alert('Please add products to view GST details');
        return;
    }
    
    // Show loading modal
    $('#gstDetailsModal').modal('show');
    $('#gstDetailsContent').html(`
        <div class="text-center py-5">
            <i class="fas fa-spinner fa-spin fa-3x text-primary"></i>
            <p class="mt-3">Loading GST Details...</p>
        </div>
    `);
    
    // Fetch GST details
    fetchGSTDetails(editingSaleId, invoiceNumber);
}

/**
 * Show GST Details from Current Cart (Running Invoice)
 */
function showGSTDetailsFromCart() {
    // Get customer GST info
    const customerId = $('#customerSelect').val();
    const customerGST = customerId ? $('#customerSelect option:selected').data('gst') : '';
    const customerName = customerId ? $('#customerSelect option:selected').data('name') : 'Walk-in Customer';
    
    // Determine tax type
    let taxType = 'INTRA'; // Default CGST+SGST for Tamil Nadu
    if (customerGST && customerGST.length >= 2) {
        const stateCode = customerGST.substring(0, 2);
        if (stateCode !== '33') {
            taxType = 'INTER'; // IGST for other states
        }
    }
    
    // Render directly from cart data (no database call needed)
    renderGSTDetailsFromCart(taxType, customerName, customerGST);
}

/**
 * Render GST Details from Cart with HSN-wise Grouping
 */
function renderGSTDetailsFromCart(taxType, customerName, customerGST) {
    const invoiceNumber = $('#currentInvoiceNumber').text().trim();
    const currentDate = new Date().toLocaleDateString('en-GB');
    
    // Calculate GST for each cart item and group by HSN
    const hsnGroups = {};
    let totalTaxableAmount = 0;
    let totalCGST = 0;
    let totalSGST = 0;
    let totalIGST = 0;
    let totalTaxAmount = 0;
    let grandTotal = 0;
    
    cart.forEach(item => {
        // Get HSN and tax rate from cart item (should be already loaded with product)
        const hsn = item.hsn || item.hsnCode || '-';
        const taxRate = parseFloat(item.taxRate || item.taxPercentage || 0);
        
        // Get GST type from GSTTypeManager
        const gstType = window.GSTTypeManager ? window.GSTTypeManager.getGSTType() : 'inclusive';
        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 total discount amount
        let discountAmount = 0;
        if (item.discount && item.discount > 0) {
            const itemBaseAmount = item.rate * item.quantity;
            if (item.discountType === 'PERCENTAGE') {
                discountAmount = (itemBaseAmount * item.discount) / 100;
            } else {
                discountAmount = parseFloat(item.discount);
            }
        }
        
        // Add bill discount portion if exists
        if (item.billDiscountPortion) {
            discountAmount += parseFloat(item.billDiscountPortion);
        }
        
        // Calculate basic rate after discount (actual basic rate)
        const discountPerUnit = discountAmount / item.quantity;
        let basicRateAfterDiscount = basicRate;
        
        if (discountAmount > 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;
            }
        }
        
        // Calculate taxable amount using actual basic rate after discount
        const taxableAmount = basicRateAfterDiscount * item.quantity;
        
        // Calculate tax
        let cgstAmount = 0, sgstAmount = 0, igstAmount = 0;
        if (taxType === 'INTRA') {
            cgstAmount = (taxableAmount * taxRate) / 200; // Half of tax rate
            sgstAmount = (taxableAmount * taxRate) / 200; // Half of tax rate
        } else {
            igstAmount = (taxableAmount * taxRate) / 100;
        }
        
        const itemTaxAmount = cgstAmount + sgstAmount + igstAmount;
        const itemTotal = taxableAmount + itemTaxAmount;
        
        // Group by HSN and Tax Rate
        const key = `${hsn}_${taxRate}`;
        if (!hsnGroups[key]) {
            hsnGroups[key] = {
                hsn: hsn,
                taxRate: taxRate,
                taxableAmount: 0,
                cgstAmount: 0,
                sgstAmount: 0,
                igstAmount: 0,
                totalTax: 0,
                totalAmount: 0,
                items: []
            };
        }
        
        hsnGroups[key].taxableAmount += taxableAmount;
        hsnGroups[key].cgstAmount += cgstAmount;
        hsnGroups[key].sgstAmount += sgstAmount;
        hsnGroups[key].igstAmount += igstAmount;
        hsnGroups[key].totalTax += itemTaxAmount;
        hsnGroups[key].totalAmount += itemTotal;
        hsnGroups[key].items.push({
            code: item.productCode,
            name: item.productName,
            rate: item.rate,
            qty: item.quantity,
            discount: discountAmount,
            taxableAmount: taxableAmount,
            cgst: cgstAmount,
            sgst: sgstAmount,
            igst: igstAmount,
            total: itemTotal
        });
        
        // Add to totals
        totalTaxableAmount += taxableAmount;
        totalCGST += cgstAmount;
        totalSGST += sgstAmount;
        totalIGST += igstAmount;
        totalTaxAmount += itemTaxAmount;
        grandTotal += itemTotal;
    });
    
    // Render compact HSN-wise view
    let html = `
        <!-- Invoice Info - Compact -->
        <div class="card mb-2 shadow-sm">
            <div class="card-body p-2" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <div class="row text-white align-items-center">
                    <div class="col-md-6">
                        <small class="d-block opacity-75">Invoice No:</small>
                        <strong class="h6 mb-0">${invoiceNumber}</strong>
                    </div>
                    <div class="col-md-6 text-right">
                        <small class="d-block opacity-75">Date:</small>
                        <strong>${currentDate}</strong>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- HSN-wise Summary - Very Compact -->
        <div class="card mb-2 shadow-sm">
            <div class="card-header bg-gradient-success text-white py-2">
                <h6 class="mb-0"><i class="fas fa-list-alt"></i> HSN-wise GST Summary</h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height: 350px;">
                    <table class="table table-sm table-hover mb-0" style="font-size: 0.85rem;">
                        <thead class="thead-light sticky-top">
                            <tr>
                                <th width="12%">HSN</th>
                                <th width="8%" class="text-center">Tax%</th>
                                <th width="15%" class="text-right">Taxable Amt</th>
    `;
    
    if (taxType === 'INTRA') {
        html += `
                                <th width="13%" class="text-right">CGST</th>
                                <th width="13%" class="text-right">SGST</th>
        `;
    } else {
        html += `
                                <th width="13%" class="text-right">IGST</th>
        `;
    }
    
    html += `
                                <th width="15%" class="text-right">Total Tax</th>
                                <th width="15%" class="text-right">Total Amt</th>
                            </tr>
                        </thead>
                        <tbody>
    `;
    
    // Add HSN-wise rows
    Object.keys(hsnGroups).forEach((key, index) => {
        const group = hsnGroups[key];
        const bgClass = index % 2 === 0 ? '' : 'bg-light';
        
        html += `
            <tr class="${bgClass}">
                <td><strong class="text-primary">${group.hsn}</strong></td>
                <td class="text-center"><span class="badge badge-info">${group.taxRate.toFixed(1)}%</span></td>
                <td class="text-right font-weight-bold">₹${group.taxableAmount.toFixed(2)}</td>
        `;
        
        if (taxType === 'INTRA') {
            html += `
                <td class="text-right text-primary">₹${group.cgstAmount.toFixed(2)}<br><small class="text-muted">${(group.taxRate/2).toFixed(1)}%</small></td>
                <td class="text-right text-primary">₹${group.sgstAmount.toFixed(2)}<br><small class="text-muted">${(group.taxRate/2).toFixed(1)}%</small></td>
            `;
        } else {
            html += `
                <td class="text-right text-warning" colspan="2">₹${group.igstAmount.toFixed(2)}<br><small class="text-muted">${group.taxRate.toFixed(1)}%</small></td>
            `;
        }
        
        html += `
                <td class="text-right font-weight-bold text-danger">₹${group.totalTax.toFixed(2)}</td>
                <td class="text-right font-weight-bold text-success">₹${group.totalAmount.toFixed(2)}</td>
            </tr>
        `;
    });
    
    // Add transport row if transport amount exists
    const transportGSTAmount = parseFloat($('#transportGSTAmount').val()) || 0;
    const transportGSTPercent = parseFloat($('#transportGSTPercent').val()) || 0;
    const transportGSTType = $('#transportGSTTypeValue').val() || 'inclusive';
    
    let transportBasicAmount = 0;
    let transportCGST = 0;
    let transportSGST = 0;
    let transportIGST = 0;
    let transportTotalTax = 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;
            
            if (taxType === 'INTRA') {
                transportCGST = (transportBasicAmount * transportGSTPercent) / 200;
                transportSGST = (transportBasicAmount * transportGSTPercent) / 200;
            } else {
                transportIGST = (transportBasicAmount * transportGSTPercent) / 100;
            }
            transportTotalTax = transportCGST + transportSGST + transportIGST;
            transportTotalAmount = transportGSTAmount; // Already includes tax
        } else if (transportGSTType === 'exclusive' && transportGSTPercent > 0) {
            // Add GST to basic amount
            transportBasicAmount = transportGSTAmount;
            
            if (taxType === 'INTRA') {
                transportCGST = (transportBasicAmount * transportGSTPercent) / 200;
                transportSGST = (transportBasicAmount * transportGSTPercent) / 200;
            } else {
                transportIGST = (transportBasicAmount * transportGSTPercent) / 100;
            }
            transportTotalTax = transportCGST + transportSGST + transportIGST;
            transportTotalAmount = transportBasicAmount + transportTotalTax;
        } else {
            // No GST
            transportBasicAmount = transportGSTAmount;
            transportTotalTax = 0;
            transportTotalAmount = transportGSTAmount;
        }
        
        // Add transport row
        html += `
            <tr class="bg-warning bg-opacity-25">
                <td><strong class="text-info"><i class="fas fa-truck"></i> TRANSPORT</strong></td>
                <td class="text-center"><span class="badge badge-secondary">${transportGSTPercent.toFixed(1)}%</span></td>
                <td class="text-right font-weight-bold">₹${transportBasicAmount.toFixed(2)}</td>
        `;
        
        if (taxType === 'INTRA') {
            html += `
                <td class="text-right text-primary">₹${transportCGST.toFixed(2)}<br><small class="text-muted">${(transportGSTPercent/2).toFixed(1)}%</small></td>
                <td class="text-right text-primary">₹${transportSGST.toFixed(2)}<br><small class="text-muted">${(transportGSTPercent/2).toFixed(1)}%</small></td>
            `;
        } else {
            html += `
                <td class="text-right text-warning" colspan="2">₹${transportIGST.toFixed(2)}<br><small class="text-muted">${transportGSTPercent.toFixed(1)}%</small></td>
            `;
        }
        
        html += `
                <td class="text-right font-weight-bold text-danger">₹${transportTotalTax.toFixed(2)}</td>
                <td class="text-right font-weight-bold text-success">₹${transportTotalAmount.toFixed(2)}</td>
            </tr>
        `;
        
        // Add transport amounts to totals
        totalTaxableAmount += transportBasicAmount;
        totalCGST += transportCGST;
        totalSGST += transportSGST;
        totalIGST += transportIGST;
        totalTaxAmount += transportTotalTax;
        grandTotal += transportTotalAmount;
    }
    
    // Totals row
    html += `
                        </tbody>
                        <tfoot class="bg-dark text-white">
                            <tr>
                                <th colspan="2" class="text-right">TOTAL:</th>
                                <th class="text-right">₹${totalTaxableAmount.toFixed(2)}</th>
    `;
    
    if (taxType === 'INTRA') {
        html += `
                                <th class="text-right">₹${totalCGST.toFixed(2)}</th>
                                <th class="text-right">₹${totalSGST.toFixed(2)}</th>
        `;
    } else {
        html += `
                                <th class="text-right" colspan="2">₹${totalIGST.toFixed(2)}</th>
        `;
    }
    
    html += `
                                <th class="text-right">₹${totalTaxAmount.toFixed(2)}</th>
                                <th class="text-right">₹${grandTotal.toFixed(2)}</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Tax Summary - Compact -->
        <div class="card border-info shadow-sm">
            <div class="card-body p-2">
                <div class="row align-items-center">
                    <div class="col-6">
                        <div class="d-flex justify-content-between mb-1">
                            <small class="text-muted">Taxable Amount:</small>
                            <strong>₹${totalTaxableAmount.toFixed(2)}</strong>
                        </div>
    `;
    
    if (taxType === 'INTRA') {
        html += `
                        <div class="d-flex justify-content-between mb-1">
                            <small class="text-muted">Total CGST:</small>
                            <strong class="text-primary">₹${totalCGST.toFixed(2)}</strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <small class="text-muted">Total SGST:</small>
                            <strong class="text-primary">₹${totalSGST.toFixed(2)}</strong>
                        </div>
        `;
    } else {
        html += `
                        <div class="d-flex justify-content-between">
                            <small class="text-muted">Total IGST:</small>
                            <strong class="text-warning">₹${totalIGST.toFixed(2)}</strong>
                        </div>
        `;
    }
    
    html += `
                    </div>
                    <div class="col-6 border-left">
                        <div class="text-center">
                            <small class="text-muted d-block">Tax Type:</small>
                            <span class="badge badge-${taxType === 'INTRA' ? 'success' : 'warning'} mb-2">
                                ${taxType === 'INTRA' ? 'Intra-State (CGST+SGST)' : 'Inter-State (IGST)'}
                            </span>
                            <hr class="my-2">
                            <small class="text-muted d-block">Grand Total</small>
                            <h4 class="mb-0 text-success">₹${grandTotal.toFixed(2)}</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#gstDetailsContent').html(html);
}

/**
 * Fetch GST Details from server
 */
function fetchGSTDetails(saleId, invoiceNumber) {
    let url = 'api/get-gst-details.php?';
    
    if (saleId) {
        url += `sale_id=${saleId}`;
    } else {
        url += `invoice_number=${encodeURIComponent(invoiceNumber)}`;
    }
    
    $.ajax({
        url: url,
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                currentGSTData = response;
                renderGSTDetails(response);
            } else {
                $('#gstDetailsContent').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i> ${response.message}
                    </div>
                `);
            }
        },
        error: function(xhr, status, error) {
            $('#gstDetailsContent').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Error loading GST details: ${error}
                </div>
            `);
        }
    });
}

/**
 * Render GST Details in Modal
 */
function renderGSTDetails(data) {
    const saleInfo = data.saleInfo;
    const gstDetails = data.gstDetails;
    const totals = data.totals;
    const taxType = saleInfo.TaxType;
    
    let html = `
        <!-- Sale Information -->
        <div class="card mb-3">
            <div class="card-header bg-primary text-white py-2">
                <h6 class="mb-0"><i class="fas fa-file-invoice"></i> Invoice Information</h6>
            </div>
            <div class="card-body p-3">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless mb-0">
                            <tr>
                                <td class="text-muted" width="40%">Invoice No:</td>
                                <td><strong>${saleInfo.InvoiceNumber}</strong></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Date:</td>
                                <td><strong>${saleInfo.SaleDate}</strong></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Customer:</td>
                                <td><strong>${saleInfo.CustomerName}</strong></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless mb-0">
                            <tr>
                                <td class="text-muted" width="40%">Customer Code:</td>
                                <td><strong>${saleInfo.CustomerCode}</strong></td>
                            </tr>
                            <tr>
                                <td class="text-muted">GST Number:</td>
                                <td><strong>${saleInfo.GSTNumber}</strong></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Tax Type:</td>
                                <td>
                                    <span class="badge ${taxType === 'INTRA' ? 'badge-success' : 'badge-warning'}">
                                        ${saleInfo.TaxTypeLabel}
                                    </span>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- GST Breakdown Table -->
        <div class="card mb-3">
            <div class="card-header bg-success text-white py-2">
                <h6 class="mb-0"><i class="fas fa-list"></i> GST Breakdown by Product</h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-hover mb-0" id="gstDetailsTable">
                        <thead class="thead-light sticky-top">
                            <tr>
                                <th width="3%">#</th>
                                <th width="10%">Code</th>
                                <th width="22%">Product Name</th>
                                <th width="8%" class="text-right">Rate</th>
                                <th width="6%" class="text-right">Qty</th>
                                <th width="8%" class="text-right">Disc</th>
                                <th width="10%" class="text-right">Taxable Amt</th>
                                <th width="5%" class="text-center">Tax%</th>
    `;
    
    if (taxType === 'INTRA') {
        html += `
                                <th width="9%" class="text-right">CGST</th>
                                <th width="9%" class="text-right">SGST</th>
        `;
    } else {
        html += `
                                <th width="9%" class="text-right">IGST</th>
        `;
    }
    
    html += `
                                <th width="10%" class="text-right">Total</th>
                            </tr>
                        </thead>
                        <tbody>
    `;
    
    // Add product rows
    gstDetails.forEach((item, index) => {
        html += `
            <tr>
                <td>${index + 1}</td>
                <td><small class="font-weight-bold">${item.ProductCode}</small></td>
                <td><small>${item.ProductName}</small></td>
                <td class="text-right"><small>₹${item.Rate}</small></td>
                <td class="text-right"><small>${item.Quantity}</small></td>
                <td class="text-right"><small class="text-danger">₹${item.DiscountAmount}</small></td>
                <td class="text-right"><small class="font-weight-bold">₹${item.TaxableAmount}</small></td>
                <td class="text-center"><small><span class="badge badge-info">${item.TaxPercentage}%</span></small></td>
        `;
        
        if (taxType === 'INTRA') {
            html += `
                <td class="text-right"><small class="text-primary">₹${item.CGSTAmount}<br><span class="text-muted">(${item.CGSTPercent}%)</span></small></td>
                <td class="text-right"><small class="text-primary">₹${item.SGSTAmount}<br><span class="text-muted">(${item.SGSTPercent}%)</span></small></td>
            `;
        } else {
            html += `
                <td class="text-right"><small class="text-warning">₹${item.IGSTAmount}<br><span class="text-muted">(${item.IGSTPercent}%)</span></small></td>
            `;
        }
        
        html += `
                <td class="text-right"><small class="font-weight-bold text-success">₹${item.FinalAmount}</small></td>
            </tr>
        `;
    });
    
    html += `
                        </tbody>
                        <tfoot class="thead-dark">
                            <tr>
                                <th colspan="6" class="text-right">TOTAL:</th>
                                <th class="text-right">₹${totals.TotalTaxableAmount}</th>
                                <th></th>
    `;
    
    if (taxType === 'INTRA') {
        html += `
                                <th class="text-right">₹${totals.TotalCGST}</th>
                                <th class="text-right">₹${totals.TotalSGST}</th>
        `;
    } else {
        html += `
                                <th class="text-right">₹${totals.TotalIGST}</th>
        `;
    }
    
    html += `
                                <th class="text-right">₹${totals.TotalFinalAmount}</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Tax Summary -->
        <div class="card border-info">
            <div class="card-header bg-info text-white py-2">
                <h6 class="mb-0"><i class="fas fa-calculator"></i> Tax Summary</h6>
            </div>
            <div class="card-body p-3">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless mb-0">
                            <tr>
                                <td class="text-muted">Taxable Amount:</td>
                                <td class="text-right"><h6 class="mb-0">₹${totals.TotalTaxableAmount}</h6></td>
                            </tr>
    `;
    
    if (taxType === 'INTRA') {
        html += `
                            <tr>
                                <td class="text-muted">Total CGST:</td>
                                <td class="text-right"><h6 class="mb-0 text-primary">₹${totals.TotalCGST}</h6></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Total SGST:</td>
                                <td class="text-right"><h6 class="mb-0 text-primary">₹${totals.TotalSGST}</h6></td>
                            </tr>
        `;
    } else {
        html += `
                            <tr>
                                <td class="text-muted">Total IGST:</td>
                                <td class="text-right"><h6 class="mb-0 text-warning">₹${totals.TotalIGST}</h6></td>
                            </tr>
        `;
    }
    
    html += `
                        </table>
                    </div>
                    <div class="col-md-6 border-left">
                        <table class="table table-sm table-borderless mb-0">
                            <tr>
                                <td class="text-muted">Total Tax Amount:</td>
                                <td class="text-right"><h6 class="mb-0 text-danger">₹${totals.TotalTaxAmount}</h6></td>
                            </tr>
                            <tr>
                                <td class="text-muted"><strong>Grand Total:</strong></td>
                                <td class="text-right"><h4 class="mb-0 text-success">₹${totals.TotalFinalAmount}</h4></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#gstDetailsContent').html(html);
}

/**
 * Save GST Details to Database
 */
function saveGSTDetails(saleId, invoiceNumber, cartItems, customerGST) {
    console.log('=== saveGSTDetails called ===');
    console.log('SaleID:', saleId);
    console.log('InvoiceNumber:', invoiceNumber);
    console.log('Cart Items:', cartItems);
    console.log('Customer GST:', customerGST);
    
    // Log each cart item's discount properties for debugging
    cartItems.forEach((item, index) => {
        console.log(`Cart Item ${index}:`, {
            name: item.productName,
            rate: item.rate,
            quantity: item.quantity,
            discount: item.discount,
            discountType: item.discountType,
            billDiscountPortion: item.billDiscountPortion
        });
    });
    
    // Determine tax type
    let taxType = 'INTRA'; // Default CGST+SGST for Tamil Nadu
    if (customerGST && customerGST.length >= 2) {
        const stateCode = customerGST.substring(0, 2);
        if (stateCode !== '33') {
            taxType = 'INTER'; // IGST for other states
        }
    }
    
    // Prepare GST items - fetch tax info from each cart item
    const gstItems = cartItems.map(item => {
        console.log('Processing item:', item);
        
        // Get GST type from GSTTypeManager
        const gstType = window.GSTTypeManager ? window.GSTTypeManager.getGSTType() : 'inclusive';
        const taxPercentage = parseFloat(item.taxRate || item.taxPercentage || 0);
        const taxMultiplier = 1 + (taxPercentage / 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' && taxPercentage > 0) {
                basicRate = item.rate / taxMultiplier;
            } else if (gstType === 'exclusive') {
                basicRate = item.rate / taxMultiplier;
            }
        }
        
        // Calculate total discount amount
        let discountAmount = 0;
        if (item.discount && item.discount > 0) {
            const itemBaseAmount = item.rate * item.quantity;
            if (item.discountType === 'PERCENTAGE') {
                discountAmount = (itemBaseAmount * item.discount) / 100;
            } else {
                discountAmount = parseFloat(item.discount);
            }
        }
        
        // Add bill discount portion if exists
        if (item.billDiscountPortion) {
            discountAmount += parseFloat(item.billDiscountPortion);
        }
        
        // Calculate basic rate after discount (actual basic rate)
        const discountPerUnit = discountAmount / item.quantity;
        let basicRateAfterDiscount = basicRate;
        
        if (discountAmount > 0) {
            if (gstType === 'inclusive' && taxPercentage > 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;
            }
        }
        
        // Calculate taxable amount using actual basic rate after discount
        const taxableAmount = basicRateAfterDiscount * item.quantity;
        
        console.log('  - Product:', item.productName);
        console.log('  - Basic Rate (before discount):', basicRate.toFixed(2));
        console.log('  - Discount per unit:', discountPerUnit.toFixed(2));
        console.log('  - Basic Rate (after discount):', basicRateAfterDiscount.toFixed(2));
        console.log('  - Taxable Amount:', taxableAmount.toFixed(2));
        console.log('  - GST Type:', gstType);
        console.log('  - Tax Percentage:', taxPercentage);
        
        let cgstPercent = 0, sgstPercent = 0, igstPercent = 0;
        let cgstAmount = 0, sgstAmount = 0, igstAmount = 0;
        
        if (taxPercentage > 0) {
            if (taxType === 'INTRA') {
                cgstPercent = taxPercentage / 2;
                sgstPercent = taxPercentage / 2;
                cgstAmount = (taxableAmount * cgstPercent) / 100;
                sgstAmount = (taxableAmount * sgstPercent) / 100;
            } else {
                igstPercent = taxPercentage;
                igstAmount = (taxableAmount * igstPercent) / 100;
            }
        }
        
        const totalTaxAmount = cgstAmount + sgstAmount + igstAmount;
        const finalAmount = taxableAmount + totalTaxAmount;
        
        return {
            productId: item.productId,
            productCode: item.productCode,
            productName: item.productName,
            hsnCode: item.hsnCode || '',
            rate: item.rate,
            quantity: item.quantity,
            discountAmount: discountAmount,
            taxableAmount: taxableAmount,
            taxPercentage: taxPercentage,
            cgstPercent: cgstPercent,
            cgstAmount: cgstAmount,
            sgstPercent: sgstPercent,
            sgstAmount: sgstAmount,
            igstPercent: igstPercent,
            igstAmount: igstAmount,
            totalTaxAmount: totalTaxAmount,
            finalAmount: finalAmount
        };
    });
    
    // Add transport amount as a separate GST item if it exists (NOT affected by discounts)
    const transportGSTAmount = parseFloat($('#transportGSTAmount').val()) || 0;
    const transportGSTPercent = parseFloat($('#transportGSTPercent').val()) || 0;
    const transportGSTType = $('#transportGSTTypeValue').val() || 'inclusive';
    const transportName = $('#transportNameValue').val() || 'Transport';
    
    if (transportGSTAmount > 0) {
        let transportBasicAmount = 0;
        let transportCGSTPercent = 0;
        let transportSGSTPercent = 0;
        let transportIGSTPercent = 0;
        let transportCGSTAmount = 0;
        let transportSGSTAmount = 0;
        let transportIGSTAmount = 0;
        let transportTotalTax = 0;
        let transportFinalAmount = 0;
        
        if (transportGSTType === 'inclusive' && transportGSTPercent > 0) {
            // Extract basic amount and GST from inclusive price
            const taxMultiplier = 1 + (transportGSTPercent / 100);
            transportBasicAmount = transportGSTAmount / taxMultiplier;
            
            if (taxType === 'INTRA') {
                transportCGSTPercent = transportGSTPercent / 2;
                transportSGSTPercent = transportGSTPercent / 2;
                transportCGSTAmount = (transportBasicAmount * transportCGSTPercent) / 100;
                transportSGSTAmount = (transportBasicAmount * transportSGSTPercent) / 100;
            } else {
                transportIGSTPercent = transportGSTPercent;
                transportIGSTAmount = (transportBasicAmount * transportIGSTPercent) / 100;
            }
            transportTotalTax = transportCGSTAmount + transportSGSTAmount + transportIGSTAmount;
            transportFinalAmount = transportGSTAmount; // Already includes tax
        } else if (transportGSTType === 'exclusive' && transportGSTPercent > 0) {
            // Add GST to basic amount
            transportBasicAmount = transportGSTAmount;
            
            if (taxType === 'INTRA') {
                transportCGSTPercent = transportGSTPercent / 2;
                transportSGSTPercent = transportGSTPercent / 2;
                transportCGSTAmount = (transportBasicAmount * transportCGSTPercent) / 100;
                transportSGSTAmount = (transportBasicAmount * transportSGSTPercent) / 100;
            } else {
                transportIGSTPercent = transportGSTPercent;
                transportIGSTAmount = (transportBasicAmount * transportIGSTPercent) / 100;
            }
            transportTotalTax = transportCGSTAmount + transportSGSTAmount + transportIGSTAmount;
            transportFinalAmount = transportBasicAmount + transportTotalTax;
        } else {
            // No GST
            transportBasicAmount = transportGSTAmount;
            transportTotalTax = 0;
            transportFinalAmount = transportGSTAmount;
        }
        
        // Add transport as a GST item
        gstItems.push({
            productId: 0, // Special ID for transport
            productCode: 'TRANSPORT',
            productName: transportName,
            hsnCode: '996511', // HSN code for transport services
            rate: transportGSTAmount,
            quantity: 1,
            discountAmount: 0, // Transport is NOT discounted
            taxableAmount: transportBasicAmount,
            taxPercentage: transportGSTPercent,
            cgstPercent: transportCGSTPercent,
            cgstAmount: transportCGSTAmount,
            sgstPercent: transportSGSTPercent,
            sgstAmount: transportSGSTAmount,
            igstPercent: transportIGSTPercent,
            igstAmount: transportIGSTAmount,
            totalTaxAmount: transportTotalTax,
            finalAmount: transportFinalAmount
        });
        
        console.log('Transport GST Item added:', {
            amount: transportGSTAmount,
            type: transportGSTType,
            percent: transportGSTPercent,
            basicAmount: transportBasicAmount,
            totalTax: transportTotalTax,
            finalAmount: transportFinalAmount
        });
    }
    
    // Send to server
    $.ajax({
        url: 'api/save-gst-details.php',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            saleId: saleId,
            invoiceNumber: invoiceNumber,
            taxType: taxType,
            gstItems: gstItems
        }),
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                console.log('GST details saved successfully:', response.recordsInserted, 'records');
            } else {
                console.error('Error saving GST details:', response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error saving GST details:', error);
        }
    });
}

/**
 * Print GST Details
 */
function printGSTDetails() {
    // Check if we're viewing current cart or saved sale
    if (typeof cart !== 'undefined' && cart.length > 0 && !$('#editingSaleId').val()) {
        printGSTDetailsFromCart();
        return;
    }
    
    if (!currentGSTData) {
        Swal.fire({
            icon: 'warning',
            title: 'No Data',
            text: 'No GST details available to print',
            confirmButtonColor: '#3085d6'
        });
        return;
    }
    
    const printWindow = window.open('', '_blank');
    const saleInfo = currentGSTData.saleInfo;
    const gstDetails = currentGSTData.gstDetails;
    const totals = currentGSTData.totals;
    const taxType = saleInfo.TaxType;
    
    let printContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>GST Details - ${saleInfo.InvoiceNumber}</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                h2 { text-align: center; margin-bottom: 20px; }
                .info-table { width: 100%; margin-bottom: 20px; }
                .info-table td { padding: 5px; }
                table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 12px; }
                th { background-color: #4CAF50; color: white; }
                .text-right { text-align: right; }
                .text-center { text-align: center; }
                .total-row { background-color: #f2f2f2; font-weight: bold; }
                .summary-box { border: 2px solid #4CAF50; padding: 15px; margin-top: 20px; }
                @media print {
                    button { display: none; }
                }
            </style>
        </head>
        <body>
            <h2>GST Details Report</h2>
            
            <table class="info-table">
                <tr>
                    <td><strong>Invoice No:</strong> ${saleInfo.InvoiceNumber}</td>
                    <td><strong>Date:</strong> ${saleInfo.SaleDate}</td>
                </tr>
                <tr>
                    <td><strong>Customer:</strong> ${saleInfo.CustomerName}</td>
                    <td><strong>GST No:</strong> ${saleInfo.GSTNumber}</td>
                </tr>
                <tr>
                    <td colspan="2"><strong>Tax Type:</strong> ${saleInfo.TaxTypeLabel}</td>
                </tr>
            </table>
            
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Code</th>
                        <th>Product Name</th>
                        <th class="text-right">Rate</th>
                        <th class="text-right">Qty</th>
                        <th class="text-right">Disc</th>
                        <th class="text-right">Taxable</th>
                        <th class="text-center">Tax%</th>
    `;
    
    if (taxType === 'INTRA') {
        printContent += `
                        <th class="text-right">CGST</th>
                        <th class="text-right">SGST</th>
        `;
    } else {
        printContent += `
                        <th class="text-right">IGST</th>
        `;
    }
    
    printContent += `
                        <th class="text-right">Total</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    gstDetails.forEach((item, index) => {
        printContent += `
            <tr>
                <td>${index + 1}</td>
                <td>${item.ProductCode}</td>
                <td>${item.ProductName}</td>
                <td class="text-right">₹${item.Rate}</td>
                <td class="text-right">${item.Quantity}</td>
                <td class="text-right">₹${item.DiscountAmount}</td>
                <td class="text-right">₹${item.TaxableAmount}</td>
                <td class="text-center">${item.TaxPercentage}%</td>
        `;
        
        if (taxType === 'INTRA') {
            printContent += `
                <td class="text-right">₹${item.CGSTAmount}</td>
                <td class="text-right">₹${item.SGSTAmount}</td>
            `;
        } else {
            printContent += `
                <td class="text-right">₹${item.IGSTAmount}</td>
            `;
        }
        
        printContent += `
                <td class="text-right">₹${item.FinalAmount}</td>
            </tr>
        `;
    });
    
    printContent += `
                    <tr class="total-row">
                        <td colspan="6" class="text-right">TOTAL:</td>
                        <td class="text-right">₹${totals.TotalTaxableAmount}</td>
                        <td></td>
    `;
    
    if (taxType === 'INTRA') {
        printContent += `
                        <td class="text-right">₹${totals.TotalCGST}</td>
                        <td class="text-right">₹${totals.TotalSGST}</td>
        `;
    } else {
        printContent += `
                        <td class="text-right">₹${totals.TotalIGST}</td>
        `;
    }
    
    printContent += `
                        <td class="text-right">₹${totals.TotalFinalAmount}</td>
                    </tr>
                </tbody>
            </table>
            
            <div class="summary-box">
                <h3>Tax Summary</h3>
                <p><strong>Taxable Amount:</strong> ₹${totals.TotalTaxableAmount}</p>
    `;
    
    if (taxType === 'INTRA') {
        printContent += `
                <p><strong>Total CGST:</strong> ₹${totals.TotalCGST}</p>
                <p><strong>Total SGST:</strong> ₹${totals.TotalSGST}</p>
        `;
    } else {
        printContent += `
                <p><strong>Total IGST:</strong> ₹${totals.TotalIGST}</p>
        `;
    }
    
    printContent += `
                <p><strong>Total Tax:</strong> ₹${totals.TotalTaxAmount}</p>
                <h3><strong>Grand Total:</strong> ₹${totals.TotalFinalAmount}</h3>
            </div>
            
            <button onclick="window.print()" style="margin-top: 20px; padding: 10px 20px; font-size: 16px;">Print</button>
        </body>
        </html>
    `;
    
    printWindow.document.write(printContent);
    printWindow.document.close();
}

/**
 * Export GST Details to Excel
 */
function exportGSTToExcel() {
    if (!currentGSTData) {
        Swal.fire({
            icon: 'warning',
            title: 'No Data',
            text: 'No GST details available to export',
            confirmButtonColor: '#3085d6'
        });
        return;
    }
    
    // This would require a library like xlsx.js or send to server for Excel generation
    Swal.fire({
        icon: 'info',
        title: 'Export Feature',
        text: 'Excel export functionality can be implemented using xlsx.js library',
        confirmButtonColor: '#3085d6'
    });
}

/**
 * Print GST Details from Current Cart
 */
function printGSTDetailsFromCart() {
    const printWindow = window.open('', '_blank');
    const content = $('#gstDetailsContent').html();
    
    const invoiceNumber = $('#currentInvoiceNumber').text().trim();
    const currentDate = new Date().toLocaleDateString('en-GB');
    
    let printContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>GST Details - ${invoiceNumber}</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 15px; }
                h3 { text-align: center; margin-bottom: 20px; color: #2d3748; }
                .info-box { background: #f7fafc; padding: 10px; border-radius: 5px; margin-bottom: 15px; }
                .info-box strong { color: #2d3748; }
                table { width: 100%; border-collapse: collapse; margin-bottom: 15px; font-size: 13px; }
                th, td { border: 1px solid #cbd5e0; padding: 6px 8px; text-align: left; }
                th { background-color: #48bb78; color: white; font-weight: 600; }
                .text-right { text-align: right; }
                .text-center { text-align: center; }
                .total-row { background-color: #2d3748; color: white; font-weight: bold; }
                .summary-box { border: 2px solid #48bb78; padding: 10px; margin-top: 15px; border-radius: 5px; }
                .summary-box h4 { margin: 5px 0; color: #2d3748; }
                .badge { display: inline-block; padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: 600; }
                .badge-success { background: #48bb78; color: white; }
                .badge-warning { background: #ed8936; color: white; }
                .badge-info { background: #4299e1; color: white; }
                @media print {
                    button { display: none; }
                }
            </style>
        </head>
        <body>
            <h3>GST Details - HSN-wise Summary</h3>
            
            <div class="info-box">
                <strong>Invoice No:</strong> ${invoiceNumber} &nbsp;&nbsp;&nbsp;
                <strong>Date:</strong> ${currentDate}
            </div>
            
            ${content}
            
            <button onclick="window.print()" style="margin-top: 20px; padding: 8px 16px; font-size: 14px; background: #4299e1; color: white; border: none; border-radius: 4px; cursor: pointer;">
                Print This Document
            </button>
        </body>
        </html>
    `;
    
    printWindow.document.write(printContent);
    printWindow.document.close();
}

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