@extends('layout')
@section('content')
<style>
    .invoice-table {
        width: 100%;
        border-collapse: collapse;
    }
    .invoice-table th, .invoice-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    .invoice-table th {
        background-color: #f2f2f2;
    }
    .form-control {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    .checkbox-label {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
    }
    .summary-box {
        border: 1px solid #ddd;
        padding: 15px;
        margin-top: 20px;
        background-color: #f9f9f9;
    }
    .char-count {
        font-size: 12px;
        color: #6c757d;
    }
    .btn {
        padding: 8px 16px;
        margin-right: 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .btn-primary {
        background-color: #007bff;
        color: white;
    }
    .btn-secondary {
        background-color: #6c757d;
        color: white;
    }
    .btn-danger {
        background-color: #dc3545;
        color: white;
    }
    .btn-success {
        background-color: #28a745;
        color: white;
    }
    .action-buttons {
        margin-bottom: 15px;
    }
    .extra-charge-box {
        display: none;
    }
</style>
<main class="main-content">
    <div class="container px-2">
        <h2>View Purchase Bill</h2>
        <div class="page-header">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ asset('dashboard') }}">{{ __('message.dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ asset('account/purchase-bill') }}">Purchase Bill</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Edit</li>
                </ol>
            </nav>
        </div>

        <div class="card">
            <x-flashMessage />
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form action="{{ asset('account/add-purchase-bill') }}" method="post">
                @csrf
                <input disabled type="hidden" name="bill_id" value="{{$invoice->id}}">
                <div class="card-header py-4">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-5">Vendor/Supplier</label>
                                <select class="col-7 form-control py-2 border" name="vendor_id" required>
                                    <option selected disabled>Select</option>
                                    @foreach($customers as $cus)
                                        <option value="{{$cus->id}}" {{$invoice->vendor_id == $cus->id ? "selected" : ""}}>{{$cus->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Bill No.</label>
                                <input disabled type="text" class="form-control py-2 col-7 border" value="{{$invoice->bill_number}}" name="bill_number" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Bill Date</label>
                                <input disabled type="date" class="form-control py-2 col-7 border" name="bill_date" value="{{$invoice->bill_date}}" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Due Date</label>
                                <input disabled type="date" class="form-control py-2 col-7 border invoice_date" name="due_date" value="{{$invoice->due_date}}" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">PO No.</label>
                                <input disabled type="text" class="form-control py-2 col-7 border" name="po_number" value="{{$invoice->po_number}}"  required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">PO Date</label>
                                <input disabled type="date" class="form-control py-2 col-7 border" name="po_date" value="{{$invoice->po_date}}" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Invoice Number</label>
                                <input disabled type="text" class="form-control py-2 col-7 border invoice_date" value="{{$invoice->invoice_number}}" name="invoice_number" required>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="action-buttons">
                        <button type="button" id="addItemBtn" class="btn btn-success">
                            <i class="fa fa-plus"></i> Add Item
                        </button>
                    </div>
                    
                    <table class="invoice-table" id="invoiceItems">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Item Name</th>
                                <th>QTY</th>
                                <th>Price</th>
                                <th>Discount (%)</th>
                                <th>CGST</th>
                                <th>SGST</th>
                                <th>IGST</th>
                                <th>Total</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($invoice_items as $index => $item)
                            <tr class="item-row">
                                <td>{{ $index + 1 }}</td>
                                <td>
                                    <select class="form-control item-name select-item-change" name="item_id[]" required>
                                        <option value="">Select Item</option>
                                        @foreach($items as $product)
                                            <option value="{{ $product->id }}" 
                                                {{ $item->item_id == $product->id ? 'selected' : '' }}
                                                data-price="{{ $product->sales_unit_price }}"
                                                data-tax="{{ $product->tax }}">
                                                {{ $product->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td><input disabled type="number" class="form-control item-qty" min="1" name="item_quantity[]" value="{{ $item->item_quantity }}" required></td>
                                <td><input disabled type="number" class="form-control item-price" min="0" step="0.01" name="item_price[]" value="{{ $item->item_price }}"></td>
                                <td><input disabled type="number" class="form-control item-discount" min="0" max="100" name="item_discount[]" value="{{ $item->item_discount }}"></td>
                                <td><input disabled type="number" class="form-control item-cgst" readonly name="item_cgst[]" value="{{ $item->item_cgst }}"></td>
                                <td><input disabled type="number" class="form-control item-sgst" readonly name="item_sgst[]" value="{{ $item->item_sgst }}"></td>
                                <td><input disabled type="number" class="form-control item-igst" readonly name="item_igst[]" value="{{ $item->item_igst }}"></td>
                                <td><input disabled type="number" class="form-control item-total" readonly name="item_total[]" value="{{ $item->item_total }}"></td>
                                <td>
                                    @if($index > 0)
                                        <button type="button" class="remove-item-btn btn btn-sm btn-danger">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    @endif
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            
                            
                            <div class="form-group">
                                <label>Description</label>
                                <textarea class="form-control" id="description" rows="3" name="description">{{ $invoice->description }}</textarea>
                                <div class="char-count"><span id="charCount">{{ 1000 - strlen($invoice->description) }}</span> characters left</div>
                            </div>
                            
                            <div class="form-group">
                                <div class="row">
                                    <div class="checkbox-label col-md-5">
                                        <input disabled type="checkbox" id="shippingCharges" {{ $invoice->shipping_charge > 0 ? 'checked' : '' }}>
                                        <label for="shippingCharges" class="pt-2" style="cursor:pointer;">&nbsp;Add shipping charges</label>
                                    </div>
                                    <div class="col-md-7 px-3 extra-charge-box" id="shippingBox" style="{{ $invoice->shipping_charge > 0 ? '' : 'display:none;' }}">
                                        <div class="form-group">
                                            <input disabled type="number" class="form-control shipping-charge" name="shipping_charge" 
                                                   placeholder="Enter shipping amount" min="0" step="0.01"
                                                   value="{{ $invoice->shipping_charge }}">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="checkbox-label">
                                    <input disabled type="checkbox" id="showCess"  {{ $invoice->cess > 0 ? 'checked' : '' }}>
                                    <label for="showCess" class="pt-2">&nbsp; Show CESS</label>
                                </div>
                                <div class="checkbox-label mt-2">
                                    <input disabled type="checkbox" id="addOtherCharges"> <label for="addOtherCharges" class="pt-2">&nbsp; Add Other Charges</label>
                                </div>
                                
                                <div id="otherChargesContainer" class="mt-2" style="display:none;">
                                    <div class="additional-charge-row">
                                        <div class="row">
                                            <div class="col-md-5">
                                                <input disabled type="text" class="form-control" placeholder="Charge Name" id="otherChargeName">
                                            </div>
                                            <div class="col-md-5">
                                                <input disabled type="number" class="form-control" placeholder="Amount" id="otherChargeAmount" min="0" step="0.01">
                                            </div>
                                            <div class="col-md-2">
                                                <button type="button" class="btn btn-sm btn-success" id="addOtherChargeBtn">Add</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="checkbox-label mt-2">
                                    <input disabled type="checkbox" id="applyDiscount"> <label for="applyDiscount" class="pt-2">&nbsp; Apply All Discount</label>
                                </div>
                                
                                <div id="discountContainer" class="mt-2" style="display:none;">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <input disabled type="number" class="form-control" placeholder="Discount Percentage" id="discountPercentage" min="0" max="100">
                                        </div>
                                        <div class="col-md-4">
                                            <button type="button" class="btn btn-sm btn-primary" id="applyDiscountBtn">Apply</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="summary-box">
                                <h4>Summary</h4>
                                <div class="d-flex justify-content-between">
                                    <span>Subtotal: </span>
                                    <span>₹ &nbsp;<input disabled id="subtotal" type="text" name="subtotal" class="p-1 border-0" 
                                           value="{{ number_format($invoice->subtotal, 2) }}" readonly></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>CGST:</span>
                                    <span>₹ &nbsp;<input disabled id="cgstTotal" type="text" name="cgst_total" class="p-1 border-0" 
                                           value="{{ number_format($invoice->cgst_total, 2) }}" readonly></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>SGST:</span>
                                    <span>₹ &nbsp;<input disabled id="sgstTotal" type="text" name="sgst_total" class="p-1 border-0" 
                                           value="{{ number_format($invoice->sgst_total, 2) }}" readonly></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>IGST:</span>                                
                                    <span>₹ &nbsp;<input disabled id="igstTotal" type="text" name="igst_total" class="p-1 border-0" 
                                           value="{{ number_format($invoice->igst_total, 2) }}" readonly></span>
                                </div>
                                <div class="d-flex justify-content-between" id="cessContainer" 
                                     style="{{ $invoice->cess > 0 ? '' : 'display:none;' }}">
                                    <span>CESS:</span>
                                    <span>₹ &nbsp;<input disabled id="cessTotal" type="text" name="cess_total" class="p-1 border-0" 
                                           value="{{ number_format($invoice->cess, 2) }}" readonly></span>
                                </div>
                                <div class="d-flex justify-content-between" id="cessContainer" style="display:none;">
                                    <span>Other Charge:</span>
                                    <input disabled type="hidden" min="0" max="100" name="others_charge_name" id="others_charge_name" value="{{$invoice->others_charge_name}}">
                                    <span>₹ &nbsp;<input disabled id="others_charge_amount" type="text" name="others_charge_amount" value="{{$invoice->others_charge_amount}}" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                <div class="d-flex justify-content-between" id="cessContainer" style="display:none;">
                                    <span>All Discount:</span>
                                    <input disabled type="hidden" min="0" max="100" name="all_discount_percentage" id="all_discount_percentage" value="{{$invoice->all_discount_percentage}}">
                                    <span>₹ &nbsp;<input disabled id="all_discount_amount" type="text" name="all_discount_amount" class="p-1 border-0" placeholder="0.00" value="{{$invoice->all_discount_amount}}"></span>
                                </div>
                                @if($invoice->shipping_charge > 0)
                                <div class="d-flex justify-content-between shipping_input disabled_box">
                                    <span>Shipping Charge:</span>                                
                                    <span>₹ &nbsp;<input disabled id="shippinginput disabled" type="text" class="p-1 border-0" 
                                           value="{{ number_format($invoice->shipping_charge, 2) }}" readonly></span>
                                </div>
                                @endif
                                <hr>
                                <div class="d-flex justify-content-between font-weight-bold">
                                    <span>Total:</span>
                                    <span>₹ &nbsp;<input disabled id="grandTotal" type="text" name="grand_total" class="p-1 border-0" 
                                           value="{{ number_format($invoice->grand_total, 2) }}" readonly></span>
                                </div>
                            </div>
                            
                            <div class="form-group mt-3">
                                <label>Terms & Conditions</label>
                                <textarea class="form-control" rows="3" name="terms_and_conditions">{{ $invoice->terms_and_conditions }}</textarea>
                            </div>
                            
                            <div class="form-group">
                                <label>Private notes (not shown to client)</label>
                                <textarea class="form-control" rows="3" name="private_note">{{ $invoice->private_note }}</textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="text-right mt-4">
                        <button type="submit" class="btn btn-primary" disabled>Update Invoice</button>
                        
                    </div>
                </div>
            </form>
        </div>
    </div>
</main>
@endsection

@push('footer-script')
<script>
    $(document).ready(function() {
        // Initialize item counter
        let itemCounter = 1;
        let discountPercentage  = 0;
        let otherCharges = 0;
        
        // Character count for description
        $('#description').on('input disabled', function() {
            const maxLength = 1000;
            const currentLength = $(this).val().length;
            $('#charCount').text(maxLength - currentLength);
        });

        
        // Show/hide other charges input disabled
        $('#addOtherCharges').change(function() {
            $('#otherChargesContainer').toggle(this.checked);
        });

        // Show/hide discount input disabled
        $('#applyDiscount').change(function() {
            $('#discountContainer').toggle(this.checked);
            if (!this.checked) {
                discountPercentage = 0;
                $('#discountSummary').hide();
                calculateInvoice();
            }
        });
            // Add other charge
        $('#addOtherChargeBtn').click(function() {
            const chargeName = $('#otherChargeName').val();
            const chargeAmount = parseFloat($('#otherChargeAmount').val()) || 0;
            
            if (chargeName && chargeAmount > 0) {
                otherCharges = chargeAmount;
                // Add to summary
                $('#otherChargesSummary').append(`
                    <div class="d-flex justify-content-between" data-charge="${chargeName}">
                        <span>${chargeName}:</span>
                        <span>₹ &nbsp;<input disabled type="text" value="${chargeAmount.toFixed(2)}" class="p-1 border-0" readonly></span>
                    </div>
                `);
                
                // show other charge
                $('#others_charge_name').val(chargeName);
                $('#others_charge_amount').val(chargeAmount);
                
                calculateInvoice();
            }
        });

        // Apply discount
        $('#applyDiscountBtn').click(function() {
            discountPercentage = parseFloat($('#discountPercentage').val()) || 0;
            if (discountPercentage > 0) {
                $('#discountSummary').show();
                calculateInvoice();
            }
        });

        // Add new item row
        $('#addItemBtn').click(function() {
            itemCounter++;
            const newRow = `
                <tr class="item-row">
                    <td>${itemCounter}</td>
                    <td>
                        <select class="form-control item-name select-item-change" name="item_id[]">
                            <option disabled selected>Select</option>
                            @foreach($items as $item)
                                <option value="{{$item->id}}">{{$item->name}}</option>
                            @endforeach
                        </select>
                    </td>
                    
                    <td><input disabled type="number" class="form-control item-qty" min="1" name="item_quantity[]" required></td>
                    <td><input disabled type="number" class="form-control item-price" min="0" step="0.01" name="item_price[]"></td>
                    <td><input disabled type="number" class="form-control item-discount" min="0" max="100" name="item_discount[]"></td>
                    <td><input disabled type="number" class="form-control item-cgst" readonly name="item_cgst[]"></td>
                    <td><input disabled type="number" class="form-control item-sgst" readonly name="item_sgst[]"></td>
                    <td><input disabled type="number" class="form-control item-igst" readonly name="item_igst[]"></td>
                    <td><input disabled type="number" class="form-control item-total" readonly name="item_total[]"></td>
                            
                    
                    <td><button type="button" class="remove-item-btn btn btn-sm btn-danger"><i class="fa fa-trash"></i></button></td>
                </tr>
            `;
            $('#invoiceItems tbody').append(newRow);
            $('#removeItemBtn').prop('disabled', false);
            
            // Set tax rates based on current selection
            
            
            // Add event listeners to new row
            addRowEventListeners($('#invoiceItems tbody tr:last'));
            // Remove last item row
            $('.remove-item-btn').click(function() {
                
                    $(this).parent().parent().remove();
                    calculateInvoice();
                
            });

            //select item change
            $(".select-item-change").on("change",function(){
                var item_id = $(this).val();
                var row = $(this).closest('tr');
                $.ajax({
                        url: "{{asset('account/fetch-item')}}",
                        type: 'post',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        data: {
                            "item_id":item_id
                        },
                        success: function(result) {
                            const item = (result.data);
                            row.find('.item-price').val(item.sales_unit_price);
                            row.find('.item-igst').val(Number(item.tax));

                            updateTaxRates(Number(item.tax));
                        },
                        error: function(xhr) {
                            console.log("error");
                        }
                    });
            });
        });

        // Add new item row
        $('#addItemBtn').click(function() {
            itemCounter++;
            const newRow = `
                <tr class="item-row">
                    <td>${itemCounter}</td>
                    <td>
                        <select class="form-control item-name select-item-change" name="item_id[]">
                            <option disabled selected>Select</option>
                            @foreach($items as $item)
                                <option value="{{$item->id}}">{{$item->name}}</option>
                            @endforeach
                        </select>
                    </td>
                    
                    <td><input disabled type="number" class="form-control item-qty" min="1" name="item_quantity[]" required></td>
                    <td><input disabled type="number" class="form-control item-price" min="0" step="0.01" name="item_price[]"></td>
                    <td><input disabled type="number" class="form-control item-discount" min="0" max="100" name="item_discount[]"></td>
                    <td><input disabled type="number" class="form-control item-cgst" readonly name="item_cgst[]"></td>
                    <td><input disabled type="number" class="form-control item-sgst" readonly name="item_sgst[]"></td>
                    <td><input disabled type="number" class="form-control item-igst" readonly name="item_igst[]"></td>
                    <td><input disabled type="number" class="form-control item-total" readonly name="item_total[]"></td>
                            
                    
                    <td><button type="button" class="remove-item-btn btn btn-sm btn-danger"><i class="fa fa-trash"></i></button></td>
                </tr>
            `;
            $('#invoiceItems tbody').append(newRow);
            $('#removeItemBtn').prop('disabled', false);
            
            // Set tax rates based on current selection
            
            
            // Add event listeners to new row
            addRowEventListeners($('#invoiceItems tbody tr:last'));
            // Remove last item row
            $('.remove-item-btn').click(function() {
                
                    $(this).parent().parent().remove();
                    calculateInvoice();
                
            });

            //select item change
            $(".select-item-change").on("change",function(){
                var item_id = $(this).val();
                var row = $(this).closest('tr');
                $.ajax({
                        url: "{{asset('account/fetch-item')}}",
                        type: 'post',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        data: {
                            "item_id":item_id
                        },
                        success: function(result) {
                            const item = (result.data);
                            row.find('.item-price').val(item.sales_unit_price);
                            row.find('.item-igst').val(Number(item.tax));

                            updateTaxRates(Number(item.tax));
                        },
                        error: function(xhr) {
                            console.log("error");
                        }
                    });
            });
        });

        

        // Tax type selection
        // $('#taxType').change(function() {
        //     updateTaxRates();
        //     calculateInvoice();
        // });

        // Show/hide CESS
        $('#showCess').change(function() {
            if($(this).is(':checked')) {
                $('#cessContainer').show();
            } else {
                $('#cessContainer').hide();
            }
            calculateInvoice();
        });

        // Update tax rates for all rows
        function updateTaxRates(tax) {
            const taxType = $('#taxType').val();
            $('.item-row').each(function() {
                if(taxType === 'cgst_sgst') {
                    $(this).find('.item-igst').val(0);
                    $(this).find('.item-cgst').val(0);
                    $(this).find('.item-sgst').val(0);
                } else {
                    $(this).find('.item-igst').val(tax);
                    $(this).find('.item-cgst').val(0);
                    $(this).find('.item-sgst').val(0);
                }
            });
        }

        // Add event listeners to a row
        function addRowEventListeners(row) {
            row.find('.item-qty, .item-price, .item-discount').on('input disabled', calculateInvoice);
        }

        // Auto calculation for invoice items
        function calculateInvoice() {
            let subtotal = 0;
            let totalCgst = 0;
            let totalSgst = 0;
            let totalIgst = 0;
            let grandTotal = 0;

            $('.item-row').each(function() {
                const qty = parseFloat($(this).find('.item-qty').val()) || 0;
                const price = parseFloat($(this).find('.item-price').val()) || 0;
                const discount = parseFloat($(this).find('.item-discount').val()) || 0;
                const cgstRate = parseFloat($(this).find('.item-cgst').val()) || 0;
                const sgstRate = parseFloat($(this).find('.item-sgst').val()) || 0;
                const igstRate = parseFloat($(this).find('.item-igst').val()) || 0;
                
                // Calculate item subtotal after discount
                const itemSubtotal = qty * price;
                const discountAmount = itemSubtotal * (discount / 100);
                const itemSubtotalAfterDiscount = itemSubtotal - discountAmount;
                
                // Calculate taxes
                const cgstAmount = itemSubtotalAfterDiscount * (cgstRate / 100);
                const sgstAmount = itemSubtotalAfterDiscount * (sgstRate / 100);
                const igstAmount = itemSubtotalAfterDiscount * (igstRate / 100);
                const itemTotal = itemSubtotalAfterDiscount + cgstAmount + sgstAmount + igstAmount;
                
                // Update item row
                $(this).find('.item-total').val(itemTotal.toFixed(2));
                
                // Add to totals
                subtotal += itemSubtotalAfterDiscount;
                totalCgst += cgstAmount;
                totalSgst += sgstAmount;
                totalIgst += igstAmount;
                grandTotal += itemTotal;
            });

            // Update summary
            $('#subtotal').val(subtotal.toFixed(2));
            $('#cgstTotal').val(totalCgst.toFixed(2));
            $('#sgstTotal').val(totalSgst.toFixed(2));
            $('#igstTotal').val(totalIgst.toFixed(2));
            
            
            if($("#shippingCharges").is(':checked')) {
                var shippingCharge = $("#shippinginput disabled").val();
                grandTotal = Number(grandTotal) + Number(shippingCharge);
            };
            // Calculate CESS if enabled
            if($('#showCess').is(':checked')) {
                const cessPercent = 2; // Example CESS percentage
                const cessAmount = (subtotal * cessPercent) / 100;
                $('#cessTotal').val(cessAmount.toFixed(2));
                grandTotal = parseFloat(grandTotal + cessAmount).toFixed(2);
            }
            
            
            // Add other charges
                let otherChargesTotal = 0;
                
                otherChargesTotal += otherCharges;
                
                grandTotal += otherChargesTotal;
                
                // Apply discount if enabled
                let allDdiscountAmount = 0;
                if (discountPercentage > 0) {
                    allDdiscountAmount = (grandTotal * discountPercentage) / 100;
                    $('#discountAmount').val(allDdiscountAmount.toFixed(2));
                    $("#all_discount_percentage").val(discountPercentage);
                    $("#all_discount_amount").val(allDdiscountAmount.toFixed(2));

                    grandTotal -= allDdiscountAmount.toFixed(2);
                }
            
            $('#grandTotal').val(grandTotal.toFixed(2));
        }

        // Add event listeners to initial row
        addRowEventListeners($('.item-row'));
        
        // Initial calculation
        //calculateInvoice();

        $("#shippingCharges").change(function() {
            if ($(this).is(':checked')) {
                $(".shipping_box").removeClass("d-none");
                
                // Only add shipping input disabled if it doesn't already exist
                if ($(".shipping_input disabled_box").length === 0) {
                    var shipping = `<div class="d-flex justify-content-between shipping_input disabled_box">
                                    <span>Shipping Charge:</span>                                
                                    <span>₹ &nbsp;<input disabled id="shippinginput disabled" type="number" name="shipping_total" class="p-1 border-0" placeholder="0.00" min="0" step="0.01"></span>
                                    </div>`;
                    $(".add_extra_total").append(shipping);
                }
                
                // Handle shipping charge changes
                $(".shipping_charge").on("input disabled", function() {
                    var charge = parseFloat($(this).val()) || 0;
                    $('#shippinginput disabled').val(charge.toFixed(2));
                    calculateInvoice(); // Recalculate the entire invoice
                });
            } else {
                // Remove shipping charge from calculation
                $('.shipping_input disabled_box').remove();
                $(".shipping_box").addClass("d-none");
                $(".shipping_charge").val('');
                calculateInvoice(); // Recalculate the entire invoice
            }
        });

        //select item change
        $(".select-item-change").on("change",function(){
            var item_id = $(this).val();
            var row = $(this).closest('tr');
            $.ajax({
                    url: "{{asset('account/fetch-item')}}",
                    type: 'post',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        "item_id":item_id
                    },
                    success: function(result) {
                        const item = (result.data);
                        row.find('.item-price').val(item.sales_unit_price);
                        row.find('.item-igst').val(Number(item.tax));
                    },
                    error: function(xhr) {
                        console.log("error");
                    }
                });
        });

        
        
    });
</script>
@endpush