@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 action="{{ route('b_cheque.update', ['id' => Crypt::encrypt($b_cheque->id_b_cheque)]) }}"
                    method="POST">
                    @csrf
                    @method('PUT')
                    <!-- 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"
                        value="{{ $b_cheque->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="" readonly
                                    required value="{{ $b_cheque->date ?? '' }}">
                            </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="{{ $b_cheque->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>

                                <!-- Hidden native select element -->
                                <select class="form-control d-none" name="good_receipts_truck_id" id="truck" required>
                                    <option value="">- Select -</option>
                                    @foreach ($soldTrucks as $truck)
                                        <option value="{{ $truck->id_truck }}"
                                            {{ $b_cheque->good_receipts_truck_id == $truck->id_truck ? 'selected' : '' }}>
                                            {{ $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">
                                        {{ $b_cheque->goodReceiptTruck->truck_no }}</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 }}">
                                                                <td>
                                                                    @php
                                                                        $isSameTruck =
                                                                            $b_cheque->goodReceiptTruck->id_truck ==
                                                                            $sale->goodReceiptTruck->id_truck;
                                                                    @endphp
                                                                    <input type="checkbox" class="truck-checkbox" hidden
                                                                        data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                        {{ $isSameTruck ? 'checked' : '' }}>
                                                                    <span class="checkbox-icons">
                                                                        <i
                                                                            class="fa-solid fa-circle-check text-success {{ $isSameTruck ? '' : 'd-none' }}"></i>
                                                                        <i
                                                                            class="fa-regular fa-circle-xmark text-dark {{ !$isSameTruck ? '' : 'd-none' }}"></i>
                                                                    </span>
                                                                </td>
                                                                <td>{{ $sale->goodReceiptTruck->truck_no }}</td>
                                                                <td>
                                                                    {{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->supplier_name ?? 'N/A' }}
                                                                </td>
                                                                <td>{{ $saleDetails->items_main_cate }}</td>
                                                                <td>{{ $saleDetails->items_parent_cate }}</td>
                                                                <td>{{ $saleDetails->items_child_cate }}</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->id_supplier == $b_cheque->supplier_id ? 'selected' : '' }}>
                                            {{ $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="{{ $b_cheque->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="{{ $b_cheque->detail }}">
                            </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="1" {{ $b_cheque->status == '1' ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ $b_cheque->status == '0' ? 'selected' : '' }}>In-Active</option>
                            </select>
                            @error('bCheck_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <!-- Item Details Section -->
                        <div class="col-md-12 mt-5">
                            <h4>Item Details</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">
                                        @foreach ($b_cheque->items as $key => $items)
                                            <tr data-truck-no="{{ $b_cheque->goodReceiptTruck->id_truck }}"
                                                data-salesdetails-id="{{ $items->sales_d_id }}">
                                                <input type="hidden" class="form-control" name="salesDeId[]"
                                                    value="{{ $items->sales_d_id }}">
                                                <td><input type="text" class="form-control" name="mainCate[]" hidden
                                                        value="{{ $items->main_cate }}">{{ $items->main_cate }}</td>
                                                <td><input type="text" class="form-control" name="parentCate[]" hidden
                                                        value="{{ $items->parent_cate }}">{{ $items->parent_cate }}</td>
                                                <td><input type="text" class="form-control" name="childCate[]" hidden
                                                        value="{{ $items->child_cate }}">{{ $items->child_cate }}</td>
                                                <td><input type="text" class="form-control" name="marka[]" hidden
                                                        value="{{ $items->marka }}">{{ $items->marka }}</td>
                                                <td><input type="text" class="form-control" name="bori[]" hidden
                                                        value="{{ $items->bori }}">{{ $items->bori }}</td>
                                                <td><input type="text" class="form-control" name="weight[]" hidden
                                                        value="{{ $items->weight }}">{{ $items->weight }}</td>
                                                <td><input type="text" class="form-control" name="rate[]" hidden
                                                        value="{{ $items->rate }}">{{ $items->rate }}</td>
                                                <td><input type="text" class="form-control" name="amount[]" hidden
                                                        value="{{ $items->amount }}">{{ $items->amount }}</td>
                                            </tr>
                                        @endforeach
                                    </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" 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" id="total_expanse_amount"
                                    readonly name="total_expanse_amount" placeholder="کل خرچہ درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="save_amount" class="form-label">:بچت</label>
                                <input type="text" class="form-control form-control-urdu" id="save_amount"
                                    name="save_amount" placeholder=" بچت درج کریں">
                            </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" id="total_bori" readonly
                                    name="total_bori" placeholder="کل بوریاں درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="F" class="form-label">:وزن</label>
                                <input type="text" class="form-control form-control-urdu" id="total_weight" readonly
                                    name="total_weight" placeholder="وزن درج کریں">
                            </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 type="number" class="form-control form-control-urdu" id="commission_rate"
                                    name="commission_rate" placeholder="کمیشن ریٹ درج کریں" max="100"
                                    value="{{ $b_cheque->details->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" id="commission" readonly
                                    name="commission" placeholder="کمیشن درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="more" class="form-label">:مزید</label>
                                <input type="text" class="form-control form-control-urdu" id="more"
                                    name="extra_pay" placeholder="اضافی رقم درج کریں"
                                    value="{{ $b_cheque->details->else_more_amount ?? '' }}">
                            </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="تفصیلات درج کریں">{{ $b_cheque->details->payment_details ?? '' }}</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" id="rent_received"
                                    name="rent_received" placeholder="کرایہ وصول کریں"
                                    value="{{ $b_cheque->details->rent_recieve_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label">:مزدوری</label>
                                <input type="text" class="form-control form-control-urdu" id="labour"
                                    name="labour" placeholder="مزدوری درج کریں"
                                    value="{{ $b_cheque->details->labour_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="market_fees" class="form-label">:بازار کی فیس</label>
                                <input type="text" class="form-control form-control-urdu" id="market_fees"
                                    name="market_fees" placeholder="بازار کی فیس درج کریں"
                                    value="{{ $b_cheque->details->market_fees_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="post_expense" class="form-label">:پوسٹ خرچ</label>
                                <input type="text" class="form-control form-control-urdu" id="post_expense"
                                    name="post_expense" placeholder="پوسٹ خرچ درج کریں"
                                    value="{{ $b_cheque->details->post_expense_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="miscellaneous_expense" class="form-label">:متفرق خرچ</label>
                                <input type="text" class="form-control form-control-urdu" id="miscellaneous_expense"
                                    name="miscellaneous_expense" placeholder="متفرق خرچ درج کریں"
                                    value="{{ $b_cheque->details->miscellaneous_expense_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="cash" class="form-label">:نقد</label>
                                <input type="text" class="form-control form-control-urdu" id="cash"
                                    name="cash" placeholder="نقد رقم درج کریں"
                                    value="{{ $b_cheque->details->cash_amount ?? '' }}">
                            </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">Update</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        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() {
            // 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"
            });

            // // Handle input changes for updating totals
            // handleInputChange();

            // // Update totals on page load
            // updateTotals();
        });

        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;

        //     $('#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;
        //     });

        //     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 commission = parseFloat($('input[name="commission"]').val()) || 0;
        //     let more = parseFloat($('input[name="extra_pay"]').val()) || 0;
        //     let rent_received = parseFloat($('input[name="rent_received"]').val()) || 0;
        //     let cash = parseFloat($('input[name="cash"]').val()) || 0;

        //     let cashReceived = initialCashReceived + labour + marketfee + postexp + miscellaneousExp + commission + more +
        //         cash + rent_received;
        //     let commissionVal = (totalAmount * commissionp) / 100;

        //     $('#total_bori').val(totalBori);
        //     $('#total_weight').val(totalWeight);
        //     $('#total_amount').val(totalAmount);
        //     $('#total_expanse_amount').val(cashReceived);
        //     $('#commission').val(commissionVal.toFixed(2));
        //     $('#save_amount').val(totalAmount - cashReceived);
        // }

        // function handleInputChange() {
        //     $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"], input[name="weight[]"]',
        //         updateTotals);
        //     $('input[name="extra_pay"], input[name="commission"], input[name="miscellaneous_expense"], input[name="post_expense"], input[name="market_fees"], input[name="labour"], #total_expanse_amount, input[name="commission_rate"], input[name="rent_received"], input[name="cash"]')
        //         .on('input', updateTotals);
        // }
        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));

            // Calculate the total expanses (cash received) including commission and other expenses
            let cashReceived = initialCashReceived + labour + 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));
        }

        // 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="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');

                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);

                    // 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');

                // Always append a new row for each selected truck entry
                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 = truckRow.find('td:nth-child(8)').text();
                const weight = truckRow.find('td:nth-child(9)').text();
                const rate = truckRow.find('td:nth-child(10)').text();
                const amount = truckRow.find('td:nth-child(11)').text();

                // Append the selected truck's details as a new row
                $('#item-details').append(`
                    <tr data-truck-no="${truckNo}"
                        data-salesdetails-id="${salesDeId}">
                        <input type="hidden" class="form-control" name="salesDeId[]" value="${salesDeId}">
                        <td><input type="text" class="form-control" name="mainCate[]" hidden value="${mainCate}">${mainCate}</td>
                        <td><input type="text" class="form-control" name="parentCate[]" hidden value="${parentCate}">${parentCate}</td>
                        <td><input type="text" class="form-control" name="childCate[]" hidden value="${childCate}">${childCate}</td>
                        <td><input type="text" class="form-control" name="marka[]" hidden value="${marka}">${marka}</td>
                        <td><input type="text" class="form-control" name="bori[]" hidden value="${bori}">${bori}</td>
                        <td><input type="text" class="form-control" name="weight[]" hidden value="${weight}">${weight}</td>
                        <td><input type="text" class="form-control" name="rate[]" hidden value="${rate}">${rate}</td>
                        <td><input type="text" class="form-control" name="amount[]" hidden value="${amount}">${amount}</td>
                    </tr>
                `);
                updateTotals();
            }

            // Function to remove a truck's details from the Item Details table when unchecked
            function removeTruckDetails(salesDetailsId) {
                // $(`#item-details tr[data-truck-no="${truckNo}"]`).remove();
                $(`#item-details tr[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('{{ $b_cheque->supplier_name }}');
                    $supplierDropdown.append('<option value="">- Select -</option>');
                    @foreach ($suppliers as $key => $supplier)
                        $supplierDropdown.append(
                            '<option value="{{ $supplier->id_supplier }}" {{ $supplier->id_supplier == $b_cheque->supplier_id ? 'selected' : '' }}>{{ $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('');
                            if ('{{ $b_cheque->goodReceiptTruck->truck_no }}' != null) {
                                $('#truck-toggle').html('{{ $b_cheque->goodReceiptTruck->truck_no }}');
                            } else {
                                $('#truck-toggle').html('');
                            }
                            $('#set_supplier_name').val('{{ $b_cheque->supplier_name }}');
                            $(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>
@endpush
