@extends('layouts.layoutapp')

@section('content')

      <div class="row">
        <div class="col-12">
            <div class="card me-2">
                    <div class="card-header pb-0">
                        <div class="d-flex flex-row justify-content-between">
                            <div>
                                <h5 class="mb-0">Edit Invoice</h5>
                            </div>
                            <div>
                                @if ($dueAmount > 0)
                                    <p class="badge bg-warning text-dark">Due Amount:₹ {{$dueAmount}}</p>
                                @else
                                    <p class="badge bg-secondary">Due Amount:₹ {{$dueAmount}}</p>
                                @endif
                            </div>
                        </div>
                    </div>

                    <div class="card-body">
                        <form action="{{ route('invoice-update') }}" method="POST" id="invoiceForm">
                            @csrf
                            <input type="hidden" name="id" value="{{$invoice->id}}">
                            <div class="row">
                                <div class="col-lg-3 mb-3">
                                    <label for="client_name" class="form-label">Client Name:</label>
                                    <input type="text" name="client_name" id="client_name" class="form-control"
                                        value="{{ old('client_name', $invoice->client->user->name) }}" readonly>
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="client_num" class="form-label">Client Number:</label>
                                    <input type="text" name="client_num" id="client_num" class="form-control"
                                        value="{{ old('client_num', $invoice->client->user->phone) }}"
                                        data-clientID={{$invoice->client->id}} readonly>
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="invoice_id" class="form-label">Invoice number:</label>
                                    <input type="text" id="invoice_id" class="form-control"
                                        value="{{ $invoice->invoice_id }}" readonly>
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="invoice_date" class="form-label">Invoice Date:</label>
                                    <input type="date" id="invoice_date" class="form-control" name="invoice_date"
                                        value="{{ old('invoice_date', $invoice->invoice_date) }}" required>
                                    @error('invoice_date')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="due_date" class="form-label">Due Date:</label>
                                    <input type="date" id="due_date" class="form-control" name="due_date"
                                        value="{{ old('due_date', $invoice->due_date) }}" required>
                                    @error('due_date')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="gst" class="form-label">GST/Non-GST:</label>
                                    <select name="gst" id="gst" class="form-select" onchange="toggleTaxes()">
                                        <option value="">Select</option>
                                        <option value="Y" {{ old('gst', $invoice->gst) == 'Y' ? 'selected' : '' }}>GST
                                        </option>
                                        <option value="N" {{ old('gst', $invoice->gst) == 'N' ? 'selected' : '' }}>Non-GST
                                        </option>
                                    </select>
                                    @error('gst')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="delivery_status" class="form-label">Select Status</label>
                                    <select class="form-select" name="delivery_status" id="modal-delivery-status" required>
                                        <option value="">-- Select Status --</option>
                                        <option value="1" {{$invoice->delivery_status == 1 ? 'selected' : ''}}>In Progress
                                        </option>
                                        <option value="2" {{$invoice->delivery_status == 2 ? 'selected' : ''}}>Delivered
                                        </option>
                                    </select>
                                </div>
                            </div>
                            <hr>
                            <div>
                                <h5>Product Details:</h5>
                                <div class="row align-items-center">
                                    <div class="col-lg-4 d-flex align-items-center mb-3">
                                        <i class="fa-solid fa-qrcode"
                                            style="width: 30px; height: 30px; margin-right: 10px;"></i>
                                        <input class="form-control" type="text" id="product-code-input"
                                            onkeydown="preventFormSubmit(event)">
                                    </div>
                                    <div class="col-lg-4">
                                        <button type="button" onclick="addRow(event)" class="btn btn-primary addRow">
                                            <i class="fas fa-plus"></i> Add Row
                                        </button>
                                    </div>
                                </div>

                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped text-sm" id="productsTable">
                                        <thead class="thead-dark">
                                            <tr>
                                                {{-- <th>#</th> --}}
                                                <th>Product</th>
                                                <th>Avl. Qty</th>
                                                <th>Qty</th>
                                                <th>Unit Price</th>
                                                <th>Tax</th>
                                                <th>Amount</th>
                                                <th></th>
                                            </tr>
                                        </thead>
                                        <tbody id="productRows">
                                            @php
                                                $allTaxSelections = [];
                                                foreach ($invoice->invoiceItems as $index => $item) {
                                                    $allTaxSelections[$index] = $item->invoiceItemTaxes->pluck('tax_id')->toArray();
                                                }
                                            @endphp
                                            @foreach($invoice->invoiceItems as $index => $item)
                                                @php
                                                    $product = $products->firstWhere('id', $item->product_id);
                                                    $currentQty = $product ? $product->qty : 0;
                                                    $taxIds = $item->invoiceItemTaxes->pluck('tax_id')->toArray();

                                                @endphp
                                                <tr id="row-{{ $index }}">
                                                    {{-- <td>{{ $index + 1 }}</td> --}}
                                                    <td>
                                                        <div class="d-flex flex-column">
                                                            <select name="dynamicFields[{{ $index }}][product]"
                                                                class="form-select product-select"
                                                                onchange="updateProductDetails({{ $index }})">
                                                                <option value="">Select Product</option>
                                                                @foreach($products as $product)
                                                                    <option value="{{ $product->id }}" {{ $item->product_id == $product->id ? 'selected' : '' }}>
                                                                        {{ $product->code }}-{{$product->branch->native_name_flag == 'A' ? ($product->native_name ?? $product->name) : $product->name }}
                                                                    </option>
                                                                @endforeach
                                                            </select>
                                                            @if ($branch->inv_desc_flag == 'A')
                                                                <input type="text" name="dynamicFields[{{ $index }}][description]"
                                                                    class="form-control mt-1 description"
                                                                    id="description-{{ $index }}" placeholder="Enter a Description"
                                                                    value="{{ $item->description ?? '' }}"
                                                                    style="padding-left:10px !important;">
                                                            @endif
                                                        </div>
                                                    </td>
                                                    <td style="width:120px;">
                                                        @if ($branch->avl_qty_flag == 'A')
                                                            <input type="text" name="dynamicFields[{{ $index }}][avl_qty]"
                                                                class="form-control avl-qty" value="{{ $currentQty}}" readonly />
                                                        @else
                                                            <input type="text" name="dynamicFields[{{ $index }}][avl_qty]"
                                                                class="form-control avl-qty"
                                                                value="{{ $currentQty + $item->quantity}}" readonly />
                                                        @endif
                                                    </td>
                                                    <td style="width:120px;">
                                                        <input type="text" name="dynamicFields[{{ $index }}][qty]"
                                                            class="form-control qty" value="{{ $item->quantity }}"
                                                            onchange="calculateRowAmount({{ $index }})" />
                                                        <div class="invalid-feedback quantity-error" style="display: none;">
                                                            Quantity exceeds available stock!
                                                        </div>
                                                    </td>
                                                    <td style="width:120px;">
                                                        <input type="text" name="dynamicFields[{{ $index }}][unit_price]"
                                                            class="form-control unit-price" value="{{ $item->price }}"
                                                            onchange="calculateRowAmount({{ $index }})" />
                                                    </td>
                                                    <td style="min-width: 200px;">
                                                        <select name="dynamicFields[{{ $index }}][tax][]"
                                                            class="form-select tax-select" multiple style="height: 50px;"
                                                            onchange="calculateRowAmount({{ $index }})">
                                                            @foreach($all_taxes as $tax)
                                                                <option value="{{ $tax->id }}" {{ in_array($tax->id, $taxIds) ? 'selected' : '' }} data-rate="{{ $tax->value }}">
                                                                    {{ $tax->name }} - {{ $tax->value }}%
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </td>
                                                    <td style="width:150px;">
                                                        <input type="text" name="dynamicFields[{{ $index }}][amount]"
                                                            class="form-control amount" value="{{ $item->total }}" readonly />
                                                    </td>
                                                    <td class="text-center align-middle" style="max-width: 50px;">
                                                        <a href="javascript:void(0);" onclick="removeRow({{ $index }})"
                                                            class="text-danger fs-5" title="Remove Row">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="row mt-5">
                                <div class="col-lg-6 mb-3 d-flex">
                                    <div class="col-lg-6">
                                        <label for="discount_type" class="form-label">Discount type:</label>
                                        <select name="discount_type" id="discount_type" class="form-select"
                                            onchange="calculateTotal()">
                                            <option value="">Select discount type</option>
                                            @foreach($discount_types as $type)
                                                <option value="{{ $type->id }}" {{ old('discount_type', $invoice->discount_type) == $type->id ? 'selected' : '' }}>
                                                    {{ $type->type }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('discount_type')
                                            <span class="text-danger">{{ $message }}</span>
                                        @enderror
                                    </div>

                                    <div class="col-lg-6">
                                        <label for="discount" class="form-label">Discount:</label>
                                        <input type="number" id="discount" name="discount" class="form-control"
                                            value="{{ old('discount', $invoice->discount) }}" onchange="calculateTotal()" {{ empty(old('discount_type', $invoice->discount_type)) ? 'readonly' : '' }}>
                                        @error('discount')
                                            <span class="text-danger">{{ $message }}</span>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-lg-5 mb-3">
                                    <div class="card shadow-lg">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Sub Total:</span>
                                                <span id="subTotalDisplay">{{ number_format($invoice->amount, 2) }} ₹</span>
                                            </div>
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Discount:</span>
                                                <span id="discountDisplay">{{ number_format($invoice->discount, 2) }}
                                                    ₹</span>
                                            </div>
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Tax:</span>
                                                <span
                                                    id="taxDisplay">{{ number_format($invoice->final_amount - $invoice->amount + $invoice->discount, 2) }}
                                                    ₹</span>
                                            </div>
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Total:</span>
                                                <span id="totalDisplay">{{ number_format($invoice->final_amount, 2) }}
                                                    ₹</span>
                                            </div>
                                            <input type="hidden" id="sub_total" name="sub_total"
                                                value="{{ $invoice->amount }}">
                                            <input type="hidden" id="discount_amt" name="discount_amt"
                                                value="{{ $invoice->discount }}">
                                            <input type="hidden" id="tax" name="tax"
                                                value="{{ $invoice->final_amount - $invoice->amount + $invoice->discount }}">
                                            <input type="hidden" id="total_amt" name="total_amt"
                                                value="{{ $invoice->final_amount }}">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <hr>

                            @if ($branch->loyalty_config == 'A')

                                <!-- Points Card -->
                                <div class="col-lg-12 mb-3 d-flex justify-content-between">
                                    <div class="col-md-3 mb-3 redeem_points current_point me-3" style="display: none">
                                        <label for="redeem_points" class="form-label">Redeem Points:</label>
                                        <input type="number" name="redeem_points" id="redeem_points" class="form-control"
                                            value="{{ old('redeem_points') }}">
                                        @error('redeem_points')
                                            <span class="text-danger">{{$message }}</span>
                                        @enderror
                                        <span class="text-danger error-feedback" style="display: none"></span>
                                    </div>
                                    <div class="card shadow-lg h-100 col-md-3 redeem_points" style="display: none">
                                        <div class="card-body d-flex flex-column justify-content-center">
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Earned Points:</span>
                                                <span id="earnPoints">0 <i class="fa-solid fa-coins text-warning"></i></span>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Redeemed Points:</span>
                                                <span id="redeemPoints">0 <i class="fa-solid fa-coins text-warning"></i></span>
                                            </div>
                                            <div class="d-flex justify-content-between">
                                                <span>Available Points:</span>
                                                <span id="availablePoints">0 <i
                                                        class="fa-solid fa-coins text-warning"></i></span>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="hidden" id="earn_point" name="earn_point" value="0">
                                    <input type="hidden" id="redeem_point" name="redeem_point" value="0">
                                    <input type="hidden" id="available_point" name="available_point" value="0">
                                </div>

                            @endif

                            <div>
                                @php
                                    $showNote = $branch->note_flag === 'A';
                                    $showTerm = $branch->terms_flag === 'A';
                                    $buttonLabel = 'Add ';
                                    if ($showNote && $showTerm) {
                                        $buttonLabel .= 'Note & Term';
                                    } elseif ($showNote) {
                                        $buttonLabel .= 'Note';
                                    } elseif ($showTerm) {
                                        $buttonLabel .= 'Terms';
                                    }
                                @endphp

                                @if ($showNote || $showTerm)
                                    {{--
                                    <hr> --}}
                                    <button type="button" onclick="toggleNotesAndTerms('{{$buttonLabel}}')"
                                        class="btn btn-primary" id="notesTermsBtn">
                                        <i class="fas fa-plus"></i> {{ $buttonLabel }}
                                    </button>
                                @endif

                                <div class="row mt-3" id="notesTermsSection" style="display: none;">
                                    @if ($showNote)
                                        <div class="col-lg-6">
                                            <label for="note" class="form-label">Note:</label>
                                            <textarea class="form-control" data-label='Note' name="note"
                                                id="note">{{ old('note') }}</textarea>
                                        </div>
                                    @endif

                                    @if ($showTerm)
                                        <div class="col-lg-6">
                                            <label for="term" class="form-label">Term:</label>
                                            <textarea class="form-control" data-label='Term' name="term"
                                                id="term">{{ old('term') }}</textarea>
                                        </div>
                                    @endif
                                </div>
                            </div>
                            <div class="modal-footer d-flex justify-content-between">
                                <div>
                                    <div class="d-flex justify-content-end align-items-center">
                                        <span class="me-3 fw-bold">Total Purchased Products Qty:</span>
                                        <span id="totalQuantity" class="badge bg-primary"
                                            style="font-size: 1.1rem;">0</span>
                                    </div>
                                </div>
                                <div>
                                    <button type="submit" id="submit" class="btn btn-primary">Update</button>
                                    <a href="{{ route('invoice-index') }}" class="btn btn-secondary">Cancel</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
@endsection

@push('scripts')
    <script>
        // Product data from backend
        const products = @json($products);
        const taxes = @json($all_taxes);
        const preSelected = @json($allTaxSelections);
        const defaultTaxIds = @json($default_taxes);
        const pointValue = @json($point_value);
        const currectInvoice = @json($redeem);
        const isDescription = @json($branch->inv_desc_flag);
        const ispoints = @json($branch->loyalty_config);
        const isAvl = @json($branch->avl_qty_flag);

        let avlPoint = 0;
        let redeemPoints = 0;


        let rowCount = {{ count($invoice->invoiceItems) }};
        let hasQuantityError = false;

        function preventFormSubmit(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                addProductRow();
                setTimeout(() => {
                    document.getElementById('product-code-input').focus();
                }, 1000);
            }
        }

        function addRow(event) {
            event.preventDefault();
            addProductRow();
            setTimeout(() => {
                document.getElementById('product-code-input').focus();
            }, 1000);
        }

        function addProductRow() {
            const productCode = document.getElementById('product-code-input').value;
            if (!productCode) {
                addEmptyRow();
                return;
            }

            const product = products.find(p => p.code === productCode);
            if (product) {
                const existingRow = findProductRow(product.id);

                if (existingRow) {
                    const qtyInput = existingRow.querySelector('.qty');
                    const currentQty = parseFloat(qtyInput.value) || 0;
                    qtyInput.value = currentQty + 1;
                    calculateRowAmount(existingRow.id.split('-')[1]);
                    checkQuantity(existingRow.id.split('-')[1]);
                } else {
                    addProductToTable(product);
                }

                document.getElementById('product-code-input').value = '';
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Product Not Found',
                    text: 'The product code you entered was not found in the system',
                    confirmButtonText: 'OK'
                });
            }
        }

        function findProductRow(productId) {
            const rows = document.querySelectorAll('#productRows tr');
            for (const row of rows) {
                const select = row.querySelector('.product-select');
                if (select && select.value == productId) {
                    return row;
                }
            }
            return null;
        }

        function addEmptyRow() {
            rowCount++;
            const row = `
                                            <tr id="row-${rowCount}">
                                                {{--<td>${rowCount}</td>--}}
                                                <td>
                                                    <div class="d-flex flex-column">
                                                    <select name="dynamicFields[${rowCount}][product]" class="form-select product-select" 
                                                            onchange="updateProductDetails(${rowCount})">
                                                        <option value="">Select Product</option>
                                                        ${products.map(p => {
                const name = p.branch.native_name_flag == 'A' ? (p.native_name ?? p.name) : p.name;
                return `<option value="${p.id}">${p.code} - ${name}</option>`;
            }).join('')}
                                                </select>
                                            ${isDescription === 'A' ? `
                                            <input type="text" name="dynamicFields[${rowCount}][description]"
                                                style="padding-left:10px !important;" class="form-control mt-1 description"
                                                id="description-${rowCount}" placeholder="Enter a Description">
                                        ` : ''}
                                        </div>
                                    </td>
                                    <td style="width:120px;">
                                        <input type="text" name="dynamicFields[${rowCount}][avl_qty]" class="form-control avl-qty" readonly />
                                    </td>
                                    <td style="width:120px;">
                                        <input type="text" name="dynamicFields[${rowCount}][qty]" class="form-control qty" 
                                                onchange="calculateRowAmount(${rowCount})" 
                                                oninput="checkQuantity(${rowCount})" />
                                        <div class="invalid-feedback quantity-error" style="display: none;">
                                            Quantity exceeds available stock!
                                        </div>
                                    </td>
                                    <td style="width:120px;">
                                        <input type="text" name="dynamicFields[${rowCount}][unit_price]" class="form-control unit-price"
                                                onchange="calculateRowAmount(${rowCount})" />
                                    </td>
                                    <td style="min-width: 200px;">
                                    <select name="dynamicFields[${rowCount}][tax][]" class="form-select tax-select" multiple
                                            style="height: 50px;"
                                            onchange="calculateRowAmount(${rowCount})">
                                        ${taxes.map(t => {
                return `<option value="${t.id}">${t.name} - ${t.value}%</option>`;
            }).join('')}
                                        </select>
                                    </td>
                                        <td style="width:150px;">
                                            <input type="text" name="dynamicFields[${rowCount}][amount]" class="form-control amount" readonly />
                                        </td>
                                        <td class="text-center align-middle">
                                                <a href="javascript:void(0);" onclick="removeRow(${rowCount})" class="text-danger fs-5" title="Remove Row">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                        </td>
                                            </tr>
                                        `;
            document.getElementById('productRows').insertAdjacentHTML('beforeend', row);
            $(`#row-${rowCount} .product-select`).select2({
                placeholder: "Select Product",
                width: '100%'
            });
            toggleTaxes();
        }

        function addProductToTable(product) {
            rowCount++;
            const row = `
                                    <tr id="row-${rowCount}">
                                        {{--<td>${rowCount}</td>--}}
                                        <td>
                                            <div class="d-flex flex-column">
                                            <select name="dynamicFields[${rowCount}][product]" class="form-select product-select" 
                                                    onchange="updateProductDetails(${rowCount})">
                                                <option value="">Select Product</option>
                                                ${products.map(p => `<option value="${p.id}" ${p.id == product.id ? 'selected' : ''}>${p.code} - ${p.branch.native_name_flag == 'A' ? (p.native_name ?? p.name) : p.name}</option>`).join('')}
                                            </select>
                                                ${isDescription === 'A' ? `
                                                <input type="text" name="dynamicFields[${rowCount}][description]"
                                                    style="padding-left:10px !important;" class="form-control mt-1 description"
                                                    id="description-${rowCount}" placeholder="Enter a Description">
                                            ` : ''}
                                                </div>
                                        </td>
                                        <td style="width:120px;">
                                            <input type="text" name="dynamicFields[${rowCount}][avl_qty]" class="form-control avl-qty" 
                                                    value="${product.qty}" readonly />
                                        </td>
                                        <td style="width:120px;">
                                            <input type="text" name="dynamicFields[${rowCount}][qty]" class="form-control qty" 
                                                    value="1" onchange="calculateRowAmount(${rowCount})" 
                                                    oninput="checkQuantity(${rowCount})" />
                                            <div class="invalid-feedback quantity-error" style="display: none;">
                                                Quantity exceeds available stock!
                                            </div>
                                        </td>
                                        <td style="width:120px;">
                                            <input type="text" name="dynamicFields[${rowCount}][unit_price]" class="form-control unit-price" 
                                                    value="${product.unit_price}" onchange="calculateRowAmount(${rowCount})" />
                                        </td>
                                        <td style="min-width: 200px;">
                                            <select name="dynamicFields[${rowCount}][tax][]" class="form-select tax-select" multiple
                                                    style="height: 50px;"
                                                    onchange="calculateRowAmount(${rowCount})">
                                                ${taxes.map(t => {
                // Only select if it's in the product's taxes or default taxes
                const isProductTax = product.taxes ? product.taxes.includes(t.id) : false;
                return `<option value="${t.id}" ${isProductTax ? 'selected' : ''}>${t.name} - ${t.value}%</option>`;
            }).join('')}
                                                </select>
                                            </td>
                                            <td style="width:150px;">
                                                <input type="text" name="dynamicFields[${rowCount}][amount]" class="form-control amount" 
                                                        value="${product.unit_price}" readonly />
                                            </td>
                                                <td class="text-center align-middle">
                                                <a href="javascript:void(0);" onclick="removeRow(${rowCount})" class="text-danger fs-5" title="Remove Row">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                                </tr>
                                            `;
            document.getElementById('productRows').insertAdjacentHTML('beforeend', row);
            $(`#row-${rowCount} .product-select`).select2({
                placeholder: "Select Product",
                width: '100%'
            });
            calculateRowAmount(rowCount);
            checkQuantity(rowCount);

            toggleTaxes();
        }

        // function updateProductDetails(rowId) {
        //     const row = document.getElementById(`row-${rowId}`);
        //     const productId = row.querySelector('.product-select').value;
        //     const product = products.find(p => p.id == productId);

        //     if (product) {
        //         row.querySelector('.avl-qty').value = product.qty;
        //         row.querySelector('.qty').value = 1;
        //         row.querySelector('.unit-price').value = product.unit_price;
        //         if (isDescription == 'A') {
        //             row.querySelector('.description').value = '';
        //         }
        //         calculateRowAmount(rowId);
        //         checkQuantity(rowId);
        //     } else {
        //         row.querySelector('.avl-qty').value = '';
        //         row.querySelector('.qty').value = '';
        //         row.querySelector('.unit-price').value = '';
        //         calculateRowAmount(rowId);
        //     }
        // }

        function updateProductDetails(rowId) {
            const row = document.getElementById(`row-${rowId}`);
            const productSelect = row.querySelector('.product-select');
            const productId = productSelect.value;
            const product = products.find(p => p.id == productId);

            // First remove any existing duplicate warnings and highlighting
            removeDuplicateWarnings();
            document.querySelectorAll('.duplicate-row').forEach(row => {
                row.classList.remove('duplicate-row');
            });

            if (product) {
                // Update product details regardless of duplicates
                row.querySelector('.avl-qty').value = product.qty;
                row.querySelector('.qty').value = 1;
                row.querySelector('.unit-price').value = product.unit_price;
                calculateRowAmount(rowId);
                checkQuantity(rowId);

                // Check for duplicates after updating
                checkForDuplicates(rowId);
            }
        }

        function checkForDuplicates(rowId) {
            const row = document.getElementById(`row-${rowId}`);
            const productId = row.querySelector('.product-select').value;

            if (!productId) return;

            const allRows = document.querySelectorAll('#productRows tr');
            let duplicateFound = false;

            allRows.forEach(existingRow => {
                const existingRowId = existingRow.id.split('-')[1];
                if (existingRowId != rowId) {
                    const existingProductId = existingRow.querySelector('.product-select').value;
                    if (existingProductId == productId) {
                        duplicateFound = true;
                        $('.addRow').prop('disabled', true);
                        existingRow.classList.add('duplicate-row');
                        showDuplicateWarning(row, existingRow);
                    }
                    $('.addRow').prop('disabled', true);
                }
            });
            if (duplicateFound) {
                $('.addRow').prop('disabled', true);
                document.getElementById('submit').disabled = true;
            } else {
                $('.addRow').prop('disabled', false);
                document.getElementById('submit').disabled = false;
            }
        }

        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.product-select').forEach(select => {
                select.addEventListener('change', function () {
                    const rowId = this.closest('tr').id.split('-')[1];
                    // Remove warnings when changing selection
                    removeDuplicateWarnings();
                    document.querySelectorAll('.duplicate-row').forEach(row => {
                        row.classList.remove('duplicate-row');
                    });
                    // Check again if the new selection is a duplicate
                    setTimeout(() => checkForDuplicates(rowId), 10);
                });
            });
        });

        function showDuplicateWarning(row1, row2) {
            // Only add if not already present
            if (!row1.querySelector('.duplicate-warning')) {
                const warning1 = document.createElement('div');
                warning1.className = 'duplicate-warning text-danger small mt-1';
                warning1.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Duplicate product';
                row1.querySelector('td').appendChild(warning1);
            }

            if (!row2.querySelector('.duplicate-warning')) {
                const warning2 = document.createElement('div');
                warning2.className = 'duplicate-warning text-danger small mt-1';
                warning2.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Duplicate product';
                row2.querySelector('td').appendChild(warning2);
            }
        }

        function removeDuplicateWarnings() {
            document.querySelectorAll('.duplicate-warning').forEach(warning => {
                warning.remove();
            });
        }

        function checkQuantity(rowId) {
            const row = document.getElementById(`row-${rowId}`);
            if (!row) return true; // Row might have been removed

            const qtyInput = row.querySelector('.qty');
            const avlQty = parseFloat(row.querySelector('.avl-qty').value) || 0;
            const qty = parseFloat(qtyInput.value) || 0;
            const errorElement = row.querySelector('.quantity-error');

            if (isAvl != 'A') {
                if (qty > avlQty) {
                    qtyInput.classList.add('is-invalid');
                    errorElement.style.display = 'block';
                    hasQuantityError = true;
                    return false;
                } else {
                    qtyInput.classList.remove('is-invalid');
                    errorElement.style.display = 'none';

                    // Check all rows for errors
                    hasQuantityError = false;
                    document.querySelectorAll('#productRows tr').forEach(r => {
                        const rQtyInput = r.querySelector('.qty');
                        const rAvlQty = parseFloat(r.querySelector('.avl-qty').value) || 0;
                        const rQty = parseFloat(rQtyInput?.value) || 0;

                        if (rQty > rAvlQty) {
                            hasQuantityError = true;
                        }
                    });

                    return true;
                }
            }
        }

        function calculateRowAmount(rowId) {
            const row = document.getElementById(`row-${rowId}`);
            if (!row) return; // Row might have been removed

            const qty = parseFloat(row.querySelector('.qty').value) || 0;
            const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
            const amount = qty * unitPrice;

            // Calculate tax
            const taxSelect = row.querySelector('.tax-select');
            const selectedTaxes = Array.from(taxSelect.selectedOptions).map(opt => parseInt(opt.value));
            let taxRate = 0;

            selectedTaxes.forEach(taxId => {
                if (taxId && taxId !== 'no-tax') {
                    const tax = taxes.find(t => t.id == taxId);
                    if (tax) taxRate += tax.value;
                }
            });

            const taxAmount = amount * (taxRate / 100);
            const totalWithTax = amount + taxAmount;

            row.querySelector('.amount').value = amount.toFixed(2);
            calculateTotal();
        }

        function calculateTotal() {
            let subTotal = 0;
            let totalTax = 0;
            let totalQuantity = 0;
            const redeem = parseFloat($('#redeem_points').val()) * pointValue || 0;


            document.querySelectorAll('#productRows tr').forEach(row => {
                const amount = parseFloat(row.querySelector('.amount').value) || 0;
                const qty = parseFloat(row.querySelector('.qty').value) || 0;
                const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
                const rowAmount = qty * unitPrice;
                totalQuantity += qty;
                subTotal += rowAmount;

                // Calculate tax for this row
                const taxSelect = row.querySelector('.tax-select');
                const selectedTaxes = Array.from(taxSelect.selectedOptions).map(opt => parseInt(opt.value));
                let taxRate = 0;

                selectedTaxes.forEach(taxId => {
                    if (taxId && taxId !== 'no-tax') {
                        const tax = taxes.find(t => t.id == taxId);
                        if (tax) taxRate += tax.value;
                    }
                });

                totalTax += rowAmount * (taxRate / 100);
            });

            // Calculate discount
            const discountType = document.getElementById('discount_type').value;
            const discountValue = parseFloat(document.getElementById('discount').value) || 0;
            let discountAmount = 0;

            var subtotalWithTax = subTotal + totalTax;

            if (discountType == 1) {
                discountAmount = discountValue;
            } else if (discountType == 2) {
                discountAmount = subtotalWithTax * (discountValue / 100);
            }

            let totals = subtotalWithTax - discountAmount;
            let total = totals - redeem;

            // Update display
            document.getElementById('subTotalDisplay').textContent = subTotal.toFixed(2) + ' ₹';
            document.getElementById('discountDisplay').textContent = discountAmount.toFixed(2) + ' ₹';
            document.getElementById('taxDisplay').textContent = totalTax.toFixed(2) + ' ₹';
            document.getElementById('totalDisplay').textContent = Math.floor(total).toFixed(2) + ' ₹';
            document.getElementById('totalQuantity').textContent = totalQuantity;

            // Update hidden fields
            document.getElementById('sub_total').value = subTotal.toFixed(2);
            document.getElementById('discount_amt').value = discountAmount.toFixed(2);
            document.getElementById('tax').value = totalTax.toFixed(2);
            document.getElementById('total_amt').value = Math.floor(total).toFixed(2);
        }

        function toggleTaxes() {
            const gstValue = document.getElementById('gst').value;
            const taxSelects = document.querySelectorAll('.tax-select');

            taxSelects.forEach(select => {
                const rowId = select.closest('[id^="row-"]')?.id?.split('-')[1];

                if (gstValue === 'N') {
                    select.innerHTML = '<option value="no-tax" selected>No Tax</option>';
                    select.disabled = true;
                } else {
                    select.disabled = false;

                    let selectedIds = [];

                    if (rowId in preSelected && Array.isArray(preSelected[rowId])) {
                        selectedIds = preSelected[rowId].map(Number);
                    } else {
                        selectedIds = defaultTaxIds.map(Number);
                    }

                    select.innerHTML = taxes.map(tax => {
                        const isSelected = selectedIds.includes(Number(tax.id));
                        return `<option value="${tax.id}" ${isSelected ? 'selected' : ''} data-rate="${tax.value}">${tax.name} - ${tax.value}%</option>`;
                    }).join('');
                }
            });

            calculateTotal();
        }

        function toggleNotesAndTerms(baseLabel) {
            const section = document.getElementById('notesTermsSection');
            const btn = document.getElementById('notesTermsBtn');

            const isVisible = section.style.display === 'flex' || section.style.display === 'block';

            section.style.display = isVisible ? 'none' : 'flex';

            if (!isVisible) {
                btn.innerHTML = `<i class="fas fa-minus"></i> Remove ${baseLabel}`;
            } else {
                btn.innerHTML = `<i class="fas fa-plus"></i> ${baseLabel}`;
            }
        }

        function removeRow(rowId) {
            const row = document.getElementById(`row-${rowId}`);  // Changed from rowCount to rowId
            if (row) {
                // Destroy Select2 instance before removing the row
                const select = row.querySelector('.product-select');
                if (select) {
                    $(select).select2('destroy');
                }

                row.remove();
                calculateTotal();

                // Check for quantity errors after removal
                hasQuantityError = false;
                document.querySelectorAll('#productRows tr').forEach(r => {
                    const rQtyInput = r.querySelector('.qty');
                    const rAvlQty = parseFloat(r.querySelector('.avl-qty').value) || 0;
                    const rQty = parseFloat(rQtyInput?.value) || 0;

                    if (rQty > rAvlQty) {
                        hasQuantityError = true;
                    }
                });
            }
        }

        function validateForm(event) {
            // First check all quantities
            hasQuantityError = false;
            document.querySelectorAll('#productRows tr').forEach(row => {
                const rowId = row.id.split('-')[1];
                checkQuantity(rowId);
            });

            if (hasQuantityError) {
                event.preventDefault();

                const firstError = document.querySelector('.is-invalid');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }

                return false;
            }

            return true;
        }

        $(document).ready(function () {

            if (ispoints == 'A') {
                fetchClientPoints();
            }

            $('.product-select').select2({
                placeholder: "Select Product",
                width: '100%'
            });

            if (!document.getElementById('invoice_date').value) {
                document.getElementById('invoice_date').valueAsDate = new Date();
            }
            if (!document.getElementById('due_date').value) {
                document.getElementById('due_date').valueAsDate = new Date();
            }

            document.getElementById('discount_type').addEventListener('change', function () {
                document.getElementById('discount').readOnly = !this.value;
                calculateTotal();
            });

            document.querySelector('form').addEventListener('submit', validateForm);

            toggleTaxes();
            calculateTotal();

            document.querySelectorAll('#productRows tr').forEach(row => {
                const rowId = row.id.split('-')[1];
                checkQuantity(rowId);
            });

            redeemCal();


        });

        function redeemCal() {
            const enteredPoints = parseFloat($('#redeem_points').val()) || 0;

            const errorElement = $('.redeem_points .error-feedback');
            errorElement.text('').hide();
            $('#redeem_points').removeClass('is-invalid');

            $('#redeem_point').val(enteredPoints);

            calculateTotal();
            return true;
        }

        $('#redeem_points').on('change input', function () {

            let entered_points = parseFloat($(this).val()) || 0;
            diff = entered_points - (currectInvoice && currectInvoice.points) || 0;
            total_points = avlPoint + (currectInvoice && currectInvoice.points) || 0;
            currentPoint = avlPoint - diff;
            redeemedPoints = redeemPoints + diff;

            const errorElement = $('.redeem_points .error-feedback');
            errorElement.text('').hide();
            $('#redeem_points').removeClass('is-invalid');

            if (entered_points > total_points) {
                errorElement.text('Redeem points cannot exceed available points').show();
                $('#redeem_points').addClass('is-invalid');
                $('#redeem_points').val(avlPoint);
                return false;
            }

            $('#availablePoints').text(currentPoint + ' ');
            $('#redeemPoints').text(redeemedPoints + ' ');
            $('#availablePoints,#redeemPoints').append('<i class="fa-solid fa-coins text-warning"></i>');

            calculateTotal();
        });
        function fetchClientPoints() {
            let errorElement = $("#client_num_error");
            let clientID = $('#client_num').data('clientid');

            let invoiceID = $('#invoice_id').val();

            if (!clientID) {
                errorElement.text("Invalid client ID").show();
                return;
            } else {
                errorElement.hide();
            }

            $.ajax({
                url: '{{ route('invoice-client') }}',
                type: 'GET',
                data: { clientID: clientID, invoiceID: invoiceID },
                success: function (data) {

                    $('.redeem_points').hide();

                    let earnPoints = data.earnPoints;
                    redeemPoints = data.redeemPoints;
                    avlPoint = data.availablePoints;

                    $('#earnPoints').text(earnPoints + ' ');
                    $('#redeemPoints').text(redeemPoints + ' ');
                    $('#availablePoints').text(avlPoint + ' ');
                    $('#redeem_points').val((currectInvoice && currectInvoice.points) || 0);

                    $('#earnPoints, #redeemPoints, #availablePoints').append('<i class="fa-solid fa-coins text-warning"></i>');

                    $('#earn_point').val(earnPoints);
                    $('#redeem_point').val(redeemPoints);
                    $('#available_point').val(avlPoint);

                    // if (avlPoint > 0) {
                    $('.redeem_points').show();
                    // }
                    redeemCal();
                },
                error: function (xhr) {
                    console.log(xhr);
                }
            });
        }

        $('#gst').on('change', function () {
            toggleTaxes();
        });
    </script>
@endpush