<div class="card mb-3">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap">
        <span>Items</span>
        <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
            <i class="fas fa-plus me-1"></i> Add Item
        </button>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-bordered align-middle" id="itemsTable" width="100%" cellspacing="0" >
                <thead class="table-light">
                    <tr>
                        <th>Sl no</th>
                        <th>Item Name</th>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>UOM</th>
                        <th>Unit Rate (INR)</th>
                        <th>TDS (%)</th>
                        <th>Discount %</th>
                        <th>Value (INR)</th>
                        <th>SGST (%)</th>
                        <th>CGST (%)</th>
                        <th>IGST (%)</th>
                        <th>Amount</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="itemsContainer">
                    <tr class="item-row">
                        <td>
                            <input type="text" class="form-control" name="items[0][sl_no]" id="item_sl_no_0"
                                value="1" readonly data-name="index">
                        </td>
                        <td>
                            <select class="form-control" name="items[0][item_id]" id="item_id_0" data-name="stock_item" required>
                                <option value="">Select Item</option>
                                @foreach ($items as $item)
                                    <option value="{{ $item->id }}">{{ $item->item_name }}</option>
                                @endforeach
                            </select>
                        </td>
                        <td>
                            <input type="text" class="form-control" name="items[0][description]"
                                id="item_description_0" data-name="description">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][quantity]" id="item_quantity_0"
                                min="1" value="1" required data-name="quantity">
                        </td>
                        <td>
                            <input type="text" class="form-control" name="items[0][uom]" id="item_uom_0"
                                data-name="uom">
                            <!-- <select class="form-control selectpicker" name="items[0][uom]" id="item_uom_0" required>
                                <option value="PCS">PCS</option>
                                <option value="KG">KG</option>
                                <option value="LTR">LTR</option>
                                <option value="MTR">MTR</option>
                            </select> -->
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][rate]" id="item_rate_0"
                                min="0" step="0.01" required data-name="unit_rate">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][tds]" id="item_tds_0"
                                min="0" max="100" value="0" data-name="tds">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][discount]" id="item_discount_0"
                                min="0" max="100" value="0" data-name="discount">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][value]" id="item_value_0"
                                min="0" step="0.01" value="0" readonly data-name="value">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][sgst]" id="item_sgst_0"
                                min="0" max="100" value="0" data-name="sgst">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][cgst]" id="item_cgst_0"
                                min="0" max="100" value="0" data-name="cgst">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][igst]" id="item_igst_0"
                                min="0" max="100" value="0" data-name="igst">
                        </td>
                        <td>
                            <input type="number" class="form-control" name="items[0][amount]" id="item_amount_0"
                                min="0" step="0.01" value="0" readonly data-name="amount">
                        </td>
                        <td class="text-center">
                            <button type="button" class="btn btn-outline-danger btn-sm remove-item">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="card mb-3" id="gst-aggregate">
    <div class="card-header">Items Summary</div>
    <div class="card-body">
        <!--<div id="gst-aggregate-items">
            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label" for="gst_aggregate" id="gst_aggregate_label"></label>
                </div>
                <div class="col-md-6">
                    <input type="number" class="form-control" name="gst_aggregate" id="gst_aggregate" min="0"
                        step="0.01" value="0">
                </div>
            </div>
        </div> -->
        <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 class="row mb-3">
            <div class="col-12 col-md-4 mb-2 mb-md-0">
                <label class="form-label" for="additional_charges">Additional Charges</label>
                <input type="number" class="form-control" name="additional_charges" id="additional_charges"
                    min="0" step="0.01" value="0">
            </div>
            <div class="col-12 col-md-4 mb-2 mb-md-0">
                <label class="form-label" for="total_tds">Total TDS (INR)</label>
                <input type="number" class="form-control" name="total_tds" id="total_tds" min="0"
                    max="100" value="0" readonly>
            </div>
            <div class="col-12 col-md-4">
                <label class="form-label" for="sub_total">Sub Total</label>
                <input type="text" class="form-control" id="sub_total" name="sub_total" readonly value="0.00">
            </div>
        </div>

        <div class="row">
            <div class="col-12 col-md-4 mb-2 mb-md-0">
                <label class="form-label" for="total_amount">Total Invoice Amount</label>
                <input type="text" class="form-control" id="total_amount" name="total_amount" readonly
                    value="0.00">
            </div>
            <div class="col-12 col-md-4 mb-2 mb-md-0">
                <label class="form-label" for="paid_amount">Paid Amount</label>
                <input type="number" class="form-control" name="paid_amount" id="paid_amount" min="0"
                    step="0.01" value="0">
            </div>
            <div class="col-12 col-md-4">
                <label class="form-label" for="balance_amount">Balance Amount</label>
                <input type="text" class="form-control" id="balance_amount" name="balance_amount" readonly
                    value="0.00">
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script>
        // document.addEventListener('DOMContentLoaded', function() {
            
        // });
        // Add new item row
        $('#addItemBtn').on('click', function() {
            let $lastRow = $('#itemsContainer tr.item-row:last');
            let newRow = $lastRow.clone();

            // Update all input/select names and ids for the new row
            newRow.find('input, select').each(function(idx) {
                let itemIndex = idx + 1;
                let name = $(this).attr('name');
                let id = $(this).attr('id');
                if (name) {
                    name = name.replace(/\[\d+\]/, '[' + itemIndex + ']');
                    $(this).attr('name', name);
                }
                if (id) {
                    id = id.replace(/_\d+$/, '_' + itemIndex);
                    $(this).attr('id', id);
                }
                // Reset values
                if ($(this).is('input[type="text"]')) {
                    if ($(this).attr('readonly')) {
                        // For sl_no
                        $(this).val(itemIndex + 1);
                    } else {
                        $(this).val('');
                    }
                } else if ($(this).is('input[type="number"]')) {
                    if ($(this).attr('readonly')) {
                        // For value/amount, keep as 0
                        $(this).val(0);
                    } else if ($(this).attr('min') === "1") {
                        $(this).val(1);
                    } else {
                        $(this).val(0);
                    }
                } else if ($(this).is('select')) {
                    $(this).val('');
                }
            });
            newRow.find('.remove-item').show();
            $('#itemsContainer').append(newRow);
            resetInitials();
            updateRemoveButtons();
            recalculateAll();
            // fillGstAggregate();
        });

        // Remove item row
        $(document).on('click', '.remove-item', function() {
            if ($('#itemsContainer tr.item-row').length > 1) {
                $(this).closest('tr').remove();
                updateRemoveButtons();
                recalculateAll();
            }
        });

        // Hide remove button for first row only
        function updateRemoveButtons() {
            $('#itemsContainer tr.item-row .remove-item').show();
            $('#itemsContainer tr.item-row:first .remove-item').hide();
            // $('.selectpicker').selectpicker('refresh');
        }

        $(document).ready(function() {
            resetInitials();
            updateRemoveButtons();
            recalculateAll();
        });

        // Recalculate values and totals on input change
        $(document).on('input change', '#itemsContainer input, #itemsContainer select, #additional_charges, #paid_amount',
            function() {
                recalculateAll();
            });

        function recalculateAll() {
            let totalTds = 0;
            let subTotal = 0;
            let totalAmount = 0;

            $('#itemsContainer tr.item-row').each(function(idx) {
                // Get values
                let $row = $(this);
                let quantity = parseFloat($row.find('input[name^="items["][name$="[quantity]"]').val()) || 0;
                let rate = parseFloat($row.find('input[name^="items["][name$="[rate]"]').val()) || 0;
                let discount = parseFloat($row.find('input[name^="items["][name$="[discount]"]').val()) || 0;
                let tds = parseFloat($row.find('input[name^="items["][name$="[tds]"]').val()) || 0;
                let sgst = parseFloat($row.find('input[name^="items["][name$="[sgst]"]').val()) || 0;
                let cgst = parseFloat($row.find('input[name^="items["][name$="[cgst]"]').val()) || 0;
                let igst = parseFloat($row.find('input[name^="items["][name$="[igst]"]').val()) || 0;

                // Calculate value (before taxes)
                let value = quantity * rate * (1 - discount / 100);
                value = isNaN(value) ? 0 : value;
                $row.find('input[name^="items["][name$="[value]"]').val(value.toFixed(2));

                // Calculate amount (after taxes)
                let taxPercent = sgst + cgst + igst;
                let amount = value * (1 + taxPercent / 100);
                amount = isNaN(amount) ? 0 : amount;
                $row.find('input[name^="items["][name$="[amount]"]').val(amount.toFixed(2));

                // Aggregate
                totalTds += (value * tds / 100);
                subTotal += value;
                totalAmount += amount;
            });

            // Additional charges
            let additionalCharges = parseFloat($('#additional_charges').val()) || 0;
            let paidAmount = parseFloat($('#paid_amount').val()) || 0;

            // Set aggregate fields
            $('#total_tds').val(totalTds.toFixed(2));
            $('#sub_total').val(subTotal.toFixed(2));
            $('#total_amount').val((totalAmount + additionalCharges).toFixed(2));
            let balance = (totalAmount + additionalCharges) - paidAmount;
            $('#balance_amount').val(balance.toFixed(2));
            fillGstAggregate();
        }

        function fillGstAggregate() {
            let items = $('#itemsContainer tr.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>${sgst}</td>
                    <td>${cgst}</td>
                    <td>${igst}</td>
                </tr>`
            });
            $('#gst-aggregate-items').html(gstAggregate);
        }
    </script>
@endpush
