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

                                <!-- 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>{{ $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->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" 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="کل خرچہ درج کریں"
                                    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" 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" 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" 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 readonly 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" 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" 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" 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 readonly value="{{ $labour->rate }}" type="text"
                                    class="form-control form-control-urdu" id="labour" name="labour"
                                    placeholder="مزدوری درج کریں" value="{{ old('labour') }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="market_fees" class="form-label">:بازار کی فیس</label>
                                <input readonly value="{{ $bazaar_fees->rate }}" type="text"
                                    class="form-control form-control-urdu" 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 readonly value="{{ $post_expense->rate }}" type="text"
                                    class="form-control form-control-urdu" 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" 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" 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">
        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() {
            // 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));
        }

        // 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');
                const rentReceived = $(this).closest('tr').data('rent-received');
                document.getElementById('rent_received').value = rentReceived;

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

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