@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;
        /* color: black !important; */
    }

    .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;
    }
</style>

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>B-Cheque</span>
        <span>Edit B-Cheque</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Edit 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">Edit 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

                    <div class="row row-sm mg-b-20">
                        <div class="col-md-3">
                            <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"
                                    autocomplete="off" value="{{ old('bCheck_date', $b_cheque->date) }}" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <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', $b_cheque->pb_no) }}">
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label 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 ($trucks 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="dropdown-toggle form-control" id="truck-toggle">{{ $truck->truck_no }}</div>
                                    <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>Truck No</th>
                                                    <th>Item</th>
                                                    <th>Marka</th>
                                                    <th>Quantity</th>
                                                    <th>Weight</th>
                                                    <th>Price</th>
                                                </tr>
                                            </thead>
                                            <tbody id="truck-table-body">
                                                @foreach ($trucks as $truck)
                                                    @foreach ($truck->goodReceipts as $receipt)
                                                        @foreach ($receipt->goodReceiptDetails as $detail)
                                                            <tr class="truck-details"
                                                                data-truck-id="{{ $truck->id_truck }}">
                                                                <td>{{ $truck->truck_no }}</td>
                                                                <td>{{ $detail->goods_name }}</td>
                                                                <td>{{ $detail->marka }}</td>
                                                                <td>{{ $detail->bori }}</td>
                                                                <td>{{ $detail->weight }}</td>
                                                                <td>{{ $detail->rate }}</td>
                                                            </tr>
                                                        @endforeach
                                                    @endforeach
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label 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 $supplier)
                                        <option value="{{ $supplier->id_supplier }}"
                                            {{ $b_cheque->supplier_id == $supplier->id_supplier ? '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 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', $b_cheque->bilty_no) }}">
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label az-content-label urdu-font" for="detail"
                                    style="float: right;">
                                    تفصیل
                                </label>
                                <input type="text" class="form-control" name="detail" id="detail"
                                    value="{{ old('detail', $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="">Select</option>
                                <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: 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>
                                            <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-body">
                                        @foreach ($b_cheque->items as $item)
                                            <tr>
                                                <td>
                                                    <select class="form-control marka-select" name="marka[]"
                                                        id="marka">
                                                        <option value="{{ $item->marka }}">
                                                            {{ $item->marka }}
                                                        </option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <select class="form-control item-select" name="items_name[]"
                                                        id="items_name">
                                                        <option value="{{ $item->item }}">
                                                            {{ $item->item }}
                                                        </option>
                                                    </select>
                                                </td>
                                                <td><input type="text" class="form-control" name="bori[]"
                                                        value="{{ $item->bori }}"></td>
                                                <td><input type="text" class="form-control weight-input"
                                                        name="weight[]" value="{{ $item->weight }}"
                                                        oninput="calculateAmount(this)"></td>
                                                <td><input type="text" class="form-control rate-input" name="rate[]"
                                                        value="{{ $item->rate }}" oninput="calculateAmount(this)"></td>
                                                <td><input type="text" class="form-control amount-input"
                                                        name="amount[]" value="{{ $item->amount }}" readonly></td>
                                                <td>
                                                    <button type="button" class="btn rounded shadow-base"
                                                        onclick="removeRow(this)">
                                                        <i class="text-danger fa-solid fa-trash-can"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-az-primary btn-block mt-2" onclick="addRow()">
                                    <span class="mdi mdi-arrow-expand-up"></span> Add More
                                </button>
                            </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"
                                    name="total_amount"
                                    value="{{ old('total_amount', $b_cheque->details->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"
                                    name="total_expanse_amount"
                                    value="{{ old('total_expanse_amount', $b_cheque->details->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" value="{{ old('save_amount', $b_cheque->details->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"
                                    name="total_bori" value="{{ old('total_bori', $b_cheque->details->total_bori) }}"
                                    placeholder="کل بوریاں درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="weight" class="form-label">:وزن</label>
                                <input type="text" class="form-control form-control-urdu" id="total_weight"
                                    name="total_weight"
                                    value="{{ old('total_weight', $b_cheque->details->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"
                                    value="{{ old('commission_rate', $b_cheque->details->commission_rate) }}"
                                    placeholder="کمیشن ریٹ درج کریں" max="100">
                            </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"
                                    name="commission"
                                    value="{{ old('commission', $b_cheque->details->commission_amount) }}"
                                    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="more" value="{{ old('more', $b_cheque->details->else_more_amount) }}"
                                    placeholder="اضافی رقم درج کریں">
                            </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="تفصیلات درج کریں">{{ old('payment_details', $b_cheque->details->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"
                                    value="{{ old('rent_received', $b_cheque->details->rent_recieve_amount) }}"
                                    placeholder="کرایہ وصول کریں">
                            </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" value="{{ old('labour', $b_cheque->details->labour_amount) }}"
                                    placeholder="مزدوری درج کریں">
                            </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"
                                    value="{{ old('market_fees', $b_cheque->details->market_fees_amount) }}"
                                    placeholder="بازار کی فیس درج کریں">
                            </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"
                                    value="{{ old('post_expense', $b_cheque->details->post_expense_amount) }}"
                                    placeholder="پوسٹ خرچ درج کریں">
                            </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"
                                    value="{{ old('miscellaneous_expense', $b_cheque->details->miscellaneous_expense_amount) }}"
                                    placeholder="متفرق خرچ درج کریں">
                            </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" value="{{ old('cash', $b_cheque->details->cash_amount) }}"
                                    placeholder="نقد رقم درج کریں">
                            </div>
                        </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>
                </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();
            }
        }

        // Call calculateAmount for each row on page load if both weight and rate are already filled
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('tr').forEach(function(row) {
                let weightInput = row.querySelector('.weight-input');
                let rateInput = row.querySelector('.rate-input');

                if (weightInput && rateInput) {
                    calculateAmount(weightInput);
                    updateTotals();
                }
            });
        });

        $(document).ready(function() {
            // Initialize Select2 and Datepicker
            $('#suppliers').select2({
                theme: 'default'
            });
            $("#bCheck_date").datepicker({
                dateFormat: "yy-mm-dd"
            });

            $('#marka').select2({
                placeholder: "Select Marka",
                allowClear: true
            });

            $('#items_name').select2({
                placeholder: "Select Item",
                allowClear: true
            });

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

            var truckId = $('#truck').val();
            if (truckId) {
                $('#item-table tbody tr').each(function(index) {
                    var itemDetail = {!! json_encode($b_cheque->items) !!}[index];
                    populateMarkaAndItems($(this), itemDetail.marka, itemDetail.item);
                });
            }

            // Update totals on page load
            updateTotals();

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

            // Handle truck selection
            $('.truck-details').click(function() {
                var truckId = $(this).data('truck-id');
                var truckNumber = $(this).find('td:first').text();

                $('#truck').val(truckId);
                $('#truck-toggle').text(truckNumber);
                $('.dropdown-content').hide();

                if (truckId) {
                    $('#item-table tbody tr').each(function() {
                        populateMarkaAndItems($(this));
                    });
                }
            });

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

            // Add new row
            $('#item-table').on('click', '.add-row', function() {
                addRow();
            });

            // Remove row
            $('#item-table').on('click', '.remove-row', function() {
                removeRow(this);
            });

            // Add new bori row
            $('#bori-table').on('click', '.add-bori-row', function() {
                addBoriRow();
            });

            // Remove bori row
            $('#bori-table').on('click', '.remove-bori-row', function() {
                removeBoriRow(this);
            });

            // Filter the truck table based on search input
            $('#truck-search').on('input', function() {
                showOnlyThisTruckDetails(this.value);
            });
        });

        // function addRow() {
        //     var row = `<tr>
    //         <td><select class="form-control marka-select" name="marka[]"><option value="">- Select -</option></select></td>
    //         <td><select class="form-control item-select" name="items_name[]"><option value="">- Select -</option></select></td>
    //         <td><input type="text" class="form-control" name="bori[]"></td>
    //          <td><input type="text" class="form-control weight-input"
    //                 name="weight[]" oninput="calculateAmount(this)"></td>
    //         <td><input type="text" class="form-control rate-input" name="rate[]"
    //                 oninput="calculateAmount(this)"></td>
    //         <td><input type="text" class="form-control amount-input"
    //                 name="amount[]" readonly></td>
    //         <td><button type="button" class="btn rounded shadow-base remove-row"><i class="text-danger fa-solid fa-trash-can"></i></button></td>
    //     </tr>`;
        //     $('#item-table tbody').append(row);
        //     populateMarkaAndItems($('#item-table tbody tr:last'));
        // }

        function addRow() {
            let itemIndex = $('#item-table tbody tr').length;

            // Create the new row HTML
            var row = `
                <tr>
                    <td>
                        <select class="form-control marka-select" name="marka[]" id="marka-row-${itemIndex}">
                            <option value="">- Select -</option>
                        </select>
                    </td>
                    <td>
                        <select class="form-control item-select" name="items_name[]" id="items-row-${itemIndex}">
                            <option value="">- Select -</option>
                        </select>
                    </td>
                    <td><input type="text" class="form-control" name="bori[]"></td>
                    <td><input type="text" class="form-control weight-input" name="weight[]" oninput="calculateAmount(this)"></td>
                    <td><input type="text" class="form-control rate-input" name="rate[]" oninput="calculateAmount(this)"></td>
                    <td><input type="text" class="form-control amount-input" name="amount[]" readonly></td>
                    <td>
                        <button type="button" class="btn rounded shadow-base remove-row">
                            <i class="text-danger fa-solid fa-trash-can"></i>
                        </button>
                    </td>
                </tr>`;

            // Append the new row to the table
            $('#item-table tbody').append(row);

            // Initialize select2 for the new row after it is appended
            $(`#marka-row-${itemIndex}`).select2({
                placeholder: "Select Marka",
                allowClear: true
            });

            $(`#items-row-${itemIndex}`).select2({
                placeholder: "Select Item",
                allowClear: true
            });

            // Call the function to populate select options (if necessary)
            populateMarkaAndItems($('#item-table tbody tr:last'));
        }


        // function addRow() {
        //     let table = document.getElementById('item-table').getElementsByTagName('tbody')[0];
        //     let newRow = table.rows[0].cloneNode(true);

        //     // Reset values for the new row
        //     newRow.querySelectorAll('input').forEach(input => input.value = '');

        //     // Append the new row to the table
        //     table.appendChild(newRow);

        //     populateMarkaAndItems($('#item-table tbody tr:last'));
        // }

        function removeRow(button) {
            $(button).closest('tr').remove();
            updateTotals();
        }

        function addBoriRow() {
            var row = `<tr>
            <td><input type="text" class="form-control" name="bori_number[]"></td>
            <td><input type="text" class="form-control" name="per_bori_weight[]"></td>
            <td><button type="button" class="btn rounded shadow-base remove-bori-row"><i class="text-danger fa-solid fa-trash-can"></i></button></td>
        </tr>`;
            $('#bori-table tbody').append(row);
        }

        function removeBoriRow(button) {
            $(button).closest('tr').remove();
        }

        // function populateMarkaAndItems(newRow) {
        //     var truckId = $('#truck').val();
        //     if (truckId) {
        //         $.ajax({
        //             url: '{{ route('get.truck.items', '__TRUCK_ID__') }}'.replace('__TRUCK_ID__', truckId),
        //             type: 'GET',
        //             success: function(data) {
        //                 newRow.find('.marka-select').empty().append('<option value="">- Select -</option>');
        //                 $.each(data.markas, function(_, marka) {
        //                     newRow.find('.marka-select').append(
        //                         `<option value="${marka}">${marka}</option>`);
        //                 });
        //                 newRow.find('.item-select').empty().append('<option value="">- Select -</option>');
        //             }
        //         });
        //     }
        // }
        function populateMarkaAndItems(newRow, selectedMarka = null, selectedItem = null) {
            var truckId = $('#truck').val();
            if (truckId) {
                $.ajax({
                    url: '{{ route('get.truck.items', '__TRUCK_ID__') }}'.replace('__TRUCK_ID__', truckId),
                    type: 'GET',
                    success: function(data) {
                        var markaSelect = newRow.find('.marka-select');
                        markaSelect.empty().append('<option value="">- Select -</option>');
                        $.each(data.markas, function(_, marka) {
                            markaSelect.append(
                                `<option value="${marka}" ${marka == selectedMarka ? 'selected' : ''}>${marka}</option>`
                            );
                        });

                        var itemSelect = newRow.find('.item-select');
                        if (selectedItem == null) {
                            itemSelect.empty().append('<option value="">- Select -</option>');
                        }
                        if (selectedMarka && data.items[selectedMarka]) {
                            $.each(data.items[selectedMarka], function(id, name) {
                                itemSelect.append(
                                    `<option value="${name}" ${name == selectedItem ? 'selected' : ''}>${name}</option>`
                                );
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error fetching truck items:', error);
                    }
                });
            }
        }

        $('#truck').on('change', function() {
            var truckId = $(this).val();
            if (truckId) {
                $('#item-table tbody tr').each(function() {
                    populateMarkaAndItems($(this));
                });
            }
        });

        $('#item-table').on('change', 'select[name="marka[]"]', function() {
            var marka = $(this).val();
            var truckId = $('#truck').val();
            if (marka && truckId) {
                $.ajax({
                    url: '{{ route('get.items.by.marka', ['truckId' => '__TRUCK_ID__', 'marka' => '__MARKA__']) }}'
                        .replace('__TRUCK_ID__', truckId).replace('__MARKA__', marka),
                    type: 'GET',
                    success: function(data) {
                        var itemSelect = $(this).closest('tr').find('.item-select');
                        itemSelect.empty().append('<option value="">- Select -</option>');
                        $.each(data, function(id, name) {
                            itemSelect.append(`<option value="${name}">${name}</option>`);
                        });
                    }.bind(this)
                });
            }
        });

        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="more"]').val()) || 0;

            let cashReceived = initialCashReceived + labour + marketfee + postexp + miscellaneousExp + commission + more;
            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="more"], 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"]')
                .on('input', updateTotals);
        }

        function showOnlyThisTruckDetails(searchKeys) {
            var filter = searchKeys.toLowerCase();
            $('#truck-table-body tr').each(function() {
                var truckNo = $(this).find('td:first').text().toLowerCase();
                $(this).toggle(truckNo.includes(filter));
            });
        }
    </script>
@endpush
