@extends('layouts.master')

<style>
    .d-none {
        display: none;
    }

    .custom-dropdown {
        position: relative;
        display: inline-block;
        width: 100%;
    }

    .dropdown-toggle {
        background: white;
        border: 1px solid #ced4da;
        border-radius: 4px;
        padding: 5px;
        cursor: pointer;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: white;
        width: 100%;
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #ced4da;
        border-radius: 4px;
        box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.2);
        z-index: 1;
    }

    .table-hover tbody tr:hover {
        background-color: #f5f5f5;
    }

    .truck-details {
        cursor: pointer;
    }

    .urdu-text {
        font-family: 'Jameel Noori Nastaleeq', serif;
        font-weight: 700;
    }

    .form-label {
        text-align: right;
    }

    .form-control-urdu {
        text-align: right;
    }

    .az-content-label-urdu {
        float: right;
        font-size: 2.4vh;
        font-family: 'Jameel Noori Nastaleeq', serif;
        margin-bottom: 10px
    }

    .urdu-font {
        font-size: 17px;
    }

    .disabled {
        opacity: 0.5;
        pointer-events: none;
    }
</style>

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>B-Cheque</span>
        <span>Create B-Cheque</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Create B-Cheque
        <span>
            <a href="{{ route('b_cheque.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to List
            </a>
        </span>
    </h2>

    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Create B-Cheque</h5>
                <form id="addForm" action="{{ route('b_cheque.store') }}" method="POST">
                    @csrf
                    <!-- Error Display -->
                    @if (count($errors) > 0)
                        <div class="p-1">
                            @foreach ($errors->all() as $error)
                                <div class="alert alert-warning alert-danger fade show" role="alert">{{ $error }}
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    <input type="hidden" name="get_supplier_name" id="set_supplier_name">
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label" for="bCheck_date">Date</label>
                                <input type="text" class="form-control" name="bCheck_date" id="bCheck_date" readonly
                                    required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label" for="pb_no">PBNo</label>
                                <input type="text" class="form-control" name="pb_no" id="pb_no"
                                    value="{{ old('pb_no') }}">
                            </div>
                        </div>

                        {{-- Truck Entries End --}}
                        <div class="col-md-12 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="truck" style="float: right;">
                                    <span style="color:red;">*</span> ٹرک نمبر
                                </label>
                                {{-- @foreach ($sales as $sale)
                                        @foreach ($sale->salesItemsDetails as $saleDetails)
                                        {{ dd($saleDetails) }}
                                        @endforeach
                                        @endforeach --}}
                                <!-- Hidden native select element -->
                                <select class="form-control d-none" name="good_receipts_truck_id" id="truck"
                                    value="{{ old('good_receipts_truck_id') }}" required>
                                    <option value="">- Select -</option>
                                    @foreach ($soldTrucks as $truck)
                                        <option value="{{ $truck->id_truck }}">
                                            {{ $truck->truck_no }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    <div class="selected-trucks mt-2" id="selected-trucks"></div>
                                    <div class="dropdown-toggle form-control" id="truck-toggle">- Select -</div>
                                    <!-- Display selected truck here -->
                                    <div class="dropdown-content">
                                        <input type="text" id="truck-search" class="form-control"
                                            placeholder="Search the truck number..."
                                            onkeyup="showOnlyThisTruckDetails(this.value)">

                                        <table class="table table-bordered table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Select</th>
                                                    <th>Truck No</th>
                                                    <th>Supplier</th>
                                                    <th>Main Category</th>
                                                    <th>Parent Category</th>
                                                    <th>Child Category</th>
                                                    <th>Marka</th>
                                                    <th>Bori</th>
                                                    <th>Weight</th>
                                                    <th>Price</th>
                                                    <th>Total Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody id="truck-table-body">
                                                @foreach ($sales as $sale)
                                                    @if (!is_null($sale->goodReceiptTruck))
                                                        @foreach ($sale->salesItemsDetails as $saleDetails)
                                                            <tr class="truck-details"
                                                                data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                data-truck-no="{{ $sale->goodReceiptTruck->truck_no }}"
                                                                data-salesdetails-id="{{ $saleDetails->id_sid }}"
                                                                data-supplier-id="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->id_supplier }}"
                                                                data-rent-received="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->rent_recieve }}">
                                                                <td>
                                                                    <input type="checkbox" class="truck-checkbox" hidden
                                                                        data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}">
                                                                    <span class="checkbox-icons">
                                                                        <i
                                                                            class="fa-solid fa-circle-check text-success d-none"></i>
                                                                        <i class="fa-regular fa-circle-xmark text-dark"></i>
                                                                    </span>
                                                                </td>
                                                                {{-- -> --}}
                                                                <td>{{ $sale->goodReceiptTruck->truck_no }}</td>
                                                                <td>{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->supplier_name ?? 'N/A' }}
                                                                </td>
                                                                <td data-mcat-id="{{ $saleDetails->items_main_cate }}">
                                                                    {{ $saleDetails?->productMainCate?->products_category_name }}
                                                                </td>
                                                                <td data-pcat-id="{{ $saleDetails->items_parent_cate }}">
                                                                    {{ $saleDetails?->productParentCate?->name }}</td>
                                                                <td data-ccat-id="{{ $saleDetails->items_child_cate }}">
                                                                    {{ $saleDetails?->productChildCate?->name }}</td>
                                                                <td>{{ $saleDetails->marka }}</td>
                                                                <td>{{ $saleDetails->bori }}</td>
                                                                <td>{{ $saleDetails->weight }}</td>
                                                                <td>{{ $saleDetails->rate }}</td>
                                                                <td>{{ $saleDetails->amount }}</td>
                                                            </tr>
                                                        @endforeach
                                                    @endif
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Truck Entries End --}}


                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="suppliers" style="float: right;">
                                    <span style="color:red;">*</span>
                                    سپلائرز
                                </label>
                                <select class="form-control select2" name="suppliers" id="suppliers" required>
                                    <option value="">- Select -</option>
                                    @foreach ($suppliers as $key => $supplier)
                                        <option value="{{ $supplier->id_supplier }}">{{ $supplier->supplier_name }} -
                                            {{ $supplier->supplier_name_urdu }}</option>
                                    @endforeach
                                </select>
                            </div>
                            @error('suppliers')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="bilty_no" style="float: right;">
                                    بلٹی نمبر
                                </label>
                                <input type="text" class="form-control" name="bilty_no" id="bilty_no"
                                    value="{{ old('bilty_no') }}">
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="detail" style="float: right;">
                                    تفصیل
                                </label>
                                <input type="text" class="form-control" name="details" id="detail"
                                    value="{{ old('details') }}">
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <label class="az-content-label" for="bCheck_status">Status</label>
                            <select id="bCheck_status" name="bCheck_status" class="form-control">
                                <option value="">Select</option>
                                <option value="1" selected>Active</option>
                                <option value="0" {{ old('bCheck_status') == '0' ? 'selected' : '' }}>
                                    In-Active
                                </option>
                            </select>
                            @error('bCheck_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <?php
                        $prefNames = ['Labour', 'Bazaar Fees', 'Post Expense', 'Commission'];
                        $gen_pref = app\GeneralPrefrence::whereIn('name', $prefNames)->get()->keyBy('name');

                        $labour = $gen_pref->get('Labour');
                        $bazaar_fees = $gen_pref->get('Bazaar Fees');
                        $post_expense = $gen_pref->get('Post Expense');
                        $commission = $gen_pref->get('Commission');
                        ?>
                        <!-- Item Details Section -->
                        <div class="col-md-12 mt-5">
                            <h4>
                                Item Details
                                <span class="show-span d-none">
                                    (You have selected the same values, Now the values are merged)
                                </span>
                            </h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table table-bordered" id="item-table">
                                    <thead>
                                        <tr>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Main Cate
                                            </th>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Parent Cate
                                            </th>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Child Cate
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                مارکہ
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                بوری
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                وزن
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                ریٹ
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                رقم
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody id="item-details">
                                        <!-- Dynamic rows will be added here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <br><br>
                    <hr>
                    <br>
                    <div class="row urdu-text">
                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="total_amount" class="form-label">:کل رقم</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="total_amount"
                                    readonly name="total_amount" placeholder="کل رقم درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="total_expanse_amount" class="form-label">:کل خرچہ</label>
                                <input type="text" class="form-control form-control-urdu n-amount"
                                    id="total_expanse_amount" readonly name="total_expanse_amount"
                                    placeholder="کل خرچہ درج کریں" value="{{ old('total_expanse_amount') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="save_amount" class="form-label">:بچت</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="save_amount"
                                    readonly name="save_amount" placeholder="بچت درج کریں"
                                    value="{{ old('save_amount') }}">
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="total_bori" class="form-label">:کل بوریاں</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="total_bori"
                                    readonly name="total_bori" placeholder="کل بوریاں درج کریں"
                                    value="{{ old('total_bori') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="F" class="form-label">:وزن</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="total_weight"
                                    readonly name="total_weight" placeholder="وزن درج کریں"
                                    value="{{ old('total_weight') }}">
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="commission_rate" class="form-label">
                                    <span style="float: left; font-size: 1.9vh; font-weight: 100 !important;">Put The value
                                        of total in percentage <span style="color: red;">(%)</span></span>
                                    <span>:کمیشن ریٹ</span>
                                </label>
                                <input value="{{ $commission->rate }}" type="number"
                                    class="form-control form-control-urdu" id="commission_rate" name="commission_rate"
                                    placeholder="کمیشن ریٹ درج کریں" max="100"
                                    value="{{ old('commission_rate') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="commission" class="form-label">:کمیشن</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="commission"
                                    readonly name="commission" placeholder="کمیشن درج کریں"
                                    value="{{ old('commission') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="more" class="form-label">:مزید</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="more"
                                    name="extra_pay" placeholder="اضافی رقم درج کریں" value="{{ old('extra_pay') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="payment_details" class="form-label">:تفصیلات</label>
                                <textarea class="form-control form-control-urdu" name="payment_details" id="payment_details" rows="5"
                                    placeholder="تفصیلات درج کریں"></textarea>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="rent_received" class="form-label">:کرایہ وصول</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="rent_received"
                                    name="rent_received" placeholder="کرایہ وصول کریں"
                                    value="{{ old('rent_received') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> :مزدوری بوری</label>
                                <input value="{{ $labour->rate }}" type="text"
                                    class=" n-amount form-control form-control-urdu" id="labour" name="labour"
                                    placeholder="مزدوری درج کریں" value="{{ old('labour') }}">
                            </div>

                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> :کل کَٹا</label>
                                <input value="" type="text" class=" n-amount form-control form-control-urdu"
                                    id="total_katta" name="total_katta" placeholder=" کَٹا درج کریں کل"
                                    value="{{ old('total_katta') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> :مزدوری کَٹا</label>
                                <input value="{{ $labour->rate }}" type="text"
                                    class=" n-amount form-control form-control-urdu" id="labour_katta"
                                    name="labour_katta" placeholder="مزدوری کَٹا درج کریں"
                                    value="{{ old('labour_katta') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="market_fees" class="form-label">:بازار کی فیس</label>
                                <input value="{{ $bazaar_fees->rate }}" type="text"
                                    class="form-control form-control-urdu n-amount" id="market_fees" name="market_fees"
                                    placeholder="بازار کی فیس درج کریں" value="{{ old('market_fees') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="post_expense" class="form-label">:پوسٹ خرچ</label>
                                <input value="{{ $post_expense->rate }}" type="text"
                                    class="form-control form-control-urdu n-amount" id="post_expense" name="post_expense"
                                    placeholder="پوسٹ خرچ درج کریں" value="{{ old('post_expense') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="miscellaneous_expense" class="form-label">:متفرق خرچ</label>
                                <input type="text" class="form-control form-control-urdu n-amount"
                                    id="miscellaneous_expense" name="miscellaneous_expense"
                                    placeholder="متفرق خرچ درج کریں" value="{{ old('miscellaneous_expense') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="cash" class="form-label">:نقد</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="cash"
                                    name="cash" placeholder="نقد رقم درج کریں" value="{{ old('cash') }}">
                            </div>
                        </div>
                        <div class="mt-5">
                            <a href="{{ route('b_cheque.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                            <button type="submit" class="btn btn-az-primary pd-x-20">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection


@push('scripts')
    <script type="text/javascript">
        const checkParentUrl = "{{ route('check-cate-parent') }}";
        const checkChildUrl = "{{ route('check-cate-child') }}";

        function initAutoNumeric() {
            document.querySelectorAll('.n-amount').forEach(el => {
                if (!AutoNumeric.getAutoNumericElement(el)) {
                    new AutoNumeric(el, {
                        digitGroupSeparator: ',',
                        decimalPlaces: 2,
                        unformatOnSubmit: true
                    });
                }
            });
        }
        initAutoNumeric(); // on page load


        function checkForParentCate(productMainCateId, uniqId) {

            let productMainCateIdNew = $('#mainCate_' + uniqId).val();
            let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);
            $.ajax({
                url: checkParentUrl,
                type: 'GET',
                data: {
                    productMainCateId: productMainCateIdNew
                },
                success: function(response) {
                    if (response.productParentCate.length > 0) {
                        let options = '<option value="">Select Item</option>';
                        response.productParentCate.forEach(function(subParentCategory) {
                            options +=
                                `<option value="${subParentCategory.id_pro_sub_cat_parent}">${subParentCategory.name} | ${subParentCategory.name_urdu}</option>`;
                        });
                        $('#parentCate_' + uniqId).html(options).trigger('change');
                        // Update hidden row's mainCate and reset parent/child
                        if (hiddenRow.length) {
                            hiddenRow.find('input[name="mainCate[]"]').val(productMainCateIdNew);
                            hiddenRow.find('input[name="parentCate[]"]').val('');
                            hiddenRow.find('input[name="childCate[]"]').val('');
                        }

                    }
                },
                error: function() {
                    alert('Error checking Product Parent Category!');
                }
            });
        }

        function checkForChildCate(productParentCateId, uniqId) {
            let productParentCateIdNew = $('#parentCate_' + uniqId).val();
            let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);
            $.ajax({
                url: checkChildUrl,
                type: 'GET',
                data: {
                    productParentCateId: productParentCateIdNew
                },
                success: function(response) {
                    if (response.productChildCate.length > 0) {
                        let options = '<option value="">Select Item</option>';
                        response.productChildCate.forEach(function(subChildCategory) {
                            options +=
                                `<option value="${subChildCategory.id_pro_sub_cat_child}">${subChildCategory.name} | ${subChildCategory.name_urdu}</option>`;
                        });
                        $('#childCate_' + uniqId).html(options);
                        if (hiddenRow.length) {
                            hiddenRow.find('input[name="parentCate[]"]').val(productParentCateIdNew);
                            hiddenRow.find('input[name="childCate[]"]').val('');
                        }


                    }
                },
                error: function() {
                    alert('Error checking Product Child Category!');
                }
            });
        }

        function updateChildValue(uniqId) {
            let productChildCateIdNew = $('#childCate_' + uniqId).val();
            let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);
            if (hiddenRow.length) {
                hiddenRow.find('input[name="childCate[]"]').val(productChildCateIdNew);
            }
        }


        document.addEventListener('keydown', function(event) {
            if ((event.ctrlKey || event.metaKey) && event.key === 's') {
                event.preventDefault();

                document.getElementById('addForm').submit();
            }

            if (event.key === 'Enter') {
                event.preventDefault();
            }
        });

        function calculateAmount(input) {
            // Find the row where the input is located
            let row = input.closest('tr');


            // Get the weight and rate inputs
            let weight = row.querySelector('.weight-input').value;
            let rate = row.querySelector('.rate-input').value;

            // If both weight and rate are filled, calculate the amount
            if (weight && rate) {
                let amount = (parseFloat(rate) * parseFloat(weight)) / 40;
                // Set the calculated amount in the amount field
                row.querySelector('.amount-input').value = amount.toFixed(2); // Rounds to 2 decimal places
                updateTotals();
            }
        }

        $(document).ready(function() {

            // AutoNumeric.multiple('.n-amount', {
            //     digitGroupSeparator: ',',
            //     decimalPlaces: 2
            // });
            //     document.querySelectorAll('.n-amount').forEach(function(el) {
            //     new AutoNumeric(el, {
            //         digitGroupSeparator: ',',
            //          decimalPlaces: 0,
            //         unformatOnSubmit: true
            //     });
            // });
            // Initialize Select2 and Datepicker
            $('#suppliers').select2({
                theme: 'default'
            });

            var today = new Date();
            var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' +
                today.getDate()).slice(-2);

            $("#bCheck_date").val(formattedDate);

            // Initialize datepicker with custom format

            $("#bCheck_date").datepicker({
                dateFormat: "yy-mm-dd"
            });
        });

        function validateCommissionRate() {
            let commissionRateInput = $('#commission_rate');
            let commissionRateValue = parseFloat(commissionRateInput.val()) || 0;
            let maxCommissionRate = 100;
            if (commissionRateValue > maxCommissionRate) {
                commissionRateInput.val(maxCommissionRate);
            }
        }

        $('#commission_rate').on('input', validateCommissionRate);

        // function updateTotals() {
        //     let totalBori = 0;
        //     let totalWeight = 0;
        //     let totalAmount = 0;
        //     let initialCashReceived = 0;

        //     // Loop through each item row to calculate total bori, weight, and amount
        //     $('#item-table tbody tr').each(function() {
        //         let bori = parseFloat($(this).find('input[name="bori[]"]').val()) || 0;
        //         let weight = parseFloat($(this).find('input[name="weight[]"]').val()) || 0;
        //         let amount = parseFloat($(this).find('input[name="amount[]"]').val()) || 0;

        //         totalBori += bori;
        //         totalWeight += weight;
        //         totalAmount += amount;
        //     });

        //     // Get values for expenses and other inputs
        //     let labour = parseFloat($('input[name="labour"]').val()) || 0;
        //     let marketfee = parseFloat($('input[name="market_fees"]').val()) || 0;
        //     let postexp = parseFloat($('input[name="post_expense"]').val()) || 0;
        //     let miscellaneousExp = parseFloat($('input[name="miscellaneous_expense"]').val()) || 0;
        //     let commissionp = parseFloat($('input[name="commission_rate"]').val()) || 0;
        //     let rent_received = parseFloat($('input[name="rent_received"]').val()) || 0;
        //     let cash = parseFloat($('input[name="cash"]').val()) || 0;
        //     let more = parseFloat($('input[name="extra_pay"]').val()) || 0;

        //     // Calculate commission value based on total amount and commission rate
        //     let commissionVal = (totalAmount * commissionp) / 100;
        //     $('#commission').val(commissionVal.toFixed(2));
        //     let finalLabor = labour * totalBori;

        //     // Calculate the total expanses (cash received) including commission and other expenses
        //     let cashReceived = initialCashReceived + finalLabor + marketfee + postexp + miscellaneousExp + commissionVal +
        //         more + rent_received + cash;

        //     // Update the total fields
        //     $('#total_bori').val(totalBori);
        //     $('#total_weight').val(totalWeight);
        //     $('#total_amount').val(totalAmount);
        //     $('#total_expanse_amount').val(cashReceived.toFixed(2));
        //     $('#save_amount').val((totalAmount - cashReceived).toFixed(2));
        // }

        function updateTotals() {

            let totalBori = 0;
            let totalWeight = 0;
            let totalAmount = 0;


            // Function to get value from autonumeric OR normal input
            const getVal = (el) => {
                if (!el) return 0;

                if (AutoNumeric.isManagedByAutoNumeric(el)) {
                    return parseFloat(AutoNumeric.getAutoNumericElement(el).getNumericString()) || 0;
                }

                return parseFloat(el.value.replace(/,/g, '')) || 0;
            };

            // Loop table rows
            $('#item-table tbody tr').each(function() {
                totalBori += getVal($(this).find('input[name="bori[]"]')[0]);
                totalWeight += getVal($(this).find('input[name="weight[]"]')[0]);
                totalAmount += getVal($(this).find('input[name="amount[]"]')[0]);
            });

            // Other values
            let labour = getVal(document.querySelector('input[name="labour"]'));
            let total_katta = getVal(document.querySelector('input[name="total_katta"]'));
            let labour_katta = getVal(document.querySelector('input[name="labour_katta"]'));
            let total_katta_charges = total_katta * labour_katta;

            let marketfee = getVal(document.querySelector('input[name="market_fees"]'));
            let postexp = getVal(document.querySelector('input[name="post_expense"]'));
            let misc = getVal(document.querySelector('input[name="miscellaneous_expense"]'));
            let commissionP = getVal(document.querySelector('input[name="commission_rate"]'));
            let rentReceived = getVal(document.querySelector('input[name="rent_received"]'));
            let cash = getVal(document.querySelector('input[name="cash"]'));
            let extra = getVal(document.querySelector('input[name="extra_pay"]'));

            // Calculations
            let commissionVal = (totalAmount * commissionP) / 100;
            let finalLabor = labour * totalBori;

            let totalExpense =
                finalLabor + marketfee + postexp + misc + commissionVal +
                extra + rentReceived + cash + total_katta_charges;

            // ===============================
            // SET FORMATTED OUTPUTS
            // ===============================

            AutoNumeric.getAutoNumericElement('#total_bori').set(totalBori);
            AutoNumeric.getAutoNumericElement('#total_weight').set(totalWeight);
            AutoNumeric.getAutoNumericElement('#total_amount').set(totalAmount);
            AutoNumeric.getAutoNumericElement('#commission').set(commissionVal);
            AutoNumeric.getAutoNumericElement('#total_expanse_amount').set(totalExpense);
            AutoNumeric.getAutoNumericElement('#save_amount').set(totalAmount - totalExpense);
        }





        // Recalculate totals when input values change
        function handleInputChange() {
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"], input[name="weight[]"]',
                updateTotals);
            $('input[name="extra_pay"], input[name="commission_rate"], input[name="miscellaneous_expense"], input[name="post_expense"], input[name="market_fees"], input[name="labour"],input[name="total_katta"],input[name="labour_katta"] input[name="rent_received"], input[name="cash"]')
                .on('input', updateTotals);
        }

        // Initialize event listeners
        $(document).ready(function() {
            handleInputChange();
            updateTotals();
        });

        // For truck drop-down
        $(document).ready(function() {
            let selectedTruckNumbers = [];
            let selectedTruckIds = [];
            let selectedSuppliers = new Set();

            $('#truck-toggle').click(function() {
                $('.dropdown-content').toggle();
            });

            $('#truck-search').on('input', function() {
                showOnlyThisTruckDetails(this.value);
            });

            // Handle checkbox selection and icon toggle
            $('.truck-checkbox').on('change', function() {
                const truckId = $(this).data('truck-id');
                const truckNo = $(this).closest('tr').data('truck-no');
                const salesDetailsId = $(this).closest('tr').data('salesdetails-id');
                const supplierName = $(this).closest('tr').find('td:nth-child(3)').text().trim();
                const supplierId = $(this).closest('tr').data('supplier-id');
                const icons = $(this).siblings('.checkbox-icons');
                const rentReceived = $(this).closest('tr').data('rent-received');
                AutoNumeric.set('#rent_received', rentReceived || 0);

                if (this.checked) {
                    selectedTruckNumbers.push(truckNo);
                    selectedTruckIds.push(truckId);
                    selectedSuppliers.add(supplierName);

                    // Show the checked icon, hide the unchecked icon
                    icons.find('.fa-circle-check').removeClass('d-none');
                    icons.find('.fa-circle-xmark').addClass('d-none');

                    // Reflect the selected truck's details in the Item Details table
                    appendSelectedTruckDetails($(this).closest('tr'));
                } else {
                    const index = selectedTruckNumbers.indexOf(truckNo);
                    if (index > -1) {
                        selectedTruckNumbers.splice(index, 1);
                        selectedTruckIds.splice(index, 1);
                    }

                    // Hide the checked icon, show the unchecked icon
                    icons.find('.fa-circle-check').addClass('d-none');
                    icons.find('.fa-circle-xmark').removeClass('d-none');

                    // Remove the unselected truck's details from the Item Details table
                    removeTruckDetails(salesDetailsId, $(this).closest('tr'));

                    // Update suppliers dropdown and check if supplier still exists
                    let supplierStillExists = false;
                    $('.truck-details').each(function() {
                        const otherSupplier = $(this).find('td:nth-child(3)').text().trim();
                        const otherTruckNo = $(this).data('truck-no');
                        if (selectedTruckNumbers.includes(otherTruckNo) && otherSupplier ===
                            supplierName) {
                            supplierStillExists = true;
                        }
                    });
                    if (!supplierStillExists) {
                        selectedSuppliers.delete(supplierName);
                    }
                }

                updateSelectedTrucks(truckNo);
                updateSuppliersDropdown(supplierId);
                filterTruckDetails();
            });





            // Function to append the selected truck's data in the Item Details table
            // function appendSelectedTruckDetails(truckRow) {
            //     const truckNo = truckRow.data('truck-no');
            //     const salesDeId = truckRow.data('salesdetails-id');

            //     const mainCate = truckRow.find('td:nth-child(4)').text();
            //     const parentCate = truckRow.find('td:nth-child(5)').text();
            //     const childCate = truckRow.find('td:nth-child(6)').text();
            //     const marka = truckRow.find('td:nth-child(7)').text();
            //     const bori = parseFloat(truckRow.find('td:nth-child(8)').text());
            //     const weight = parseFloat(truckRow.find('td:nth-child(9)').text());
            //     const rate = parseFloat(truckRow.find('td:nth-child(10)').text());
            //     const amount = parseFloat(truckRow.find('td:nth-child(11)').text());

            //     // Check if a visible row already exists for merging
            //     let existingRow = $('#item-details tr.visibleRow').filter(function() {
            //         return $(this).find('td:eq(0)').text() === mainCate &&
            //             $(this).find('td:eq(1)').text() === parentCate &&
            //             $(this).find('td:eq(2)').text() === childCate &&
            //             $(this).find('td:eq(3)').text() === marka &&
            //             $(this).find('td:eq(6)').text() === rate.toString();
            //     });

            //     if (existingRow.length > 0) {
            //         // Merge values by adding bori, weight, and amount to the existing row
            //         const existingBori = parseFloat(existingRow.find('.boriSet').text()) || 0;
            //         const existingWeight = parseFloat(existingRow.find('.weightSet').text()) || 0;
            //         const existingAmount = parseFloat(existingRow.find('.amountSet').text()) || 0;

            //         existingRow.find('.boriSet').text((existingBori + bori).toFixed(2));
            //         existingRow.find('.weightSet').text((existingWeight + weight).toFixed(2));
            //         existingRow.find('.amountSet').text((existingAmount + amount).toFixed(2));
            //     } else {
            //         // Append a new visible row if it doesn't already exist
            //         $('#item-details').append(`
        //         <tr class="visibleRow" data-salesdetails-id="${salesDeId}">
        //             <td>${mainCate}</td>
        //             <td>${parentCate}</td>
        //             <td>${childCate}</td>
        //             <td>${marka}</td>
        //             <td><span class="boriSet">${bori}</span></td>
        //             <td><span class="weightSet">${weight}</span></td>
        //             <td><span class="rateSet">${rate}</span></td>
        //             <td><span class="amountSet">${amount}</span></td>
        //         </tr>
        //     `);
            //     }

            //     // Append a hidden row for backend data saving, ensuring only one per selection
            //     if ($(`#item-details tr.hiddenRow[data-salesdetails-id="${salesDeId}"]`).length === 0) {
            //         $('#item-details').append(`
        //         <tr hidden data-truck-no="${truckNo}" data-salesdetails-id="${salesDeId}" class="hiddenRow">
        //             <input type="hidden" name="salesDeId[]" value="${salesDeId}">
        //             <td><input type="text" name="mainCate[]" hidden value="${mainCate}"></td>
        //             <td><input type="text" name="parentCate[]" hidden value="${parentCate}"></td>
        //             <td><input type="text" name="childCate[]" hidden value="${childCate}"></td>
        //             <td><input type="text" name="marka[]" hidden value="${marka}"></td>
        //             <td><input type="text" class="form-control" hidden name="bori[]" value="${bori}"></td>
        //             <td><input type="text" class="form-control" hidden name="weight[]" value="${weight}"></td>
        //             <td><input type="text" class="form-control" hidden name="rate[]" value="${rate}"></td>
        //             <td><input type="text" class="form-control" hidden name="amount[]" value="${amount}"></td>
        //         </tr>
        //     `);
            //     }

            //     updateTotals();
            // }


            const productCateMainJson = @json($productCateMain);

            function appendSelectedTruckDetails(truckRow) {
                const truckNo = truckRow.data('truck-no');
                const salesDeId = truckRow.data('salesdetails-id');

                const mainCate = truckRow.find('td:nth-child(4)').attr('data-mcat-id');
                const parentCate = truckRow.find('td:nth-child(5)').attr('data-pcat-id');
                const childCate = truckRow.find('td:nth-child(6)').attr('data-ccat-id');

                const mainCateTxt = truckRow.find('td:nth-child(4)').text();
                const parentCateTxt = truckRow.find('td:nth-child(5)').text();
                const childCateTxt = truckRow.find('td:nth-child(6)').text();


                const marka = truckRow.find('td:nth-child(7)').text();
                const bori = parseFloat(truckRow.find('td:nth-child(8)').text());
                const weight = parseFloat(truckRow.find('td:nth-child(9)').text());
                const rate = parseFloat(truckRow.find('td:nth-child(10)').text());
                const amount = parseFloat(truckRow.find('td:nth-child(11)').text());
                const uniqueId = Date.now(); // For unique select IDs
                // Build Main Category options from $productCateMain (Blade variable)
                let mainOptions = `<option value="">Select Main Cate</option>`;

                productCateMainJson.forEach(function(main) {
                    const selected = mainCate == main.id_pro_cate_main ? 'selected' : '';
                    mainOptions +=
                        `<option data-mcat-id='${main.id_pro_cate_main}' value="${main.id_pro_cate_main}" ${selected}>${main.products_category_name} | ${main.products_category_name_urdu}</option>`;
                });


                // Check for an existing visible row (same combination)
                let existingRow = $('#item-details tr.visibleRow').filter(function() {
                    return (
                        $(this).find('td:eq(0)').text() === mainCate &&
                        $(this).find('td:eq(1)').text() === parentCate &&
                        $(this).find('td:eq(2)').text() === childCate &&
                        $(this).find('td:eq(3)').text() === marka &&
                        $(this).find('td:eq(6) input').val() === rate.toString()
                    );
                });

                if (existingRow.length > 0) {
                    // Merge values
                    const existingBori = parseFloat(existingRow.find('.boriSet').val()) || 0;
                    const existingWeight = parseFloat(existingRow.find('.weightSet').val()) || 0;
                    const existingAmount = parseFloat(existingRow.find('.amountSet').val()) || 0;

                    existingRow.find('.boriSet').val((existingBori + bori).toFixed(2));
                    existingRow.find('.weightSet').val((existingWeight + weight).toFixed(2));
                    existingRow.find('.amountSet').val((existingAmount + amount).toFixed(2));
                } else {
                    // Add new editable visible row

                    $('#item-details').append(`
            <tr class="visibleRow" data-salesdetails-id="${salesDeId}">
            <td>
                <select class="form-control form-control-sm mainCateSelect" id="mainCate_${uniqueId}" onchange="checkForParentCate(${mainCate},${uniqueId})">
                    ${mainOptions}
                </select>
            </td>
            <td>
                <select class="form-control form-control-sm parentCateSelect" id="parentCate_${uniqueId}" onchange="checkForChildCate(${parentCate},${uniqueId})">
                    ${parentCate ? `<option value="${parentCate}" selected>${parentCateTxt}</option>` : `<option value="">Select Parent</option>`}
                </select>
            </td>
            <td>
                <select class="form-control form-control-sm childCateSelect" onchange="updateChildValue(${uniqueId})" id="childCate_${uniqueId}">
                    ${childCate ? `<option value="${childCate}" selected>${childCateTxt}</option>` : `<option value="">Select Child</option>`}
                </select>
            </td>

                <td>${marka}</td>
                <td><input type="text" step="1" class="form-control form-control-sm boriSet n-amount" value="${bori}"></td>
                <td><input type="text" step="1" class="form-control form-control-sm weightSet n-amount" value="${weight}"></td>
                <td><input type="text" step="1" class="form-control form-control-sm rateSet n-amount" value="${rate}"></td>
                <td><input type="text" step="1" readonly class="form-control form-control-sm amountSet bg-light n-amount" value="${amount}"></td>
            </tr>
        `);

                }

                // Append hidden row for backend data saving
                if ($(`#item-details tr.hiddenRow[data-salesdetails-id="${salesDeId}"]`).length === 0) {
                    $('#item-details').append(`
            <tr hidden  data-truck-no="${truckNo}" data-uniq-id='${uniqueId}' data-salesdetails-id="${salesDeId}" class="hiddenRow">
                <input type="hidden" name="salesDeId[]" value="${salesDeId}">
                <td><input type="hidden" name="mainCate[]" value="${mainCate}"></td>
                <td><input type="hidden" name="parentCate[]" value="${parentCate}"></td>
                <td><input type="hidden" name="childCate[]" value="${childCate}"></td>
                <td><input type="hidden" name="marka[]" value="${marka}"></td>
                <td><input type="hidden" name="bori[]" value="${bori}"></td>
                <td><input type="hidden" name="weight[]" value="${weight}"></td>
                <td><input type="hidden" name="rate[]" value="${rate}"></td>
                <td><input type="hidden" name="amount[]" value="${amount}"></td>
            </tr>
        `);
                }

                updateTotals();
                initAutoNumeric();
            }






            /* ==============================
               Handle edits and auto updates
               ============================== */
            // $(document).on('input', '.boriSet, .weightSet, .rateSet', function() {
            //     const row = $(this).closest('tr');
            //     const bori = parseFloat(row.find('.boriSet').val()) || 0;
            //     const weight = parseFloat(row.find('.weightSet').val()) || 0;
            //     const rate = parseFloat(row.find('.rateSet').val()) || 0;
            //     const newAmount = ((weight * rate).toFixed(2)) / 40;

            //     row.find('.amountSet').val(newAmount);

            //     // Update hidden inputs (backend sync)
            //     const salesDeId = row.data('salesdetails-id');
            //     const hiddenRow = $(`#item-details tr.hiddenRow[data-salesdetails-id="${salesDeId}"]`);
            //     hiddenRow.find('input[name="bori[]"]').val(bori);
            //     hiddenRow.find('input[name="weight[]"]').val(weight);
            //     hiddenRow.find('input[name="rate[]"]').val(rate);
            //     hiddenRow.find('input[name="amount[]"]').val(newAmount);

            //     updateTotals();
            // });

            $(document).on('input', '.boriSet, .weightSet, .rateSet', function() {

                const row = $(this).closest('tr');
                const salesDeId = row.data('salesdetails-id');

                // ---------------------------------------------------
                // SAFE function to get numeric value from AutoNumeric
                // ---------------------------------------------------
                const getAN = (el) => {
                    const dom = el.get(0);
                    const an = AutoNumeric.getAutoNumericElement(dom);
                    if (an) {
                        return Number(an.getNumericString()); // "12,000" → 12000
                    }
                    return Number(el.val().replace(/,/g, "")) || 0;
                };

                // ---------------------------------------------------
                // READ values — AutoNumeric COMPATIBLE
                // ---------------------------------------------------
                const bori = getAN(row.find('.boriSet'));
                const weight = getAN(row.find('.weightSet'));
                const rate = getAN(row.find('.rateSet'));

                // ---------------------------------------------------
                // CALCULATE amount
                // ---------------------------------------------------
                let newAmount = 0;
                if (weight > 0 && rate > 0) {
                    newAmount = (weight * rate) / 40;
                }

                // ---------------------------------------------------
                // SET formatted amount using AutoNumeric (if exists)
                // ---------------------------------------------------
                const amountEl = row.find('.amountSet').get(0);
                const amountAN = AutoNumeric.getAutoNumericElement(amountEl);

                if (amountAN) {
                    amountAN.set(newAmount);
                } else {
                    row.find('.amountSet').val(newAmount.toFixed(2));
                }

                // ---------------------------------------------------
                // UPDATE hidden row (backend sync)
                // ---------------------------------------------------
                const hiddenRow = $(`#item-details tr.hiddenRow[data-salesdetails-id="${salesDeId}"]`);

                hiddenRow.find('input[name="bori[]"]').val(bori);
                hiddenRow.find('input[name="weight[]"]').val(weight);
                hiddenRow.find('input[name="rate[]"]').val(rate);
                hiddenRow.find('input[name="amount[]"]').val(newAmount);

                // ---------------------------------------------------
                // Recalculate summary totals
                // ---------------------------------------------------
                updateTotals();
            });



            // Function to remove a truck's details from the Item Details table when unchecked
            function removeTruckDetails(salesDetailsId, truckRow) {
                const mainCate = truckRow.find('td:nth-child(4)').text();
                const parentCate = truckRow.find('td:nth-child(5)').text();
                const childCate = truckRow.find('td:nth-child(6)').text();
                const marka = truckRow.find('td:nth-child(7)').text();
                const rate = parseFloat(truckRow.find('td:nth-child(10)').text());

                const bori = parseFloat(truckRow.find('td:nth-child(8)').text());
                const weight = parseFloat(truckRow.find('td:nth-child(9)').text());
                const amount = parseFloat(truckRow.find('td:nth-child(11)').text());

                // Locate existing visible row by category and rate (not by salesDetailsId)
                let existingRow = $('#item-details tr.visibleRow').filter(function() {
                    return $(this).find('td:eq(0)').text() === mainCate &&
                        $(this).find('td:eq(1)').text() === parentCate &&
                        $(this).find('td:eq(2)').text() === childCate &&
                        $(this).find('td:eq(3)').text() === marka &&
                        parseFloat($(this).find('.rateSet').text()) === rate;
                });

                if (existingRow.length > 0) {
                    const existingBori = parseFloat(existingRow.find('.boriSet').text()) || 0;
                    const existingWeight = parseFloat(existingRow.find('.weightSet').text()) || 0;
                    const existingAmount = parseFloat(existingRow.find('.amountSet').text()) || 0;

                    // Subtract values
                    const newBori = existingBori - bori;
                    const newWeight = existingWeight - weight;
                    const newAmount = existingAmount - amount;

                    // Update visible row with new values
                    existingRow.find('.boriSet').text(newBori.toFixed(2));
                    existingRow.find('.weightSet').text(newWeight.toFixed(2));
                    existingRow.find('.amountSet').text(newAmount.toFixed(2));

                    // Remove row if all values reach zero or below
                    if (newBori <= 0 && newWeight <= 0 && newAmount <= 0) {
                        existingRow.remove();
                    }
                }

                // Remove the hidden row for backend submission
                $(`#item-details tr.hiddenRow[data-salesdetails-id="${salesDetailsId}"]`).remove();

                updateTotals();
            }

            $(document).click(function(event) {
                if (!$(event.target).closest('.custom-dropdown').length) {
                    $('.dropdown-content').hide();
                }
            });

            function updateSelectedTrucks(truckNo) {
                $('#selected-trucks').text('Selected Truck: ' + truckNo);
                selectedTruckIds.forEach(function(truckId) {
                    $('#truck').append('<option value="' + truckId + '" selected>' + truckNo + '</option>');
                });
                $('#truck-toggle').html(truckNo);
            }

            function updateSuppliersDropdown(supplierId) {
                const $supplierDropdown = $('#suppliers');
                $supplierDropdown.html('');

                if (selectedSuppliers.size > 0) {
                    selectedSuppliers.forEach(function(supplier) {
                        $supplierDropdown.append('<option value="' + supplierId + '" selected>' + supplier +
                            '</option>');
                        $('#set_supplier_name').val(supplier);
                    });
                } else {
                    $('#set_supplier_name').val('');
                    $supplierDropdown.append('<option value="">- Select -</option>');
                    @foreach ($suppliers as $key => $supplier)
                        $supplierDropdown.append(
                            '<option value="{{ $supplier->id_supplier }}">{{ $supplier->supplier_name }} - {{ $supplier->supplier_name_urdu }}</option>'
                        );
                    @endforeach
                }
            }

            $('#truck-table-body').on('click', '.truck-details', function() {
                const checkbox = $(this).find('.truck-checkbox')[0];
                checkbox.checked = !checkbox.checked;
                $(checkbox).trigger('change');
            });

            function filterTruckDetails() {
                const allTrucks = {};

                $('.truck-details').each(function() {
                    const truckNo = $(this).data('truck-no');
                    const truckId = $(this).data('truck-id');
                    const isSelected = selectedTruckNumbers.includes(truckNo);

                    // Track all trucks with their selection status
                    if (!allTrucks[truckNo]) {
                        allTrucks[truckNo] = {
                            count: 0,
                            checked: 0
                        };
                    }
                    allTrucks[truckNo].count++;
                    if (isSelected) {
                        allTrucks[truckNo].checked++;
                    }
                });

                // Enable or disable rows based on the selection count for each truck number
                $('.truck-details').each(function() {
                    const truckNo = $(this).data('truck-no');
                    const allSelected = allTrucks[truckNo].checked === allTrucks[truckNo].count;

                    if (allSelected) {
                        $(this).find('.truck-checkbox').prop('disabled', false); // Enable checkbox
                        $(this).removeClass('disabled');
                    } else {
                        if (selectedTruckNumbers.length > 0 && !selectedTruckNumbers.includes(truckNo)) {
                            $(this).find('.truck-checkbox').prop('disabled', true); // Disable checkbox
                            $(this).addClass('disabled');
                        } else if ($('.truck-checkbox:checked').length == 0) {
                            $('#selected-trucks').text('Selected Truck: ' + '');
                            $('#truck').html('');
                            $('#truck-toggle').html('- Select -');
                            $('#set_supplier_name').val('');
                            $('#rent_received').val('');
                            $(this).find('.truck-checkbox').prop('disabled', false); // Enable checkbox
                            $(this).removeClass('disabled');
                        }
                    }
                });
            }

            function showOnlyThisTruckDetails(searchValue) {
                searchValue = searchValue.toLowerCase();
                document.querySelectorAll('#truck-table-body .truck-details').forEach(function(row) {
                    const cells = row.querySelectorAll('td');
                    let matchFound = false;

                    cells.forEach(function(cell) {
                        if (cell.textContent.toLowerCase().includes(searchValue)) {
                            matchFound = true;
                        }
                    });

                    row.style.display = matchFound ? '' : 'none';
                });
            }
        });
    </script>


    <script>
        $(window).on('load', function() {
            setTimeout(function() {

                $('.dropdown-content').css('display', 'block');
                var $input = $('#truck-search');

                // Make sure it's visible before focusing
                $input.css('display', 'block');

                // Focus after the browser has rendered
                setTimeout(function() {
                    $input.trigger('focus'); // jQuery focus
                    // Native fallback
                    if ($input.length) {
                        $input[0].focus({
                            preventScroll: true
                        });
                    }
                }, 50);
            }, 600);
        });
        $(function() {
            document.addEventListener('keydown', function(event) {
                const activeElement = document.activeElement;

                // Check for Tab key press
                if (event.key === "Tab") {

                    const allRemarksInputs = document.querySelectorAll('textarea[name="remarks[]"]');
                    const lastRemarksInput = allRemarksInputs[allRemarksInputs.length - 1];


                    // If activeElement is the last remarks input, add a new row
                    if (activeElement === lastRemarksInput) {
                        event.preventDefault(); // Prevent default tab behavior

                        // Trigger the click event of the 'Add More' button
                        document.getElementById('add-item').click();

                        // Focus on the newly added row's first input field (e.g., items select)
                        setTimeout(function() {
                            const newItemsInput = document.querySelectorAll(
                                'select[name="productCat[]"]');
                            newItemsInput[newItemsInput.length - 1]
                                .focus(); // Focus on the last added input
                        }, 0);
                    }
                }

                // Detect Alt + D to delete the selected row
                if (event.altKey && event.key === 'd') {
                    event.preventDefault();

                    const focusedElement = document.activeElement;
                    const focusedRow = focusedElement.closest(
                        '.delete_row'); // Find the closest row (div.row)

                    // If a row is focused, remove it
                    if (focusedRow) {
                        focusedRow.remove(); // Remove the focused row

                        // You can add additional functionality like recalculating totals here
                        // Example: updateTotals();
                    } else {
                        showErrorNotification(
                            'Please select the row you want to delete.\nبراہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
                        );
                    }
                }
            });

            // Initialize all Select2 fields; add class="select2" to your <select> elements
            $('select.select2').select2({
                placeholder: '- Select -',
                allowClear: true,
                width: '100%' // optional
            });

            // Ensure search field focuses when any Select2 opens
            $(document).on('select2:open', function() {
                setTimeout(() => {
                    const search = document.querySelector('.select2-search__field');
                    if (search) search.focus();
                }, 0);
            });

            // Visibility and tabbables
            function isActuallyVisible(el) {
                if (!el || el.disabled) return false;
                const style = window.getComputedStyle(el);
                if (style.visibility === 'hidden' || style.display === 'none') return false;
                // Hidden select backing Select2 is allowed
                if (el.offsetParent === null && !el.classList.contains('select2-hidden-accessible')) return false;
                return true;
            }

            function getFocusables() {
                return Array.from(document.querySelectorAll(
                    'input, textarea, select, button, [tabindex]:not([tabindex="-1"])'
                )).filter(el => {
                    if (el.disabled) return false;
                    const isSelect2Hidden = el.classList.contains('select2-hidden-accessible');
                    return isActuallyVisible(el) || isSelect2Hidden;
                });
            }

            function focusNextField(current) {
                const focusables = getFocusables();
                const idx = focusables.indexOf(current);
                if (idx === -1) return;
                for (let i = idx + 1; i < focusables.length; i++) {
                    const next = focusables[i];
                    if (!next) break;

                    // If next is a Select2-backed select, open it
                    if (next.tagName === 'SELECT' && next.classList.contains('select2-hidden-accessible')) {
                        $(next).select2('open');
                        return;
                    }

                    if (isActuallyVisible(next)) {
                        next.focus();
                        return;
                    }
                }
            }

            function focusPrevField(current) {
                const focusables = getFocusables();
                const idx = focusables.indexOf(current);
                if (idx === -1) return;
                for (let i = idx - 1; i >= 0; i--) {
                    const prev = focusables[i];
                    if (!prev) break;

                    if (prev.tagName === 'SELECT' && prev.classList.contains('select2-hidden-accessible')) {
                        $(prev).select2('open');
                        return;
                    }

                    if (isActuallyVisible(prev)) {
                        prev.focus();
                        return;
                    }
                }
            }

            // Global Tab/Shift+Tab across native fields
            $(document).on('keydown', 'input, textarea, select, button, [tabindex]:not([tabindex="-1"])', function(
                e) {
                if (e.key === 'Tab') {
                    e.preventDefault();
                    if (e.shiftKey) {
                        focusPrevField(this);
                    } else {
                        focusNextField(this);
                    }
                }
            });


            $(document).on('keydown', '.select2-search__field', function(e) {
                if (e.key === 'Tab') {
                    e.preventDefault();

                    const enterEvent = new KeyboardEvent('keydown', {
                        key: 'Enter',
                        code: 'Enter',
                        keyCode: 13,
                        which: 13,
                        bubbles: true
                    });
                    this.dispatchEvent(enterEvent);


                    const $select = $('.select2-container--open').prev('select');
                    if ($select.length) {
                        $select.select2('close');
                        const rawSelect = $select[0];
                        setTimeout(() => {
                            if (e.shiftKey) {
                                focusPrevField(rawSelect);
                            } else {
                                focusNextField(rawSelect);
                            }
                        }, 10);
                    }
                }
            });


            // $(document).on('keydown', '.select2-search__field', function(e) {
            //     if (e.key === 'Enter') {
            //         e.stopPropagation();
            //     }
            // });
        });
    </script>
@endpush
