@extends('layouts.layoutapp')

@section('content')
<style>
    /* .form-control{
        padding-left: 10px !important;
    } */
</style>
  <div class="row">
        <div class="col-12">
            <div class="card me-2">
                    <div class="card-header pb-0">
                        <div class="d-flex justify-content-between flex-row">
                            <div>
                                <h5 class="mb-0">Convert Quotes To Invoice</h5>
                            </div>
                        </div>
                    </div>

                    <form action="{{ route('quotes-update') }}" method="POST">
                        @csrf
                        <input type="hidden" name="id" value="{{ $quote->id }}" />
                        <div class="card-body">
                            <div class="row">
                                <div class="col-lg-3 mb-3">
                                    <label for="client_id" class="form-label">
                                        Client Name:
                                    </label>
                                    <input name="client_id" id="client_id" class="form-control" disabled
                                        value="{{ $quote->client->user->name ?? '' }}" />
                                    <input type="hidden" name="client_id" value="{{ $quote->client_id }}" />
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="client_num" class="form-label">
                                        Client Number:
                                    </label>
                                    <div id="client_select">
                                        <select name="client_num" id="client_num_select" class="form-select" disabled>
                                            @forelse ($clients as $data)
                                                <option value="{{ $data->user->phone }}" {{ $quote->client->user->phone == $data->user->phone ? 'selected' : '' }}>
                                                    {{ $data->user->phone }}
                                                </option>
                                            @empty
                                                <option>No Client found</option>
                                            @endforelse
                                        </select>
                                    </div>
                                    @error('client_num')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="quote_id" class="form-label">
                                        Quotes Id:
                                    </label>
                                    <input type="text" id="quote_id" name="quote_id" class="form-control"
                                        value="{{ $quote->quote_id }}" readonly required />
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="quote_date" class="form-label">
                                        Quotes Date:
                                    </label>
                                    <input type="date" id="quote_date" name="quote_date" value="{{ $quote->quote_date }}"
                                        class="form-control" required />
                                </div>
                                <div class="col-lg-3 mb-3">
                                    <label for="due_date" class="form-label">
                                        Due Date:
                                    </label>
                                    <input type="date" id="due_date" name="due_date" class="form-control"
                                        value="{{ $quote->due_date }}" required />
                                </div>
                                @if ($branch->non_gst == 'A')
                                    <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') == 'Y' ? 'selected' : '' }}>GST</option>
                                        <option value="N" {{ old('gst') == 'N' ? 'selected' : '' }} selected>Non-GST</option>
                                    </select>
                                    @error('gst')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                                @else
                                    <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') == 'Y' ? 'selected' : '' }} selected>GST</option>
                                        <option value="N" {{ old('gst') == 'N' ? 'selected' : '' }} >Non-GST</option>
                                    </select>
                                    @error('gst')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                                @endif
                                
                                <div class="col-lg-3 mb-3">
                                    <label for="status" class="form-label">
                                        Status
                                    </label>
                                    <select name="status" id="status" class="form-select" required>
                                        <option value="1" {{ $quote->status == 1 ? 'selected' : '' }}>
                                            Draft
                                        </option>
                                        <option value="2" {{ $quote->status == 2 ? 'selected' : '' }}>
                                            Partially Completed
                                        </option>     
                                        <option value="3" {{ $quote->status == 3 ? 'selected' : '' }}>
                                            Completed
                                        </option>                                   
                                    </select>
                                </div>
                            </div>
                            <hr />
                            <div>
                                <h5>Product Details:</h5>
                                <div class="row align-items-center">
                                    <div class="col-lg-4">
                                        <button type="button" id="add-row" class="btn btn-primary">
                                            <i class="fas fa-plus"></i>
                                            Add Row
                                        </button>
                                    </div>
                                </div>

                                <div class="table-responsive">
                                    <table class="table-bquoteed table-striped table" id="products-table">
                                        <thead class="thead-dark">
                                            <tr>
                                                <th>#</th>
                                                <th>Product</th>
                                                @if (Auth::user()->user_flg !== 'C')
                                                    <th>Avl. Qty</th>
                                                @endif

                                                <th>Qty</th>
                                                <th>Unit Price</th>
                                                <th>Tax</th>
                                                <th>Amount</th>
                                                <th></th>
                                            </tr>
                                        </thead>
                                        <tbody id="productRows">
                                            @foreach ($quote->quotesItem as $index => $item)
                                                @php
                                                    $product = $products->firstWhere('id', $item->product_id);
                                                    $available_qty = $product ? $product->qty : 0;
                                                @endphp

                                                <tr class="product-row" id="row-{{ $index + 1 }}">
                                                    <td>{{ $index + 1 }}</td>
                                                    <td style="min-width: 200px;">
                                                        <select name="products[{{ $index + 1 }}][id]"
                                                            class="form-select product-select" required>
                                                            <option value="">Select Product</option>
                                                            @foreach ($products as $product)
                                                                <option value="{{ $product->id }}"
                                                                    data-available="{{ $product->qty }}"
                                                                    data-amount="{{ $item->total }}"
                                                                    data-price="{{ $product->unit_price }}" {{ $item->product_id == $product->id ? 'selected' : '' }}>
                                                                    {{ $product->code }}-{{ $product->branch->native_name_flag == 'A' ? ($product->native_name ?? $product->name) : $product->name }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        <div class="duplicate-warning-container"></div>
                                                    </td>
                                                    @if (Auth::user()->user_flg !== 'C')
                                                        <td>
                                                            <input type="text" class="form-control available-qty" readonly
                                                                value="{{ $available_qty }}" />
                                                        </td>
                                                    @endif

                                                    <td>
                                                        <input type="number" name="products[{{ $index + 1 }}][qty]"
                                                            class="form-control qty" min="1" value="{{ $item->quantity }}"
                                                            required />
                                                        <div class="invalid-feedback quantity-error" style="display: none">
                                                            Quantity exceeds available stock
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <input type="number" name="products[{{ $index + 1 }}][unit_price]"
                                                            class="form-control unit-price" min="0" step="0.01"
                                                            value="{{ $item->price }}" required readonly />
                                                    </td>
                                                    <td style="min-width: 200px;">
                                                        <select name="products[{{ $index + 1 }}][tax][]"
                                                            class="form-select tax-select" multiple
                                                            style="height: 50px;>
                                                            @foreach ($all_taxes as $tax)
                                                                <option value="{{ $tax->id }}"
                                                                    {{ in_array($tax->id, $default_taxes) ? 'selected' : '' }}
                                                                    data-rate="{{ $tax->value }}">
                                                                    {{ $tax->name }} - {{ $tax->value }}%
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control amount" style="padding-left: 10px !important;" readonly
                                                            value="{{ $item->total }}" />
                                                    </td>
                                                     <td class="text-center align-middle">
                   
                      <a href="javascript:void(0);"
                                                            class="text-danger fs-5 remove-row" title="Remove Row">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="row d-flex justify-content-between">
                                {{-- <div class="col-lg-7 mb-3">
                                    <div class="card shadow-lg">
                                        <div class="d-flex justify-content-between px-3 pt-3 pb-0">
                                            <h5 class="px-3 pt-3 pb-0">Address</h5>
                                            <div>
                                                <button type="button" class="btn btn-primary btn-sm mb-3" data-bs-toggle="modal"
                                                    data-bs-target="#addAddressModal">
                                                    Add New Address
                                                </button>
                                            </div>
                                        </div>
                                        <div class="card-body address-body px-3 pb-2 pt-2"></div>
                                    </div>
                                </div> --}}
                                <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="calculateTotals()">
                                            <option value="">Select discount type</option>
                                            @foreach($discount_types as $dis_type)
                                                <option value="{{ $dis_type->id }}" {{ old('discount_type', $quote->discount_type) == $dis_type->id ? 'selected' : '' }}>
                                                    {{ $dis_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', $quote->discount) }}" onchange="calculateTotals()" {{ empty(old('discount', $quote->discount)) ? '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">{{ $quote->sub_total }} ₹</span>
                                            </div>
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Tax:</span>
                                                <span id="taxDisplay">0.00 ₹</span>
                                            </div>
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Discount:</span>
                                                <span id="discountDisplay">0.00 ₹</span>
                                            </div>
                                            <div class="d-flex justify-content-between pl-5">
                                                <span>Total:</span>
                                                <span id="totalDisplay">{{ $quote->total_amount }} ₹</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div>
                               <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap">
                                    <div class="d-flex align-items-center gap-3 flex-wrap">
                                        <!-- Label -->
                                        <h5 class="mb-0">Payment Details:</h5>

                                        <!-- Tendered Amount Input -->
                                        <input type="number" step="0.01" name="tendered_amount" id="tendered_amount"
                                            class="form-control w-auto" style="min-width: 200px;"
                                            value="{{ old('tendered_amount') }}" placeholder="Enter tendered amount">
                                        @error('tendered_amount')
                                            <span class="text-danger">{{ $message }}</span>
                                        @enderror
                                    </div>

                                    <!-- Extra Amount Badge (Right Side) -->
                                    <span class="badge bg-primary extra_amount">Extra Amount: ₹ 0.00</span>
                                </div>
                                <div class="row">
                                    <!-- Payment Method Fields -->
                                    <div class="col-lg-12">
                                        <div class="row">
                                            
                                            <div class="col-md-4 mb-2">
                                                <label for="upi" class="form-label">UPI:</label>
                                                <input type="text" name="upi" id="upi" class="form-control"
                                                    value="{{ old('upi') }}">
                                                @error('upi')
                                                    <span class="text-danger">{{ $message }}</span>
                                                @enderror
                                            </div>
                                            <div class="col-md-4 mb-2">
                                                <label for="cash" class="form-label">Cash:</label>
                                                <input type="text" name="cash" id="cash" class="form-control"
                                                    value="{{ old('cash') }}">
                                                @error('cash')
                                                    <span class="text-danger">{{ $message }}</span>
                                                @enderror
                                            </div>
                                            <div class="col-md-4 mb-2">
                                                <label for="online" class="form-label">Online:</label>
                                                <input type="text" name="online" id="online" class="form-control"
                                                    value="{{ old('online') }}">
                                                @error('online')
                                                    <span class="text-danger">{{ $message }}</span>
                                                @enderror
                                            </div>

                                            @if ($errors->has('payment_total'))
                                                <div class="col-12 text-danger">
                                                    {{ $errors->first('payment_total') }}
                                                </div>
                                            @endif
                                        </div>
                                    </div>

                                    @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>
                            </div>

                            <input type="hidden" id="sub_total" name="sub_total" value="{{ $quote->sub_total }}" />
                            <input type="hidden" id="tax" name="tax" value="0" />
                            <input type="hidden" id="discount_amt" name="discount_amount" value="0" />
                            <input type="hidden" id="total_amt" name="total_amount" value="{{ $quote->total_amount }}" />
                            <input type="hidden" id="hidden-total-amt" name="type" value="{{ $type }}" />

                            <div class="modal-footer d-flex justify-content-between mt-4">
                                 <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">
                                    Convert
                                </button>
                                <a href="{{ route('quotes-index') }}" class="btn btn-secondary">
                                    Cancel
                                </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
@endsection

@push('scripts')
    <script>
        const taxes = @json($all_taxes);
        const defaultTaxIds = @json($default_taxes);
        const pointValue = @json($branch->point_redemption);
        const clientRedeemId = @json($quote->client_id);
        const isLoyalty = @json($branch->loyalty_config);
         const isAvl = @json($branch->avl_qty_flag);
         
        let avlPoint = 0;
        let redeemPoints = 0;

        $(document).ready(function () {
            let rowCount = {{ count($quote->quotesItem) }};
            const isClientUser = {{ Auth::user()->user_flg === 'C' ? 'true' : 'false' }};
            
            fetchClientAddress($('#client_num_select').val());
            toggleTaxes();
            calculateTotals();

            // Initialize existing rows
            $('.product-row').each(function() {
                const row = $(this);
                const qty = parseFloat(row.find('.qty').val()) || 0;
                const unitPrice = parseFloat(row.find('.unit-price').val()) || 0;
                const amount = qty * unitPrice;
                
                // Calculate tax for existing rows
                calculateRowTax(row);
            });

            // Add row button
            $('#add-row').click(function () {
                rowCount++;
                const rowId = rowCount;
                const row = `
                    <tr class="product-row" id="row-${rowId}">
                       <td>${rowId}</td>
                        <td style="min-width: 200px;">
                            <select name="products[${rowId}][id]" class="form-select product-select" required>
                                <option value="">Select Product</option>
                                @foreach ($products as $product)
                                    <option value="{{ $product->id }}" 
                                            data-available="{{ $product->qty }}" 
                                            data-amount="0" 
                                            data-price="{{ $product->unit_price }}">
                                        {{ $product->code }}-{{ $product->branch->native_name_flag == 'A' ? ($product->native_name ?? $product->name) : $product->name }}
                                    </option>
                                @endforeach
                            </select>
                            <div class="duplicate-warning-container"></div>
                        </td>
                        ${!isClientUser ? `<td>
                            <input type="text" class="form-control available-qty" readonly>
                        </td>` : ''}
                        <td>
                            <input type="number" name="products[${rowId}][qty]" 
                                   class="form-control qty" step="1" min="1" value="1" required>
                            ${!isClientUser ? `<div class="invalid-feedback quantity-error" style="display: none;">
                                Quantity exceeds available stock
                            </div>` : ''}
                        </td>
                        <td>
                            <input type="number" name="products[${rowId}][unit_price]" 
                                   class="form-control unit-price" min="0" step="0.01" required readonly>
                        </td>
                        <td style="min-width: 200px;">
                            <select name="products[${rowId}][tax][]" class="form-select tax-select" multiple
                            style="height: 50px;>
                            ${taxes.map(t => {
                                const taxId = t.id;
                                const isDefault = defaultTaxIds.includes(taxId);
                                return `<option value="${t.id}" ${isDefault ? 'selected' : ''} data-rate="${t.value}">
                                    ${t.name} - ${t.value}%
                                </option>`;
                            }).join('')}
                            </select>
                        </td>
                        <td>
                            <input type="text" class="form-control amount" style="padding-left: 10px !important;" readonly value="0.00">
                        </td>
                         <td class="text-center align-middle">
                   
                      <a href="javascript:void(0);"
                                                            class="text-danger fs-5 remove-row" title="Remove Row">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                    </td>
                    </tr>
                `;
                $('#productRows').append(row);
                 $('#products-table tbody tr:last .product-select').select2({
                    placeholder: "Select Product",
                    width: '100%'
                });
                // Initialize tax select for new row
                const newRow = $('#row-' + rowId);
                toggleTaxesForRow(newRow);
            });
            $('.product-select').select2({
                placeholder: "Select Product",
                width: '100%'
            });
            // Remove row
            $(document).on('click', '.remove-row', function () {
                $(this).closest('tr').remove();
                calculateTotals();
                renumberRows();
            });

            // Product select change
            // $(document).on('change', '.product-select', function () {
            //     const row = $(this).closest('tr');
            //     const selectedOption = $(this).find('option:selected');
            //     const price = selectedOption.data('price') || 0;
            //     const availableQty = selectedOption.data('available') || 0;
                
            //     row.find('.unit-price').val(price);
            //     if (!isClientUser) {
            //         row.find('.available-qty').val(availableQty);
            //     }
                
            //     // Reset quantity to 1 when product changes
            //     row.find('.qty').val(1);
                
            //     // Calculate row amount
            //     calculateRowTax(row);
            // });
            $(document).on('change', '.product-select', function () {
                const row = $(this).closest('tr');
                const selectedOption = $(this).find('option:selected');
                const price = selectedOption.data('price') || 0;
                const availableQty = selectedOption.data('available') || 0;
                const productId = $(this).val();

                row.find('.unit-price').val(price);
                if (!isClientUser) {
                    row.find('.available-qty').val(availableQty);
                }
                row.find('.qty').val(1);

                $('.duplicate-warning').remove();
                $('.duplicate-row').removeClass('duplicate-row');

                if (productId) {
                    let duplicateFound = false;

                    $('.product-select').each(function () {
                        if ($(this).val() === productId && $(this).closest('tr')[0] !== row[0]) {
                            duplicateFound = true;
                            row.addClass('duplicate-row');
                            $(this).closest('tr').addClass('duplicate-row');

                            const warningHTML = `
                                <div class="duplicate-warning text-danger small mt-1">
                                    <i class="fas fa-exclamation-triangle"></i> Duplicate product selected
                                </div>
                            `;

                            row.find('td:eq(1)').append(warningHTML);
                            $(this).closest('tr').find('td:eq(1)').append(warningHTML);
                        }
                    });

                    $('#add-row, #submit').prop('disabled', duplicateFound);
                }

            calculateRowTax(row);
            });

            // Quantity or unit price change
            $(document).on('change input', '.qty, .unit-price', function () {
                const row = $(this).closest('tr');
                calculateRowTax(row);
            });

            // Tax select change
            $(document).on('change', '.tax-select', function() {
                const row = $(this).closest('tr');
                calculateRowTax(row);
            });

            // Discount type or amount change
            $(document).on('change', '#discount_type', function() {
                
                const discountType = $(this).val();
                const discount = $('#discount');               
                
                if (discountType) {
                    discount.prop('readonly', false);
                } else {
                    discount.prop('readonly', true).val('');
                }
                
                calculateTotals();
            });
            
            $(document).on('input', '#discount', function() {
                calculateTotals();
            });
                      
            // Renumber rows
            function renumberRows() {
                let count = 1;
                $('.product-row').each(function () {
                    $(this).find('td:first').text(count);
                    // Update the name attributes to maintain sequential numbering
                    $(this).find('select, input').each(function() {
                        const name = $(this).attr('name');
                        if (name) {
                            $(this).attr('name', name.replace(/products\[\d+\]/, `products[${count}]`));
                        }
                    });
                    count++;
                });
            }

            // Form submission handler
            $('form').on('submit', function (e) {
                if (!isClientUser) {
                    let hasError = false;

                    $('.product-row').each(function () {
                        const row = $(this);
                        const qty = parseFloat(row.find('.qty').val()) || 0;
                        const available = parseFloat(row.find('.available-qty').val()) || 0;
                        const errorDiv = row.find('.quantity-error');

                        if(isAvl !='A' ){
                        if (qty > available) {
                            row.find('.qty').addClass('is-invalid');
                            errorDiv.show().text('Quantity exceeds available stock.');
                            hasError = true;
                        } else {
                            row.find('.qty').removeClass('is-invalid');
                            errorDiv.hide();
                        }
                    }
                    });

                    if (hasError) {
                        e.preventDefault();
                        Swal.fire({
                            icon: 'error',
                            title: 'Quantity Error',
                            text: 'Please correct the quantities that exceed available stock before submitting.',
                            confirmButtonText: 'OK'
                        });
                        return false;
                    }
                }

                return true;
            });

            function fetchClientAddress(clientId) {
                if (!clientId) return;

                $.ajax({
                    url: `/get-client-address/${clientId}`,
                    type: 'GET',
                    success: function (data) {
                        let addressHtml = '';

                        if (data.address.length > 0) {
                            data.address.forEach(function (address, index) {
                                const isChecked = address.oprtnl_flag === 'A' ? 'checked' : '';
                                const displayAddress = address.address ?? 'No Address Provided';

                                addressHtml += `
                                    <div class="mb-3 position-relative">
                                        <label class="card p-3 position-relative shadow-sm address-card" style="cursor: pointer; width: 100%;">
                                            <span class="position-absolute top-50 end-0 translate-middle-y me-3 fa-lg text-danger remove-address-icon"
                                                style="z-index: 2; cursor: pointer;"
                                                data-address-id="${address.id}"
                                                data-client-id="${address.client_id}">
                                                <i class="fas fa-trash"></i>
                                            </span>
                                             <input type="radio" name="selected_address" class="position-absolute top-50 start-0 translate-middle-y ms-3" 
                                                  id="address_${index}" value="${address.id}" data-client-id="${address.client_id}" ${isChecked}>

                                            <div class="card-body p-0 px-3">
                                                <p class="mb-0 text-dark">${displayAddress}</p>
                                            </div>
                                        </label>
                                    </div>
                                `;
                            });
                        } else {
                            addressHtml = '<p class="text-muted">No addresses found for this client.</p>';
                        }

                        $('.address-body').html(addressHtml);
                    },
                    error: function (xhr) {
                        console.error(xhr);
                        $('.address-body').html('<p class="text-danger">Failed to load addresses.</p>');
                    },
                });
            }

            $('#addAddressForm').on('click', '.save-address', function (e) {
                e.preventDefault();

                const clientId = $('#client_num_select').val();
                const address = $('#new_address').val();

                $.ajax({
                    url: '/store-client-address',
                    type: 'POST',
                    data: {
                        client_id: clientId,
                        address: address,
                        _token: '{{ csrf_token() }}',
                    },
                    success: function (response) {
                        $('#addAddressModal').modal('hide');
                        $('#new_address').val('');
                        fetchClientAddress(clientId);
                    },
                    error: function (xhr) {
                        console.error(xhr);
                    }
                });
            });

            $(document).on('click', '.remove-address-icon', function () {
                const addressID = $(this).data('address-id');
                const clientID = $(this).data('client-id');

                Swal.fire({
                    title: "Are you sure?",
                    text: "You won't be able to revert this!",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#f53939",
                    cancelButtonColor: "#8392AB",
                    confirmButtonText: "Yes, delete it!"
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: '{{ url("remove-client-address") }}',
                            type: 'GET',
                            data: { addressID: addressID, clientID: clientID },
                            success: function () {
                                fetchClientAddress(clientID);
                            },
                            error: function () {
                                Swal.fire('Error!', 'Something went wrong.', 'error');
                            }
                        });
                    }
                });
            });    
        });

        function toggleTaxes() {
            
            const gstValue = $('#gst').val();
            $('.tax-select').each(function() {
                const row = $(this).closest('tr');
                toggleTaxesForRow(row);
                calculateRowTax(row);
            });
            calculateTotals();           
        }
        
        function toggleTaxesForRow(row) {
            
            const gstValue = $('#gst').val();
            const taxSelect = row.find('.tax-select');
            
            if (gstValue === 'N') {
                taxSelect.html('<option value="no-tax" selected>No Tax</option>');
                taxSelect.prop('disabled', true);
            } else {
                taxSelect.prop('disabled', false);
                // Only rebuild options if they don't exist
                if (taxSelect.find('option').length <= 1) {
                    const options = taxes.map(t => {
                        const isDefault = defaultTaxIds.includes(t.id);
                        return `<option value="${t.id}" ${isDefault ? 'selected' : ''} data-rate="${t.value}">
                            ${t.name} - ${t.value}%
                        </option>`;
                    }).join('');
                    taxSelect.html(options);
                }
            }
        }

        function calculateRowTax(row) {
            const qty = parseFloat(row.find('.qty').val()) || 0;
            const unitPrice = parseFloat(row.find('.unit-price').val()) || 0;
            const subtotal = qty * unitPrice;
            
            // Calculate tax amount
            let taxRate = 0;
            let taxAmount = 0;
            
            const gstValue = $('#gst').val();
            if (gstValue === 'Y') {
                row.find('.tax-select option:selected').each(function() {
                    const rate = parseFloat($(this).data('rate')) || 0;
                    taxRate += rate;
                });
                
                taxAmount = subtotal * (taxRate / 100);
            }
            
            const total = subtotal;
            // const total = subtotal + taxAmount;
            
            // Update row display
            row.find('.amount').val(total.toFixed(2));
            
            // Update hidden fields if needed
            const rowIndex = row.find('td:first').text();
            const amountInput = row.find(`input[name="products[${rowIndex}][amount]"]`);
            if (amountInput.length === 0) {
                row.append(`<input type="hidden" name="products[${rowIndex}][amount]" value="${total.toFixed(2)}">`);
            } else {
                amountInput.val(total.toFixed(2));
            }
            
            // Recalculate totals
            calculateTotals();
        }

        function calculateTotals() {
            let subTotal = 0;
            let totalTax = 0;
            let totalQuantity = 0;
            const redeem = parseFloat($('#redeem_points').val()) * pointValue || 0;
            
            $('.product-row').each(function() {
                const qty = parseFloat($(this).find('.qty').val()) || 0;
                const unitPrice = parseFloat($(this).find('.unit-price').val()) || 0;
                const rowSubtotal = qty * unitPrice;
                
                subTotal += rowSubtotal;
                totalQuantity += qty;
                
                if ($('#gst').val() === 'Y') {
                    let rowTaxRate = 0;
                    $(this).find('.tax-select option:selected').each(function() {
                        const rate = parseFloat($(this).data('rate')) || 0;
                        rowTaxRate += rate;
                    });
                    
                    totalTax += rowSubtotal * (rowTaxRate / 100);
                }
            });
            
            const discountType = $('#discount_type').val();
            const discountValue = parseFloat($('#discount').val()) || 0;
            let discountAmount = 0;
            
            if (discountType == 1) { 
                discountAmount = discountValue;
            } else if (discountType == 2) { 
                discountAmount = (subTotal + totalTax) * (discountValue / 100);
            }
            
           const total = subTotal + totalTax - discountAmount - redeem;        
            
            $('#subTotalDisplay').text(subTotal.toFixed(2) + ' ₹');
            $('#taxDisplay').text(totalTax.toFixed(2) + ' ₹');
            $('#discountDisplay').text(discountAmount.toFixed(2) + ' ₹');
          $('#totalDisplay').text(Math.max(0, Math.floor(total)).toFixed(2) + ' ₹');
             document.getElementById('totalQuantity').textContent = totalQuantity;
            
            $('#sub_total').val(subTotal.toFixed(2));
            $('#tax').val(totalTax.toFixed(2));
            $('#discount_amt').val(discountAmount.toFixed(2));
            $('#total_amt').val(Math.max(0, Math.floor(total)).toFixed(2));
        }
        $(document).ready(function () {                           
if (isLoyalty == 'A') {
                    if (clientRedeemId) {
                        $.ajax({
                            url: '{{route('single-client')}}',
                            type: 'GET',
                            data: { clientID: clientRedeemId },
                            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 + ' ');
                                $('#earnPoints, #redeemPoints, #availablePoints').append('<i class="fa-solid fa-coins text-warning"></i>');

                                document.getElementById('earn_point').value = earnPoints;
                                document.getElementById('redeem_point').value = redeemPoints;
                                document.getElementById('available_point').value = avlPoint;

                                $('.redeem_points').show();


                            },
                            error: function (xhr) {
                                console.log(xhr);
                            }
                        });
                    } 
                }                   
            
            $('#redeem_points').on('change input', function () {
                
                let entered_points = parseFloat($(this).val()) || 0;


                let container = $(this).closest('.current_point');
                let errorElement = container.find('.error-feedback');

                errorElement.text('').hide();
                $(this).removeClass('is-invalid');

                if (entered_points > avlPoint) {
                    errorElement.text('Redeem points cannot exceed available points').show();
                    $(this).addClass('is-invalid');
                    $(this).val(avlPoint);
                    return false;
                }
                currentPoint = avlPoint - entered_points;
                redeemedPoints = redeemPoints + entered_points;
                $('#availablePoints').text(currentPoint + ' ');
                $('#redeemPoints').text(redeemedPoints + ' ');
                $('#availablePoints,#redeemPoints').append('<i class="fa-solid fa-coins text-warning"></i>');
                calculateTotals();
            });
        });
        $(document).ready(function () {
            function calculatePaymentBreakdown() {
                let total_amount = parseFloat($('#total_amt').val()) || 0;
                let tendered_amount = parseFloat($('#tendered_amount').val()) || 0;
                let upi_amount = parseFloat($('#upi').val()) || 0;
                let online_amount = parseFloat($('#online').val()) || 0;
                let cash_amount = parseFloat($('#cash').val()) || 0;

                let digital_payments = upi_amount + online_amount;

                let remaining_after_digital = total_amount - digital_payments;
                if (remaining_after_digital < 0) remaining_after_digital = 0;

                let extra_amount = 0;

                if (tendered_amount > 0) {
                    let cash_to_take = Math.min(tendered_amount, remaining_after_digital);
                    $('#cash').val(cash_to_take.toFixed(2));
                    cash_amount = cash_to_take;

                    extra_amount = tendered_amount - cash_amount;

                } else {
                    let total_paid = digital_payments + cash_amount;
                    extra_amount = total_paid - total_amount;
                }

                if (extra_amount < 0) extra_amount = 0;

                $('.extra_amount').text('Extra Amount: ₹ ' + extra_amount.toFixed(2));
            }

            $(document).on('input', '#tendered_amount, #upi, #online, #cash', function () {
                calculatePaymentBreakdown();
            });

            $(document).on('change', function () {
                calculatePaymentBreakdown();
            });
        });

    </script>
@endpush