<div id="itemsContainer" class="mb-2" >
    <div class="table-responsive">
        <table class="table table-bordered product-table" id="po-items-table">
            <thead>
                <tr>
                    <th>Sl No.</th>
                    <th>Item Name</th>
                    <th>Description</th>
                    <th>Quantity</th>
                    <th>UOM</th>
                    <th>Unit Rate</th>
                    <th>TDS (%)</th>
                    <th>Discount (%)</th>
                    <th>Value</th>
                    <th>SGST (%)</th>
                    <th>CGST (%)</th>
                    <th>IGST (%)</th>
                    <th>Amount</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="po-items" class="po-items">
                <tr class="po-item-row" data-id="po-item-row-1">
                    <td data-id="sl_no">1</td>
                    <td>
                        <select class="form-control" name="items[0][stock_item_id]" data-id="stock_item.id" data-edit-id="stock_item_id" onchange="getStockItem(this)">
                            <option value="">Select Item</option>
                            @foreach($stockItems as $item)
                                <option data-stock="{{ base64_encode(json_encode($item)) }}" value="{{ $item->id }}">{{ $item->item_name }}</option>
                            @endforeach
                        </select>
                        <input class="form-control" type="hidden" name="items[0][stock_item_name]" data-id="stock_item.item_name" data-edit-id="stock_item_name" value="" />
                    </td>
                    <td><input type="text" class="form-control" name="items[0][description]" data-id="description" data-edit-id="description"></td>
                    <td><input type="number" class="form-control" name="items[0][quantity]" data-id="quantity" data-edit-id="quantity"></td>
                    <td><input type="text" class="form-control" name="items[0][uom]" data-id="uom" data-edit-id="uom"></td>
                    <td><input type="number" class="form-control" name="items[0][unit_rate]" data-id="unit_rate" data-edit-id="unit_rate"></td>
                    <td><input type="number" class="form-control" name="items[0][tds]" data-id="tds" data-edit-id="tds"></td>
                    <td><input type="number" class="form-control" name="items[0][discount]" data-id="discount" data-edit-id="discount"></td>
                    <td><input type="number" class="form-control" name="items[0][value]" data-id="value" readonly data-edit-id="value"></td>
                    <td><input type="number" class="form-control" name="items[0][sgst]" data-id="sgst" data-edit-id="sgst" step="any" ></td>
                    <td><input type="number" class="form-control" name="items[0][cgst]" data-id="cgst" data-edit-id="cgst" step="any" ></td>
                    <td><input type="number" class="form-control" name="items[0][igst]" data-id="igst" data-edit-id="igst" step="any" ></td>
                    <td><input type="number" class="form-control" name="items[0][amount]" data-id="amount" readonly data-edit-id="amount"></td>
                    <td>
                        <button type="button" class="btn btn-danger" onclick="deleteRow(this)" data-id="delete">
                            <i class="fa fa-trash"></i>
                        </button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    
    {{-- Add Item Button --}}
    <div class="row mb-2">
        <button type="button" class="btn btn-outline-primary ml-auto mr-2" id="addItemBtn" onclick="addItem()">
            <i class="fas fa-plus me-2"></i>Add Item
        </button>
    </div>
    
    {{-- GST Summary --}}
    <div class="card mb-3" id="gst-aggregate">
        <div class="card-header">GST Summary</div>
        <div class="card-body">
            <table class="table table-bordered">
                <thead class="thead-light">
                    <tr>
                        <th>Total Tax Percentage (%)</th>
                        <th>SGST (INR)</th>
                        <th>CGST (INR)</th>
                        <th>IGST (INR)</th>
                    </tr>
                </thead>
                <tbody id="gst-aggregate-items">
    
                </tbody>
            </table>
        </div>
    </div>
    
</div>

@push('scripts')
    <script>
        function deleteRow(row) {
            $(row).closest('.po-item-row').remove();
        }

        // function getStockItem(node) {
        //     const stockItem = JSON.parse(atob($(node).find('option:selected').attr('data-stock')));
        //     $(node.parentElement).find('input').val(stockItem.item_name);
        // }
        
        function getStockItem(node) {
            const selectedOption = $(node).find('option:selected');
            const stockData = selectedOption.attr('data-stock');
            if (!stockData) return;
        
            const stockItem = JSON.parse(atob(stockData));
            const row = $(node).closest('tr');
        
            // Populate fields
            row.find('input[data-id="stock_item.item_name"]').val(stockItem.item_name || '');
            row.find('input[data-id="sgst"]').val(stockItem.sgst || 0);
            row.find('input[data-id="cgst"]').val(stockItem.cgst || 0);
            row.find('input[data-id="igst"]').val(stockItem.igst || 0);
        }
        
        $(document).on('change', 'select[name$="[stock_item_id]"]', function () {
            getStockItem(this);
        });


        // function addItem() {
        //     const row = $('#po-items  tr:last-child').clone();
        //     let index = parseInt(row.find('[data-id="sl_no"]').text()) + 1;
        //     let index = $('#po-items tr').length - 1;
        //     row.find('[data-id="sl_no"]').text(index);
        //     $('#po-items').append(row);
        //     updateNames();
        //     calculateTotals();
        // }

        function addItem() {
            const row = $('#po-items tr:last-child').clone();
            let index = parseInt(row.find('[data-id="sl_no"]').text()) + 1;
            row.find('[data-id="sl_no"]').text(index);
        
            // Reset values
            row.find('.form-control').each(function () {
                $(this).val('');
            });
        
            // Remove previously initialized Select2 to avoid conflict
            row.find('select[name$="[stock_item_id]"]').next('.select2-container').remove();
            row.find('select[name$="[stock_item_id]"]').removeClass('select2-hidden-accessible').removeAttr('data-select2-id').removeAttr('aria-hidden');
        
            $('#po-items').append(row);
        
            updateNames();       // Renames field names
            initializeSelect2(); // Reinitialize Select2 on new elements
            calculateTotals();
        }

        function handleItemChange() {
            
        }

        function updateNames() {
            $('#po-items tr.po-item-row').each(function(index) {
                $(this).find('.form-control').each(function() {
                    const name = $(this).attr('name');
                    const extractedIndex = name.match(/\[(\d+)\]/)[1];
                    $(this).attr('name', name.replace(`[${extractedIndex}]`, `[${index}]`));
                    $(this).off('input');
                    $(this).on('input', (e) => {
                        handleItemChange.bind(this)(e);
                        calculateTotals();
                    });
                });
            });
            const form = $("#purchaseInvoiceForm");
            form.find("#additional_charges,#paid_amount").off('input');
            form.find("#additional_charges,#paid_amount").on('input', (e) => {
                calculateTotals();
            });
        }

        function calculateTotals() {
            let subtotal = 0;
            let sgstTotal = 0;
            let cgstTotal = 0;
            let igstTotal = 0;
            let totalTds = 0;
            const form = $("#purchaseInvoiceForm");
            $('#po-items tr').each(function() {
                const quantity = parseFloat($(this).find('[data-id="quantity"]').val()) || 0;
                const rate = parseFloat($(this).find('[data-id="unit_rate"]').val()) || 0;
                const discount = parseFloat($(this).find('[data-id="discount"]').val()) || 0;
                const tds = parseFloat($(this).find('[data-id="tds"]').val()) || 0;
                const sgst = parseFloat($(this).find('[data-id="sgst"]').val()) || 0;
                const cgst = parseFloat($(this).find('[data-id="cgst"]').val()) || 0;
                const igst = parseFloat($(this).find('[data-id="igst"]').val()) || 0;
                const value = quantity * rate * (1 - discount / 100);
                const sgstAmount = value * sgst / 100;
                const cgstAmount = value * cgst / 100;
                const igstAmount = value * igst / 100;
                $(this).find('[data-id="value"]').val(value.toFixed(2));
                $(this).find('[data-id="sgst_amount"]').val(sgstAmount.toFixed(2));
                $(this).find('[data-id="cgst_amount"]').val(cgstAmount.toFixed(2));
                $(this).find('[data-id="igst_amount"]').val(igstAmount.toFixed(2));
                $(this).find('[data-id="amount"]').val((value + sgstAmount + cgstAmount + igstAmount).toFixed(2));

                totalTds += (value * tds / 100);
                subtotal += value;
                sgstTotal += sgstAmount;
                cgstTotal += cgstAmount;
                igstTotal += igstAmount;
            });

            let additionalCharges = parseFloat($('#additional_charges').val()) || 0;

            let grandTotal = subtotal + sgstTotal + cgstTotal + igstTotal  + additionalCharges;
            let netPayableAmount = grandTotal - totalTds;
            let roundUp = (Math.ceil(netPayableAmount) - netPayableAmount);

            form.find('#subtotal').val(subtotal.toFixed(2));
            form.find('#tds_amount').val((totalTds).toFixed(2));
            form.find('#sgst_amount').val(sgstTotal.toFixed(2));
            form.find('#cgst_amount').val(cgstTotal.toFixed(2));
            form.find('#igst_amount').val(igstTotal.toFixed(2));
            form.find('#round_up').val(roundUp.toFixed(2));
            form.find('#grand_total').val((grandTotal).toFixed(2));
            form.find('#net_payable_amount').val((netPayableAmount + roundUp).toFixed(2));
            form.find('#inr_in_words').val(numberToWords(netPayableAmount + roundUp));
            let paidAmount = parseFloat(form.find('#paid_amount').val()) || 0;
            let balanceAmount = (netPayableAmount + roundUp) - paidAmount;
            form.find('#balance_amount').val(balanceAmount.toFixed(2));
            form.find('#inr_in_words').val(numberToWords(balanceAmount.toFixed(2)));
            if(balanceAmount == 0 && paidAmount > 0) {
                form.find('#payment_status').val('paid');
            } else if(paidAmount > 0 && balanceAmount > 0) {
                form.find('#payment_status').val('partial');
            } else {
                form.find('#payment_status').val('unpaid');
            }
            fillGstAggregate();
        }

        function populateItems(items,mappedKeys = {}) {
            console.log({items, mappedKeys});
            // Clear existing items
            let rowClone = $('#po-items tr:first-child').clone();
            
            if(items.length === 0) { updateNames(); calculateTotals(); return; }
            $('#po-items').empty();
            const getValue = (item, key) => {
                return dotwalk(item, mappedKeys[key] || key);
            }
            items.forEach(function(item, index) {
                let row = rowClone.clone();
                row.find('.form-control').each(function() {
                    let dataId = $(this).attr('data-id');
                    let editId = $(this).attr('data-edit-id');
                    let value = getValue(item, dataId);
                    if(!value && editId) {
                       value = getValue(item, editId);
                    }
                    $(this).val(value);
                    $(this).attr('step', 'any');
                });
                $('#po-items').append(row);
            });
            updateNames();
            calculateTotals();
        }


        function fillGstAggregate() {
            let items = $('#po-items tr.po-item-row');
            let slabs = {};
            let slabgroup = {};
            items.each(function() {
                let sgst = parseFloat($(this).find('input[name^="items["][name$="[sgst]"]').val()) || 0;
                let cgst = parseFloat($(this).find('input[name^="items["][name$="[cgst]"]').val()) || 0;
                let igst = parseFloat($(this).find('input[name^="items["][name$="[igst]"]').val()) || 0;
                let value = parseFloat($(this).find('input[name^="items["][name$="[value]"]').val()) || 0;
                let amount = parseFloat($(this).find('input[name^="items["][name$="[amount]"]').val()) || 0;
                let taxPercent = sgst + cgst + igst;
                let taxAmount = value * taxPercent / 100;
                slabs[taxPercent] = (slabs[taxPercent] || 0) + taxAmount;
                let prevGroup = slabgroup[taxPercent] || {
                    sgst: 0,
                    cgst: 0,
                    igst: 0,
                    sgst_value: 0,
                    cgst_value: 0,
                    igst_value: 0
                };
                slabgroup[taxPercent] = {
                    sgst: sgst,
                    cgst: cgst,
                    igst: igst,
                    sgst_value: prevGroup.sgst_value + (value * sgst / 100),
                    cgst_value: prevGroup.cgst_value + (value * cgst / 100),
                    igst_value: prevGroup.igst_value + (value * igst / 100)
                };
            });
            $('#gst-aggregate-items').html('');
            let gstAggregate = Object.keys(slabs).filter(key => (+key) > 0).map((key, index) => {
                let sgst = (slabgroup[key]['sgst_value']).toFixed(2);;
                let cgst = (slabgroup[key]['cgst_value']).toFixed(2);;
                let igst = (slabgroup[key]['igst_value']).toFixed(2);;
                return `<tr>
                    <td>${key} % (SGST: ${slabgroup[key]['sgst']}%, CGST: ${slabgroup[key]['cgst']}%, IGST: ${slabgroup[key]['igst']}%)</td>
                    <td style="text-align: right;">${sgst}</td>
                    <td style="text-align: right;">${cgst}</td>
                    <td style="text-align: right;">${igst}</td>
                </tr>`
            });
            $('#gst-aggregate-items').html(gstAggregate);
        }
        
        function initializeSelect2() {
            $('#po-items select[name$="[stock_item_id]"]').each(function () {
                if (!$(this).hasClass('select2-hidden-accessible')) {
                    $(this).select2({
                        placeholder: "Select Item",
                        allowClear: true,
                        width: '100%',
                        dropdownParent: $('#itemsContainer')
                    });
                }
            });
        }
        
        document.addEventListener('DOMContentLoaded', function () {
    

            initializeSelect2();
            calculateTotals();
            updateNames();
        });

    </script>
@endpush




