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

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

    .az-content-label {
        margin-top: 10px
    }

    .urdu-font {
        font-size: 17px;
    }
</style>

@section('content')
<!-- Breadcrumb and Page Title -->
<div class="az-content-breadcrumb">
    <span>Sales</span>
    <span>Create Sale</span>
</div>
<h2 class="az-content-title" style="display: inline">
    Create Sale
    <span>
        <a href="{{ route('sales.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 Sale</h5>
            <form action="{{ route('sales.store') }}" method="POST">
                @csrf
                <input type="hidden" name="getGoodsDetailId" id="setGoodsDetailId">
                <input type="hidden" name="getItemsMarka" id="setItemsMarka">
                <input type="hidden" name="getMainCateName" id="setMainCateName">
                <input type="hidden" name="getParentCateName" id="setParentCateName">
                <input type="hidden" name="getChildCateName" id="setChildCateName">

                <!-- 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-4 mt-2">
                        <div class="form-group">
                            <label class="az-content-label" for="sales_date">Date</label>
                            <input type="text" name="sales_date" id="sales_date" class="form-control"
                                placeholder="dd/mm/yyyy" readonly />
                        </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)
                                @foreach ($truck->goodReceiptDetails as $details)
                                <option value="{{ $truck->id_truck }}" data-bori="{{ $details->bori }}"
                                    data-grd-id="{{ $details->id_grd }}">
                                    {{ $truck->truck_no }} (Bori: {{ $details->bori }})
                                </option>
                                @endforeach
                                @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 ($trucks as $truck)
                                            @foreach ($truck->goodReceipts as $receipt)
                                            @foreach ($receipt->goodReceiptDetails as $detail)
                                            <tr class="truck-details" data-truck-id="{{ $truck->id_truck }}"
                                                data-details-id="{{ $detail->id_grd }}"
                                                data-items-marka="{{ $detail->marka }}"
                                                data-main-cate="{{ $detail->productMainCate->products_category_name }}"
                                                data-parent-cate="{{ $detail->productParentCate->name }}"
                                                data-child-cate="{{ $detail->productChildCate->name }}">
                                                <td>{{ $truck->truck_no }}</td>
                                                <td>
                                                    {{ $detail->productMainCate->products_category_name ?? null }}
                                                </td>
                                                <td>{{ $detail->productParentCate->name ?? null }}</td>
                                                <td>{{ $detail->productChildCate->name ?? null }}</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>

                <div class="row">
                    <div class="col-md-4">
                        <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="customer_id" id="customers" required>
                                <option value="">- Select -</option>
                                @foreach ($customers as $customer)
                                <option value="{{ $customer->id_customers }}">
                                    {{ $customer->customer_name }} - {{ $customer->customer_name_urdu }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                        @error('customer_id')
                        <span class="form-text text-danger">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="az-content-label urdu-font" for="bill_no" style="float: right;">
                                بل نمبر
                            </label>
                            <input type="text" class="form-control" name="bill_no" id="bill_no">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="az-content-label urdu-font" for="sales_status" style="float: right;">
                            حیثیت
                        </label>
                        <select id="sales_status" name="sales_status" class="form-control">
                            <option value="">Select</option>
                            <option value="1" selected>Active</option>
                            <option value="0" {{ old('sales_status') == '0' ? 'selected' : '' }}>
                                In-Active
                            </option>
                        </select>
                        @error('sales_status')
                        <span class="form-text text-danger">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mt-3">
                        <div class="form-group">
                            <label class="az-content-label urdu-font" for="details" style="float: right;">
                                تفصیلات
                            </label>
                            <textarea class="form-control" name="details" id="details" cols="5" rows="5"></textarea>
                        </div>
                    </div>
                    <div class="col-md-6 mt-3">
                        <div class="form-group">
                            <label class="az-content-label urdu-font" for="bori_details" style="float: right;">
                                بوری کی تفصیلات
                            </label>
                            <textarea class="form-control" name="bori_details" id="bori_details" cols="5" rows="5"></textarea>
                        </div>
                    </div>
                </div>
                <br>
                <br>
                <hr>
                <br>
                <br>
                <div class="row">
                    <div class="col-md-8">
                        <!-- Item Details Section -->
                        <div class="col-md-12">
                            <h4>Item Details{{-- / آئٹم کی تفصیلات --}}</h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table" 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; font-family: 'Jameel Noori Nastaleeq', serif; ">
                                                    Action
                                                </th> --}}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <input type="text" class="form-control bori-check" name="bori"
                                                    readonly>
                                                <span id="available-bori" style="display: none;">Available Bori in
                                                    stock: <span id="bori-quantity"></span></span>
                                                <span id="outofstock" class="text-danger"></span>
                                            </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" id="add-more-btn"
                                        onclick="addRow()">
                                        <span class="mdi mdi-arrow-expand-up"></span> Add More
                                    </button> --}}
                            </div>
                        </div>
                    </div>
                    <!-- Additional Bori Details Section -->
                    <div class="col-md-4">
                        <h4>Additional Bori Details{{-- / اضافی بوری کی تفصیلات --}}</h4>
                        <div class="shadow p-3 bg-light rounded">
                            <table class="table" id="bori-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;  font-family: 'Jameel Noori Nastaleeq', serif; ">
                                            Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><input type="text" class="form-control" name="bori_number[]"
                                                value="1" readonly></td>
                                        <td><input type="text" class="form-control" name="per_bori_weight[]"></td>
                                        <td>
                                            <button type="button" class="btn rounded shadow-base"
                                                onclick="removeBoriRow(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="addBoriRow()">
                                <span class="mdi mdi-arrow-expand-up"></span> Add More
                            </button>
                        </div>
                    </div>
                </div>
                <br>
                <br>
                <hr>
                <br>
                <br>
                <!-- Totals Section -->
                <div class="row mt-4">
                    <div class="col-md-12">
                        <h4>Totals</h4>
                        <div class="form-group row">
                            <label for="total_bori" class="col-sm-2 col-form-label">Total Bori:</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="total_bori" name="total_bori"
                                    readonly>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="remaining_amount" class="col-sm-2 col-form-label">Remaining
                                Amount:</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="remaining_amount"
                                    name="remaining_amount" readonly>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="cash_received" class="col-sm-2 col-form-label">Cash Received:</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="cash_received" name="cash_received">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="total_amount" class="col-sm-2 col-form-label">Total Amount:</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="total_amount" name="total_amount"
                                    readonly>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-5">
                    <a href="{{ route('sales.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                    <button type="submit" class="btn btn-az-primary pd-x-20">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div id="errorNotification" class="alert alert-danger position-fixed top-0 end-0 m-3" style="display: none;">
    <strong>Error!</strong> <span id="errorMessage">Please select the row you want to delete.</span>
</div>

@endsection

@push('scripts')
<script type="text/javascript">
    function calculateAmount(element) {
        let row = element.closest('tr'); // Get the current row
        let weight = parseFloat(row.querySelector('.weight-input').value) || 0;
        let rate = parseFloat(row.querySelector('.rate-input').value) || 0;

        // Calculate the amount (رقم)
        let amount = (rate * weight) / 40;

        // Set the calculated amount in the corresponding field
        row.querySelector('.amount-input').value = amount.toFixed(2);
        updateTotals();
    }

    function addRow() {
        let itemIndex = $('#item-table tbody tr').length;
        var row = `<tr>
                <td><input type="text" class="form-control bori-check" 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>`;
        $('#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
        // });

        // Populate marka and item selects in the new row
        populateMarkaAndItems($('#item-table tbody tr:last'));
    }

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

    let serialNumber = 2; // Initialize serial number

    function addBoriRow() {
        // Increment the serial number for the new row
        const currentSerialNumber = serialNumber++;

        // Create a new row with the updated serial number
        var row = `
                <tr>
                    <td><input type="text" class="form-control" name="bori_number[]" value="${currentSerialNumber}" readonly></td>
                    <td><input type="text" class="form-control" name="per_bori_weight[]"></td>
                    <td>
                        <button type="button" class="btn rounded shadow-base" onclick="removeBoriRow(this)">
                            <i class="text-danger fa-solid fa-trash-can"></i>
                        </button>
                    </td>
                </tr>`;

        $('#bori-table tbody').append(row);
        updateBoriDetails();
        updateTotals();
    }

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

    function updateBoriDetails() {

        $('#bori-table tbody tr').each(function(index) {
            $(this).find('td:first input').val(index + 1);
        });

        serialNumber = $('#bori-table tbody tr').length + 1;
        var totalBori = $('#bori-table tbody tr').length;
        var totalWeight = 0;

        $('#bori-table tbody tr').each(function() {
            var weight = parseFloat($(this).find('input[name="per_bori_weight[]"]').val()) || 0;
            totalWeight += weight;
        });

        // Update the Item Details section
        $('#item-table tbody tr').find('input[name="bori"]').val(totalBori);
        $('#item-table tbody tr').find('input[name="weight"]').val(totalWeight);

        // Update Totals section
        $('#total_bori').val(totalBori);
        $('#total_weight').val(totalWeight);
    }

    // Bind the input change event to update Bori Details automatically
    $('#bori-table').on('input', 'input[name="bori_number[]"], input[name="per_bori_weight[]"]', function() {
        updateBoriDetails();
    });

    // Initialize the page with any existing data
    // $(document).ready(function() {
    //     updateBoriDetails();
    // });

    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) {
                    // Populate marka select in the new row
                    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>`);
                    });

                    // Populate item select in the new row
                    newRow.find('.item-select').empty().append('<option value="">- Select -</option>');
                }
            });
        }
    }

    // Fetch items and markas when the truck is selected
    $('#truck').on('change', function() {
        var truckId = $(this).val();
        if (truckId) {
            $('#item-table tbody tr').each(function() {
                populateMarkaAndItems($(this));
            });
        }
    });

    // Fetch items based on selected marka
    $('#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 updateTotals() {
        let totalBori = 0;
        let totalAmount = 0;


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

            totalBori += bori;
            totalAmount += amount;
        });

        // Update Total Bori and Total Amount fields
        $('#total_bori').val(totalBori);
        $('#total_amount').val(totalAmount);

        // Update Remaining Amount based on Cash Received
        let cashReceived = parseFloat($('#cash_received').val()) || 0;
        $('#remaining_amount').val(totalAmount - cashReceived);
    }

    function handleInputChange() {
        // Recalculate totals when any input changes
        $('#item-table').on('input', 'input[name="bori"], input[name="amount"]', updateTotals);

        // Update remaining amount when cash received changes
        $('#cash_received').on('input', function() {
            let cashReceived = parseFloat($(this).val()) || 0;
            let totalAmount = parseFloat($('#total_amount').val()) || 0;
            $('#remaining_amount').val(totalAmount - cashReceived);
        });
    }

    // Initialize the input change handler
    $(document).ready(function() {
        var today = new Date();
        var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' +
            today.getDate()).slice(-2);

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

        // Initialize datepicker with custom format
        $("#sales_date").datepicker({
            dateFormat: "yy-mm-dd" // Customize the date format here
        });

        $('#customers').select2({
            theme: 'default'
        });

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

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

        handleInputChange();
        // Update totals when rows are added or removed
        $('#item-table').on('DOMSubtreeModified', updateTotals);

        // for truck custom dropdown

        // Toggle custom dropdown content
        $('#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();

            // Update the hidden select element
            $('#truck').val(truckId);

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

            // Update the custom dropdown display
            // $('#truck-toggle').text(truckNumber);

            // Hide the dropdown content
            $('.dropdown-content').hide();
        });

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

    // Filter the truck table based on search input
    function showOnlyThisTruckDetails(searchKeys) {
        // Convert searchKeys to lowercase for case-insensitive search
        var filter = searchKeys.toLowerCase();

        // Loop through all rows in the table and hide those that don't match the search query
        $('#truck-table-body tr').each(function() {
            var rowText = $(this).text().toLowerCase(); // Get the text of the entire row

            if (rowText.includes(filter)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }

    // Handle when a row is clicked
    document.querySelectorAll('#truck-table-body .truck-details').forEach(function(row) {
        row.addEventListener('click', function() {
            // Extract truck number and other details from the clicked row
            var truckId = row.getAttribute('data-truck-id');
            var detailID = row.getAttribute('data-details-id');
            var itemsMarka = row.getAttribute('data-items-marka');
            var mainCateName = row.getAttribute('data-main-cate');
            var parentCateName = row.getAttribute('data-parent-cate');
            var childCateName = row.getAttribute('data-child-cate');
            document.getElementById('setGoodsDetailId').value = detailID;
            document.getElementById('setItemsMarka').value = itemsMarka;
            document.getElementById('setMainCateName').value = mainCateName;
            document.getElementById('setParentCateName').value = parentCateName;
            document.getElementById('setChildCateName').value = childCateName;

            var bori = row.cells[5].textContent;
            var marka = row.cells[4].textContent;
            var mainCate = row.cells[1].textContent;
            var parentCate = row.cells[2].textContent;
            var childCate = row.cells[3].textContent;
            var boriSpan = document.getElementById('available-bori');
            var boriQuantitySpan = document.getElementById('bori-quantity');
            var outofstockSpan = document.getElementById('outofstock');

            if (bori > 0) {
                boriQuantitySpan.textContent = bori;
                boriSpan.style.display = 'inline'; // Show the span
                document.querySelector('.bori-check').removeAttribute('readonly');
                outofstockSpan.textContent = '';
            } else {
                outofstockSpan.textContent = 'Out of stock!';
                document.querySelector('.bori-check').setAttribute('readonly', true);
                boriSpan.style.display = 'none'; // Hide the span if no bori available
            }

            // Update the hidden select input with the selected truck ID and Bori value
            var hiddenSelect = document.getElementById('truck');
            hiddenSelect.value = truckId; // Update the truck ID
            hiddenSelect.setAttribute('data-bori', bori); // Store bori in data attribute

            // Show the selected truck number and Bori in the dropdown toggle
            // $('#truck-toggle').text(truckNumber);
            document.getElementById('truck-toggle').textContent =
                `Truck No: ${row.cells[0].textContent} | (Marka: ${marka}) | (Main Cate: ${mainCate}) |
                    (Parent Cate: ${parentCate}) | (Child Cate: ${childCate}) | (Bori: ${bori})`;
        });
    });

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

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

            // For "Item Details" table, add new row on Tab from the last input
            if (activeElement === lastAmountInput) {
                event.preventDefault(); // Prevent default tab behavior

                // Call the addRow function to add a new row
                addRow();

                // Set focus on the newly added row's first input field (e.g., marka)
                setTimeout(function() {
                    const newMarkaInput = document.querySelectorAll('.marka-select');
                    newMarkaInput[newMarkaInput.length - 1].focus();
                }, 0);
            }

            // For "Bori Details" table, add new row on Tab from the last input
            const allBoriWeightInputs = document.querySelectorAll('input[name="per_bori_weight[]"]');
            const lastBoriWeightInput = allBoriWeightInputs[allBoriWeightInputs.length - 1];

            if (activeElement === lastBoriWeightInput) {
                event.preventDefault(); // Prevent default tab behavior

                // Call the addBoriRow function to add a new row
                addBoriRow();

                // Set focus on the newly added row's first input field (e.g., bori number)
                setTimeout(function() {
                    const newBoriNumberInput = document.querySelectorAll('input[name="bori_number[]"]');
                    newBoriNumberInput[newBoriNumberInput.length - 1].focus();
                }, 0);
            }
        }


        if (event.altKey && event.key === 'd') {
            event.preventDefault();

            const focusedElement = document.activeElement;
            const focusedRow = focusedElement.closest('tr');


            if (focusedRow) {
                focusedRow.remove();
                updateBoriDetails();

            } else {
                showErrorNotification(
                    'Please select the row you want to delete.\nبراہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
                );
            }
        }
    });

    function showErrorNotification(message) {
        const notification = document.getElementById('errorNotification');
        const errorMessage = document.getElementById('errorMessage');

        errorMessage.innerText = message;
        notification.style.display = 'block';

        setTimeout(() => {
            notification.style.display = 'none';
        }, 5000); // Hide after 5 seconds
    }
</script>



@endpush
