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

                    <div class="row row-sm mg-b-20">
                        <div class="col-md-2">
                            <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>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <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">
                            </div>
                        </div>

                        {{-- <div class="col-md-8">
                            <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 ($trucks as $truck)
                                        <option value="{{ $truck->id_truck }}">
                                            {{ $truck->truck_no }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    <div class="dropdown-toggle form-control" id="truck-toggle">- Select -</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-8">
                            <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 }}">
                                            {{ $truck->truck_no }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    <div class="dropdown-toggle form-control" id="truck-toggle">- Select -</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>Main Category</th>
                                                    <th>Parent Category</th>
                                                    <th>Child Category</th>
                                                    <th>Marka</th>
                                                    <th>Quantity</th>
                                                    <th>Weight</th>
                                                    <th>Price</th>
                                                </tr>
                                            </thead>
                                            {{-- <tbody id="truck-table-body">
                                                @foreach ($sales as $sale)
                                                    @foreach ($sale->salesItemsDetails as $saleDetails)
                                                        <tr class="truck-details" data-truck-id="{{ $sale->goodReceiptTruck->first()->id_truck }}">
                                                            <td>{{ $sale->goodReceiptTruck->first()->truck_no }}</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>
                                                        </tr>
                                                    @endforeach
                                                @endforeach
                                            </tbody> --}}
                                            <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 }}">
                                                                <td>{{ $sale->goodReceiptTruck->truck_no }}</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>
                                                            </tr>
                                                        @endforeach
                                                    @endif
                                                @endforeach
                                            </tbody>

                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>


                        <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">
                            </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="detail" id="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" 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>

                        <!-- 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>
                                        <tr>
                                            <td>
                                                <select class="form-control marka-select" name="marka[]" id="marka">
                                                    <option value="">- Select -</option>
                                                </select>
                                            </td>
                                            <td>
                                                <select class="form-control item-select" name="items_name[]"
                                                    id="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"
                                                    onclick="removeRow(this)">
                                                    <i class="text-danger fa-solid fa-trash-can"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </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" 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" 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"
                                    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"
                                    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">
                            </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" 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" 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="تفصیلات درج کریں"></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="کرایہ وصول کریں">
                            </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="مزدوری درج کریں">
                            </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="بازار کی فیس درج کریں">
                            </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="پوسٹ خرچ درج کریں">
                            </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="متفرق خرچ درج کریں">
                            </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="نقد رقم درج کریں">
                            </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">
        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'
            });

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

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

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

            // 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" name="weight[]"></td>
    //     <td><input type="text" class="form-control" name="rate[]"></td>
    //     <td><input type="text" class="form-control" name="amount[]"></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 = 1;
        //     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>`;

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

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

        //     $('#item-table tbody').append(row);
        //     populateMarkaAndItems($('#item-table tbody tr:last'));

        //     itemIndex++;
        // }

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

            // Create the new row HTML
            var row = `
                <tr class="delete_row">
                    <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>');
                    }
                });
            }
        }

        $('#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));
        //     });
        // }
        function showOnlyThisTruckDetails(searchValue) {
            // Convert search value to lowercase
            searchValue = searchValue.toLowerCase();

            // Loop through all table rows to filter results
            document.querySelectorAll("#truck-table-body .truck-details").forEach(function(row) {
                // Get all the columns (cells) in the row
                const cells = row.querySelectorAll("td");
                let matchFound = false;

                // Check each cell's content for the search value
                cells.forEach(function(cell) {
                    if (cell.textContent.toLowerCase().includes(searchValue)) {
                        matchFound = true; // If a match is found in any cell, set this to true
                    }
                });

                // Show or hide the row based on whether a match was found
                row.style.display = matchFound ? "" : "none";
            });
        }



        document.addEventListener('keydown', function(event) {
            const activeElement = document.activeElement;

            // Check for Tab key press
            if (event.key === "Tab") {
                const allRemarksInputs = document.querySelectorAll('input[name="amount[]"]');
                const lastRemarksInput = allRemarksInputs[allRemarksInputs.length - 1];

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

                    // Trigger the click event of the 'Add More' button
                    addRow();

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

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

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

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

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