@extends('layouts.master')

<style>
    .d-none {
        display: none;
    }

    .table-wrapper {
        max-height: 300px;
        overflow-y: auto;
        overflow-x: auto;
        display: block;
    }

    .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>Edit Sale</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Edit 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">Edit Sale</h5>
                <form action="{{ route('sales.update', Crypt::encrypt($sale->id_sales)) }}" method="POST" id="salesForm">
                    @method('put')
                    @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">
                                    <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>
                                <div id="truck_labels" class="mt-2"></div>

                                <!-- 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>Select</th>
                                                    <th>Truck No</th>
                                                    <th>Main Category</th>
                                                    <th>Parent Category</th>
                                                    <th>Child Category</th>
                                                    <th>Marka</th>
                                                    <th>Bori</th>
                                                    <th>Weight</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 select-truck "
                                                                data-truck-id="{{ $truck->id_truck }}"
                                                                data-details-id="{{ $detail->id_grd }}"
                                                                data-bori="{{ $detail->bori }}"
                                                                data-marka="{{ $detail->marka }}"
                                                                data-weight="{{ $detail->weight }}"
                                                                data-main-cate="{{ $detail->productMainCate->products_category_name ?? '' }}"
                                                                data-parent-cate="{{ $detail->productParentCate->name ?? '' }}"
                                                                data-child-cate="{{ $detail->productChildCate->name ?? '' }}">
                                                                <td>
                                                                    <button type="button"
                                                                        class="btn btn-sm btn-select btn-outline-success  ">
                                                                        <i class="fa fa-check"></i>
                                                                    </button>
                                                                    <button type="button"
                                                                        class="btn btn-sm btn-deselect btn-outline-danger  d-none">
                                                                        <i class="fa fa-times"></i>
                                                                    </button>
                                                                </td>
                                                                <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>

                                                            </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 @if ($customer->id_customers == $sale->customer_id) selected @endif
                                            value="{{ $customer->id_customers }}">
                                            {{ $customer->customer_name }} - {{ $customer->customer_name_urdu }}
                                        </option>
                                    @endforeach
                                </select><button type="button" style="color:#fff;" class="btn btn-sm btn-info mt-2"
                                    data-toggle="modal" data-target="#addCustomerModal">
                                    + Add Customer
                                </button>
                            </div>
                            @error('customer_id')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </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 class="col-md-4">
                            <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>

                    <div class="row mb-5">

                    </div>
                    <hr>
                    <div class="row my-5">
                        <div class="col-md-12">
                            <!-- 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>Select Truck</th>
                                                <th>Main Category</th>
                                                <th>Parent Category</th>
                                                <th>Child Category</th>
                                                <th
                                                    style="font-size: 2vh; color: black; text-align: right;  font-family: 'Jameel Noori Nastaleeq', serif;">
                                                    Marka
                                                </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>
                                        </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-6">
                            <h4>Additional Bori Details{{-- / اضافی بوری کی تفصیلات --}}</h4>
                            <div class="table-wrapper">
                                <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 n-amount"
                                                        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>

                                </div>

                            </div>
                            <button type="button" id="addPlusbori" class="btn btn-az-primary btn-block mt-2"
                                onclick="addBoriRow()">
                                <span class="mdi mdi-arrow-expand-up"></span> Add More
                            </button>
                        </div>
                    </div>
                    <hr>
                    <!-- 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="text" class="form-control n-amount" id="total_bori"
                                        name="total_bori" value="{{ old('total_bori') }}" 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="text" class="form-control n-amount" id="cash_received"
                                        name="cash_received" value="{{ $sale->paid ?? old('cash_received') }}">
                                </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="text" class="form-control n-amount" id="remaining_amount"
                                        name="remaining_amount" readonly>
                                </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="text" class="form-control n-amount " id="total_amount"
                                        name="total_amount" readonly>
                                </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" id="submitData">Update</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>
    <div class="modal fade" id="addCustomerModal" tabindex="-1" role="dialog" aria-labelledby="addCustomerModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form id="addCustomerForm" method="POST">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Customer</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Customer Name (English)</label>
                            <input type="text" name="customer_name" id="customer_name" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Customer Name (Urdu)</label>
                            <input type="text" name="customer_name_urdu" id="customer_name_urdu"
                                class="form-control urdu-font" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success" style="color:#fff;">Save</button>
                        <button type="button" id="mdcancelBtn" class="btn btn-secondary" style="color:#fff;"
                            data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection


@push('scripts')
    {{-- Instant Add Customer Modal Script  --}}
    <script>
        var trucks = @json($trucks);
        let selectedTrucks = [];
        let selectedMarka = [];
    </script>
    <script>
        $(document).ready(function() {

            document.querySelectorAll('.n-amount').forEach(function(el) {
                new AutoNumeric(el, {
                    digitGroupSeparator: ',',
                    decimalPlaces: 0,
                    decimalCharacter: '.',
                    minimumValue: '0',
                    unformatOnSubmit: true
                });
            });

            // Attach submit event
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $(document).on('submit', '#addCustomerForm', function(e) {
                e.preventDefault(); // stops page reload ✅

                let form = $(this);

                $.ajax({
                    url: "{{ route('customers.store') }}",
                    method: "POST",
                    data: form.serialize(),
                    beforeSend: function() {
                        // optional: disable button or show loader
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#mdcancelBtn').click();

                            response.customers.forEach(function(customer) {
                                const option = `<option value="${customer.id_customers}">
                                    ${customer.customer_name} | ${customer.customer_name_urdu}
                                </option>`;
                                $('#customers').append(option);
                            });
                            $('#customer_name').val('')
                            $('#customer_name_urdu').val('')
                            toastr.success('Customer added successfully!');
                        }


                    },
                    error: function(response) {
                        if (!response.success) {
                            let errors = response.responseJSON.errors;

                            if (errors) {
                                // Print each field error
                                Object.keys(errors).forEach(function(key) {
                                    errors[key].forEach(function(msg) {
                                        toastr.error(msg);
                                    });
                                });
                            } else {
                                // Fallback message
                                toastr.error(response.responseJSON.message);
                            }
                        }
                    }
                });
            });
        });
    </script>
    <script type="text/javascript">
        // For Bori
        function checkBoriQty(inputElement) {

            const $input = $(inputElement); // the Bori input
            const maxBori = parseFloat($input.data("max-bori")) || 0; // available Bori for this row

            // Get the numeric value using AutoNumeric
            const value = AutoNumeric.getNumber($input[0]) || 0;

            // Find the error span inside the same row
            const $errorSpan = $input.siblings(".bori-error");

            if (value > maxBori) {
                // Input exceeds available Bori
                $input.addClass("border border-danger");
                $errorSpan.show().text("Exceeded available Bori! Max: " + maxBori);

                // Disable submit button (optional)
                $("#submitData").prop("disabled", true);
            } else {
                // Input is valid

                $input.removeClass("border border-danger");
                $errorSpan.hide().text("");

                // Enable submit if no other errors
                const anyError = $(".bori-error:visible").length > 0;
                $("#submitData").prop("disabled", anyError);
            }
            calculateAmount(inputElement);
        }


        document.addEventListener('keydown', function(event) {
            if ((event.ctrlKey || event.metaKey) && event.key === 's') {
                event.preventDefault();

                document.getElementById('salesForm').submit();
            }

            if (event.key === 'Enter') {
                event.preventDefault();
            }
        });



        function calculateAmount(element) {
            let row = element.closest('tr'); // Get the current row
            let weight = parseFloat(AutoNumeric.getNumber(row.querySelector('.weight-input'))) || 0;
            let bori = parseFloat(AutoNumeric.getNumber(row.querySelector('.bori-check'))) || 0;
            let rate = parseFloat(AutoNumeric.getNumber(row.querySelector('.rate-input'))) || 0;
            // Calculate the amount (رقم)
            let amount;
            if (weight == null || weight == 0) {
                amount = (rate * bori);
            } else {
                amount = (rate * weight) / 40;
            }

            if (AutoNumeric.getAutoNumericElement(row.querySelector('.amount-input'))) {
                AutoNumeric.getAutoNumericElement(row.querySelector('.amount-input')).set(amount);
            } else {
                row.querySelector('.amount-input').value = amount.toFixed(2);
            }
            updateTotals();
        }

        function getTruckOptions(selectedId = '') {
            selectedId = selectedId ? String(selectedId) : '';
            if (!selectedTrucks || selectedTrucks.length === 0) {
                return `<option value="">Select Truck</option>`;
            }
            // ensure we compare strings
            const selectedSet = selectedTrucks.map(String);
            let options = `<option value="">Select Truck</option>`;
            trucks.forEach(truck => {
                const id = String(truck.id_truck);
                if (selectedSet.includes(id)) {
                    const selected = id === selectedId ? 'selected' : '';
                    options += `<option value="${id}" ${selected}>${truck.truck_no}</option>`;
                }
            });
            return options;
        }

        function updateSubmitButton() {

            const rowCount = $("#item-table tbody tr").length;
            if (rowCount === 1) {
                $("#addPlusbori").prop("disabled", false);
                $('#dismyDiv').removeClass('disabled-div');
            } else {
                $("#addPlusbori").prop("disabled", true);
                $('#dismyDiv').addClass('disabled-div');
            }
        }

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



            var row = `<tr data-truck-id="${truckId}" data-details-id="${detailsId}">
            <td>
        <select class="form-control select-truck-good" name="good_receipts_truck_ids[]">
            ${getTruckOptions(truckId)}
        </select>
    </td>

    <td>
        <select class="form-control main-cate" name="main_category[]"></select>
    </td>


    <td>
        <select class="form-control parent-cate" name="parent_category[]"></select>
    </td>


    <td>
        <select class="form-control child-cate" name="child_category[]"></select>
    </td>
    <td>
          <select class="form-control marka marka-select" name="marka[]"></select>
    </td>

            <td>
                <input type="hidden" id="setBori_${detailsId}">
                <input type="text" class="form-control bori-check n-amount" value="1" name="bori[]" data-max-bori="" onkeyup="checkBoriQty(this)">
                <small class="text-muted">Available Bori: </small>
                <span class="bori-error text-danger" style="display:none;">Exceeded available Bori!</span>
            </td>

            <td>
                <input type="hidden" id="setWeight_${detailsId}">
                <input type="text" class="form-control n-amount weight-input" name="weight[]" oninput="calculateAmount(this)">
                <span class="available-weight" style="display:none;">
                    Available Weight in stock: <span class="weight-quantity"></span>
                </span>
                <span class="outofstockWeight text-danger"></span>
            </td>
              <input type="hidden"class="good_receipt_detail_id" name='good_receipt_detail_id[]' value="${detailsId}">
            <td><input type="text" class="form-control n-amount rate-input" name="rate[]" oninput="calculateAmount(this)"></td>
            <td><input type="text" class="form-control n-amount amount-input" name="amount[]" readonly></td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-danger remove-row">
                    <i class="fa fa-trash"></i>
                </button>
            </td>
        </tr>`;
            $('#item-table tbody').append(row);
            updateSubmitButton();
            $("#item-table tbody tr:last .n-amount").each(function() {
                new AutoNumeric(this, {
                    digitGroupSeparator: ',',
                    decimalPlaces: 0,
                    decimalCharacter: '.',
                    minimumValue: '0',
                    unformatOnSubmit: true
                });
            });

            // Bori validation
            $(document).on("input", ".bori-check", function() {
                const $input = $(this);
                const maxBori = parseFloat($input.data("max-bori")) || 0;
                const value = AutoNumeric.getNumber($input[0]) || 0;
                if (value > maxBori) {
                    $input.addClass("border border-danger");
                    $input.siblings(".bori-error").show();
                    $("#submitData").prop("disabled", true);
                } else {
                    $input.removeClass("border border-danger");
                    $input.siblings(".bori-error").hide();
                    $("#submitData").prop("disabled", false);
                }
                updateBoriDetails();
                updateTotals();
            });

            updateSubmitButton();
        }

        function getUsedBori(currentRow) {
            let total = 0;

            let truckId = currentRow.find("input[name='good_receipts_truck_ids[]']").val();
            let mainId = currentRow.find('.main-cate').val();
            let parentId = currentRow.find('.parent-cate').val();
            let childId = currentRow.find('.child-cate').val();
            let markaId = currentRow.find('.marka-select').val(); // adjust class

            $('#item-table tbody tr').each(function() {
                let row = $(this);

                if (row.is(currentRow)) return; // skip current row

                if (
                    row.find("input[name='good_receipts_truck_ids[]']").val() == truckId &&
                    row.find('.main-cate').val() == mainId &&
                    row.find('.parent-cate').val() == parentId &&
                    row.find('.child-cate').val() == childId &&
                    row.find('.marka-select').val() == markaId
                ) {
                    let input = row.find('.bori-check')[0];
                    let an = AutoNumeric.getAutoNumericElement(input);

                    if (an) {
                        total += Number(an.getNumber());
                    }
                }
            });

            return total;
        }
        $(document).on('keyup change', '.bori-check', function() {
            validateBori(this);
            updateTotals();
        });

        function getUsedBoriForSameDetails(row) {
            let total = 0;

            let truckId = row.find("input[name='good_receipts_truck_ids[]']").val();
            let mainId = row.find('.main-cate').val();
            let parentId = row.find('.parent-cate').val();
            let childId = row.find('.child-cate').val();
            let markaId = row.find('.marka').val(); // adjust class if needed

            $('#item-table tbody tr').each(function() {
                let r = $(this);

                if (r.is(row)) return; // skip current row

                if (
                    r.find("input[name='good_receipts_truck_ids[]']").val() == truckId &&
                    r.find('.main-cate').val() == mainId &&
                    r.find('.parent-cate').val() == parentId &&
                    r.find('.child-cate').val() == childId &&
                    r.find('.marka').val() == markaId
                ) {
                    let input = r.find('.bori-check')[0];
                    let an = AutoNumeric.getAutoNumericElement(input);

                    if (an) {
                        total += Number(an.getNumber());
                    }
                }
            });

            return total;
        }

        function validateBori(input) {
            let row = $(input).closest('tr');
            let an = AutoNumeric.getAutoNumericElement(input);

            if (!an) return;

            let enteredBori = Number(an.getNumber());
            let maxBori = Number($(input).data('max-bori'));

            let usedBori = getUsedBori(row);
            let remainingBori = maxBori - usedBori;

            if (enteredBori > remainingBori) {
                alert(`Remaining Bori is ${remainingBori}`);

                an.set(remainingBori > 0 ? remainingBori : 0);
                return false;
            }
            updateTotals();
            return true;
        }

        function getSelectedTruckMarka(truckId = null) {
            let markaList = [];


            $('.truck-details.select-truck, .truck-details.is-selected').each(function() {
                let row = $(this);


                if (truckId && row.data('truck-id') != truckId) return;

                let marka = row.data('marka');
                if (marka) {
                    markaList.push(String(marka));
                }
            });


            return [...new Set(markaList)];
        }
        $(document).on('change', '.child-cate', function() {
            let row = $(this).closest('tr');
            let childId = row.find('.child-cate').val();
            let mainId = row.find('.main-cate').val();
            let parentId = row.find('.parent-cate').val();
            let truckId = row.find('.select-truck-good').val();

            if (!childId) return;

            let url = '{{ route('get.goods-receipt.truck', ':truckId') }}';
            url = url.replace(':truckId', truckId);

            $.ajax({
                url: url,
                type: 'GET',
                data: {
                    truck_id: truckId,
                    main_id: mainId,
                    parent_id: parentId,
                    child_id: childId,
                    type_for: 'getMarka'
                },
                success: function(res) {
                    if (!res.data || res.data.length === 0) return;
                    let data = res.data[0];


                    /* ---------------- MARKA LOGIC (NEW) ---------------- */

                    let markaSelect = row.find('.marka');
                    markaSelect.empty().append('<option value="">Select Marka</option>');

                    if (Array.isArray(data.marka_list)) {

                        let selectedTruckMarka = getSelectedTruckMarka(
                            truckId);


                        let filteredMarka = data.marka_list.filter(marka => selectedTruckMarka.includes(
                            String(marka)));

                        filteredMarka.forEach(function(marka) {
                            markaSelect.append(
                                `<option value="${marka}">${marka}</option>`
                            );
                        });

                        let detailMarka = row.data('original-detail')?.marka || filteredMarka[0] || '';
                        if (detailMarka) {
                            if (markaSelect.find(`option[value="${detailMarka}"]`).length === 0) {
                                // append if missing
                                markaSelect.append(
                                    `<option value="${detailMarka}">${detailMarka}</option>`);
                            }
                            markaSelect.val(detailMarka).trigger('change'); // ✅ now it will select
                        }
                    }
                    row.find('.good_receipt_detail_id').val(data.good_receipt_detail_id);
                },
                error: function(err) {
                    console.error('AJAX error:', err);
                }
            });
        });

        $(document).on('change', '.marka', function() {
            let row = $(this).closest('tr');
            let marka = $(this).val();
            let truckId = row.find('.select-truck-good').val();
            let childId = row.find('.child-cate').val();
            let mainId = row.find('.main-cate').val();
            let parentId = row.find('.parent-cate').val();

            let originalDetail = row.data('original-detail');
            let isEditMode = row.attr('data-is-edit') === 'true';

            if (!childId) return;

            let url = '{{ route('get.goods-receipt.truck', ':truckId') }}';
            url = url.replace(':truckId', truckId);

            $.ajax({
                url: url,
                type: 'GET',
                data: {
                    truck_id: truckId,
                    main_id: mainId,
                    parent_id: parentId,
                    child_id: childId,
                    marka: marka
                },
                success: function(res) {
                    if (!res.data || res.data.length === 0) return;
                    let data = res.data[0];

                    let boriInput = row.find('.bori-check')[0];
                    let weightInput = row.find('.weight-input')[0];
                    let rateInput = row.find('.rate-input')[0];
                    let amountInput = row.find('.amount-input')[0];

                    let an = AutoNumeric.getAutoNumericElement(boriInput);
                    if (!an) return;

                    let totalBori = Number(data.bori);
                    let usedBori = 0;

                    $('#item-table tbody tr').each(function() {
                        let r = $(this);
                        if (r.is(row)) return;

                        if (
                            r.find("input[name='good_receipts_truck_ids[]']").val() ==
                            truckId &&
                            r.find('.main-cate').val() == row.find('.main-cate').val() &&
                            r.find('.parent-cate').val() == row.find('.parent-cate').val() &&
                            r.find('.child-cate').val() == childId &&
                            r.find('.marka').val() == row.find('.marka-select').val()
                        ) {
                            let otherInput = r.find('.bori-check')[0];
                            let otherAn = AutoNumeric.getAutoNumericElement(otherInput);
                            if (otherAn) {
                                usedBori += Number(otherAn.getNumber());
                            }
                        }
                    });

                    let remainingBori = totalBori - usedBori;
                    if (remainingBori < 0) remainingBori = 0;

                    // ✅ FIX: Don't set maximumValue - just store as data attribute
                    $(boriInput).attr('data-max-bori', remainingBori).data('max-bori', remainingBori);
                    row.find('.text-muted').text('Available Bori: ' + remainingBori);
                    row.find('.marka').val(data.marka);
                    row.find('.good_receipt_detail_id').val(data.good_receipt_detail_id);


                    if (isEditMode && originalDetail) {
                        setTimeout(function() {
                            if (boriInput && AutoNumeric.getAutoNumericElement(boriInput) &&
                                originalDetail.bori != null) {
                                AutoNumeric.getAutoNumericElement(boriInput).set(originalDetail
                                    .bori);
                            }

                            if (weightInput && AutoNumeric.getAutoNumericElement(weightInput) &&
                                originalDetail.weight != null && originalDetail.weight !== '') {
                                AutoNumeric.getAutoNumericElement(weightInput).set(
                                    originalDetail.weight);
                            }

                            if (rateInput && AutoNumeric.getAutoNumericElement(rateInput) &&
                                originalDetail.rate != null && originalDetail.rate !== '') {
                                AutoNumeric.getAutoNumericElement(rateInput).set(originalDetail
                                    .rate);
                            }

                            if (amountInput && AutoNumeric.getAutoNumericElement(amountInput) &&
                                originalDetail.amount != null && originalDetail.amount !== '') {
                                AutoNumeric.getAutoNumericElement(amountInput).set(
                                    originalDetail.amount);
                            }

                            // ✅ Clear the flag after setting values
                            row.removeAttr('data-is-edit');
                            row.removeData('original-detail');

                            updateTotals();

                        }, 50);
                    }
                    updateTotals();
                },
                error: function(err) {
                    console.error('AJAX error:', err);
                }
            });
        });

        $(document).on('change', '.select-truck-good', function() {
            let truckId = $(this).val();
            let row = $(this).closest('tr');
            let url = '{{ route('get.goods-receipt.truck', ':truckId') }}';
            url = url.replace(':truckId', truckId);

            if (!truckId) return;

            $.ajax({
                url: url,
                type: 'GET',
                success: function(res) {
                    let mainSelect = row.find('.main-cate');
                    let parentSelect = row.find('.parent-cate');
                    let childSelect = row.find('.child-cate');

                    // Add placeholders if not already added
                    if (mainSelect.find('option[value=""]').length === 0) {
                        mainSelect.prepend(`<option value="">Select Main</option>`);
                    }

                    if (parentSelect.find('option[value=""]').length === 0) {
                        parentSelect.prepend(`<option value="">Select Parent</option>`);
                    }

                    if (childSelect.find('option[value=""]').length === 0) {
                        childSelect.prepend(`<option value="">Select Child</option>`);
                    }

                    // LOOP over response array
                    res.data.forEach(function(item) {

                        // MAIN CATEGORY
                        if (mainSelect.find(`option[value="${item.main.id}"]`).length === 0) {
                            mainSelect.append(
                                `<option value="${item.main.id}">${item.main.name}</option>`
                            );
                        }

                        // PARENT CATEGORY
                        if (parentSelect.find(`option[value="${item.parent.id}"]`).length ===
                            0) {
                            parentSelect.append(
                                `<option value="${item.parent.id}">${item.parent.name}</option>`
                            );
                        }

                        // CHILD CATEGORY
                        if (childSelect.find(`option[value="${item.child.id}"]`).length === 0) {
                            childSelect.append(
                                `<option value="${item.child.id}">${item.child.name}</option>`
                            );
                        }

                    });
                }
            });
        });

        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 n-amount" oninput="calculatAmount(this)" 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);
            let newInput = $('#bori-table tbody tr:last').find('input[name="per_bori_weight[]"]')[0];
            new AutoNumeric(newInput, {
                digitGroupSeparator: ',',
                decimalPlaces: 0,
                decimalCharacter: '.',
                minimumValue: '0',
                unformatOnSubmit: true
            });

            // Focus the input after a short delay
            setTimeout(() => {
                if (newInput) newInput.focus();
            }, 50); // 50ms delay ensures AutoNumeric is fully ready


            let boriInput = $('.bori-check')[0];

            // Get AutoNumeric instance
            let boriAutoNumeric = AutoNumeric.getAutoNumericElement(boriInput);

            if (boriAutoNumeric) {
                // Get current value using AutoNumeric
                let bori = boriAutoNumeric.getNumber() || 0;

                // Increment
                bori++;

                // Set new value using AutoNumeric
                boriAutoNumeric.set(bori);
            }
            updateBoriDetails();
            updateTotals();
        }

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

            let boriInput = $('.bori-check')[0];

            // Get AutoNumeric instance
            let boriAutoNumeric = AutoNumeric.getAutoNumericElement(boriInput);

            if (boriAutoNumeric) {
                let bori = boriAutoNumeric.getNumber() || 0;
                bori--;
                boriAutoNumeric.set(bori);
            }
            updateBoriDetails();
            updateTotals();
        }

        function updateBoriDetails() {
            let totalBori = 0;
            let totalWeight = 0;

            // Loop through all Bori rows (bori-table - separate table)
            $('#bori-table tbody tr').each(function(index) {
                // Serial number
                $(this).find('td:first input').val(index + 1);

                // Weight per bori row
                let weightEl = $(this).find('input[name="per_bori_weight[]"]')[0];
                let weight = weightEl ? AutoNumeric.getNumber(weightEl) || 0 : 0;
                totalWeight += weight;

                // Bori per row
                let boriEl = $(this).find('input[name="bori[]"]')[0];
                let bori = boriEl ? AutoNumeric.getNumber(boriEl) || 0 : 0;
                totalBori += bori;
            });

            let rowCount = $('#item-table tbody tr').length;

            if (rowCount == 1) {
                $('#item-table tbody tr').each(function() {
                    let weightEl = $(this).find('input[name="weight[]"]')[0];
                    if (weightEl) AutoNumeric.set(weightEl, totalWeight);

                    let weightInput = $(this).find('.weight-input')[0];
                    if (weightInput) calculateAmount(weightInput);
                });
            }

            // ✅ Update only total inputs (readonly fields)
            let totalBoriInput = $('#total_bori')[0];
            if (totalBoriInput) AutoNumeric.set(totalBoriInput, totalBori);

            // If you have total weight field, update it
            let totalWeightInput = $('#total_weight')[0];
            if (totalWeightInput) AutoNumeric.set(totalWeightInput, 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();


        });

        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('.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
            $('#item-table tbody tr').each(function() {
                const boriInput = this.querySelector('input[name="bori[]"]'); // note [] for dynamic rows
                const amountInput = this.querySelector('input[name="amount[]"]');

                let bori = boriInput ? (AutoNumeric.getNumber(boriInput) || 0) : 0;
                let amount = amountInput ? (AutoNumeric.getNumber(amountInput) || 0) : 0;

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

            // Update total Bori
            const totalBoriEl = document.querySelector('#total_bori');
            if (totalBoriEl && AutoNumeric.getAutoNumericElement(totalBoriEl)) {
                AutoNumeric.getAutoNumericElement(totalBoriEl).set(totalBori);
            }

            // Update total amount
            const totalAmountEl = document.querySelector('#total_amount');
            if (totalAmountEl && AutoNumeric.getAutoNumericElement(totalAmountEl)) {
                AutoNumeric.getAutoNumericElement(totalAmountEl).set(totalAmount);
            }

            // Get cash received
            const cashReceivedEl = document.querySelector('#cash_received');
            const cashReceived = cashReceivedEl ? (AutoNumeric.getNumber(cashReceivedEl) || 0) : 0;

            // Calculate remaining
            const remainingAmount = totalAmount - cashReceived;

            // Update remaining amount
            const remainingEl = document.querySelector('#remaining_amount');
            if (remainingEl && AutoNumeric.getAutoNumericElement(remainingEl)) {
                AutoNumeric.getAutoNumericElement(remainingEl).set(remainingAmount);
            }
        }



        function handleInputChange() {


            $('#item-table').on('input', 'input[name="bori"], input[name="amount"]', updateTotals);

            $('#cash_received').on('input', function() {

                let cash = AutoNumeric.getAutoNumericElement('#cash_received');
                let total = AutoNumeric.getAutoNumericElement('#total_amount');
                let cashReceived = cash ? parseFloat(cash.getNumber()) : parseFloat($('#cash_received').val()
                    .replace(/,/g, '')) || 0;
                let totalAmount = total ? parseFloat(total.getNumber()) : parseFloat($('#total_amount').val()
                    .replace(/,/g, '')) || 0;
                let remainingAmount = totalAmount - cashReceived;
                let reman = AutoNumeric.getAutoNumericElement('#remaining_amount');

                if (reman) {
                    reman.set(remainingAmount); // formatted automatically
                } else {
                    $('#remaining_amount').val(remainingAmount);
                }
            });
        }


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

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

                $('.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 submitBtn = document.getElementById('submitData');

                var bori = row.cells[5].textContent;
                var weight = row.cells[6].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;

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


        document.addEventListener('keydown', function(event) {
            // Only handle Enter or Tab
            if (event.key !== "Enter" && event.key !== "Tab") return;

            const target = event.target;

            // ====== Item Details ======
            if (target.classList.contains('amount-input')) {
                const lastInput = document.querySelector('#item-table tbody tr:last .amount-input');
                if (target === lastInput) {
                    event.preventDefault();
                    addRow();

                    // Focus second input (weight) of new row
                    setTimeout(() => {
                        const newRow = document.querySelector('#item-table tbody tr:last');
                        if (newRow) {
                            const weightInput = newRow.querySelector('.weight-input');
                            if (weightInput) weightInput.focus();
                        }
                    }, 50);
                }
            }

            // ====== Bori Details ======
            if (target.name === 'per_bori_weight[]') {
                const allBoriInputs = document.querySelectorAll('input[name="per_bori_weight[]"]');
                const lastInput = allBoriInputs[allBoriInputs.length - 1];
                if (target === lastInput) {
                    event.preventDefault();
                    addBoriRow();

                    // Focus per_bori_weight input of new row
                    setTimeout(() => {
                        const newRow = document.querySelector('#bori-table tbody tr:last');
                        if (newRow) {
                            const weightInput = newRow.querySelector('input[name="per_bori_weight[]"]');
                            if (weightInput) weightInput.focus();
                        }
                    }, 50);
                }
            }

            // ====== Delete row with Alt+D ======
            if (event.altKey && event.key === 'd') {
                event.preventDefault();
                const focusedRow = target.closest('tr');
                if (focusedRow) {
                    focusedRow.remove();
                    updateBoriDetails();
                } else {
                    showErrorNotification('Please select the row you want to delete.');
                }
            }
        });

        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
        }

        // Custom Keys Work
        document.addEventListener('DOMContentLoaded', function() {
            // Prevent form submission on Enter key
            document.getElementById('salesForm').addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                }
            });

            // Submit form when Ctrl + S is pressed
            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 's') {
                    e.preventDefault(); // Prevent the default save dialog in the browser
                    document.getElementById('salesForm').submit(); // Submit the form
                }
            });
        });
    </script>

    <script>
        $(window).on('load', function() {
            setTimeout(function() {
                // Show the dropdown
                $('.dropdown-content').css('display', 'block');

                // Grab the input
                var $input = $('#truck-search');

                // Make sure it's visible before focusing
                $input.css('display', 'block');

                // Focus after the browser has rendered
                setTimeout(function() {
                    $input.trigger('focus'); // jQuery focus
                    // Native fallback
                    if ($input.length) {
                        $input[0].focus({
                            preventScroll: true
                        });
                    }
                }, 50);
            }, 600);
        });
        $(function() {
            document.addEventListener('keydown', function(event) {
                const activeElement = document.activeElement;

                // Check for Tab key press
                if (event.key === "Tab") {

                    const allRemarksInputs = document.querySelectorAll('textarea[name="remarks[]"]');
                    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
                        document.getElementById('add-item').click();

                        // Focus on the newly added row's first input field (e.g., items select)
                        setTimeout(function() {
                            const newItemsInput = document.querySelectorAll(
                                'select[name="productCat[]"]');
                            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
                    } else {
                        showErrorNotification(
                            'Please select the row you want to delete.\nبراہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
                        );
                    }
                }
            });

            // Initialize all Select2 fields; add class="select2" to your <select> elements
            $('select.select2').select2({
                placeholder: '- Select -',
                allowClear: true,
                width: '100%' // optional
            });

            // Ensure search field focuses when any Select2 opens
            $(document).on('select2:open', function() {
                setTimeout(() => {
                    const search = document.querySelector('.select2-search__field');
                    if (search) search.focus();
                }, 0);
            });

            // Visibility and tabbables
            function isActuallyVisible(el) {
                if (!el || el.disabled) return false;
                const style = window.getComputedStyle(el);
                if (style.visibility === 'hidden' || style.display === 'none') return false;
                // Hidden select backing Select2 is allowed
                if (el.offsetParent === null && !el.classList.contains('select2-hidden-accessible')) return false;
                return true;
            }

            function getFocusables() {
                return Array.from(document.querySelectorAll(
                    'input, textarea, select, button, [tabindex]:not([tabindex="-1"])'
                )).filter(el => {
                    if (el.disabled) return false;
                    const isSelect2Hidden = el.classList.contains('select2-hidden-accessible');
                    return isActuallyVisible(el) || isSelect2Hidden;
                });
            }

            function focusNextField(current) {
                const focusables = getFocusables();
                const idx = focusables.indexOf(current);
                if (idx === -1) return;
                for (let i = idx + 1; i < focusables.length; i++) {
                    const next = focusables[i];
                    if (!next) break;

                    // If next is a Select2-backed select, open it
                    if (next.tagName === 'SELECT' && next.classList.contains('select2-hidden-accessible')) {
                        $(next).select2('open');
                        return;
                    }

                    if (isActuallyVisible(next)) {
                        next.focus();
                        return;
                    }
                }
            }

            function focusPrevField(current) {
                const focusables = getFocusables();
                const idx = focusables.indexOf(current);
                if (idx === -1) return;
                for (let i = idx - 1; i >= 0; i--) {
                    const prev = focusables[i];
                    if (!prev) break;

                    if (prev.tagName === 'SELECT' && prev.classList.contains('select2-hidden-accessible')) {
                        $(prev).select2('open');
                        return;
                    }

                    if (isActuallyVisible(prev)) {
                        prev.focus();
                        return;
                    }
                }
            }

            // Global Tab/Shift+Tab across native fields
            $(document).on('keydown', 'input, textarea, select, button, [tabindex]:not([tabindex="-1"])', function(
                e) {
                if (e.key === 'Tab') {
                    e.preventDefault();
                    if (e.shiftKey) {
                        focusPrevField(this);
                    } else {
                        focusNextField(this);
                    }
                }
            });


            $(document).on('keydown', '.select2-search__field', function(e) {
                if (e.key === 'Tab') {
                    e.preventDefault();

                    const enterEvent = new KeyboardEvent('keydown', {
                        key: 'Enter',
                        code: 'Enter',
                        keyCode: 13,
                        which: 13,
                        bubbles: true
                    });
                    this.dispatchEvent(enterEvent);


                    const $select = $('.select2-container--open').prev('select');
                    if ($select.length) {
                        $select.select2('close');
                        const rawSelect = $select[0];
                        setTimeout(() => {
                            if (e.shiftKey) {
                                focusPrevField(rawSelect);
                            } else {
                                focusNextField(rawSelect);
                            }
                        }, 10);
                    }
                }
            });
        });
    </script>

    <script>
        $(document).ready(function() {

            // Function to initialize AutoNumeric on an input
            function initAutoNumeric(input) {
                new AutoNumeric(input, {
                    digitGroupSeparator: ',',
                    decimalCharacter: '.',
                    minimumValue: '0',
                    unformatOnSubmit: true
                });
            }




            const $dropdown = $(".dropdown-content");
            const $toggle = $("#truck-toggle");

            // Toggle open/close
            $toggle.on("click", function(e) {
                e.stopPropagation(); // prevent bubbling
                if ($dropdown.is(":visible")) {
                    $dropdown.hide();
                } else {
                    $(".dropdown-content").hide(); // close any other open dropdowns
                    $dropdown.show();
                }
            });

            // Close when clicking outside
            $(document).on("click", function(e) {
                if (!$(e.target).closest(".custom-dropdown").length) {
                    $dropdown.hide();
                }
            });

            // Optional: close with ESC key
            $(document).on("keydown", function(e) {
                if (e.key === "Escape") {
                    $dropdown.hide();
                }
            });
        });
        $(document).ready(function() {
            // Toggle dropdown
            $("#truck-toggle").on("click", function() {
                $(".dropdown-content").toggle();
            });

            // Select truck
            $(document).on("click", ".select-truck", function() {
                let row = $(this).closest("tr");
                let truckId = row.data("truck-id");
                let marka = row.data("marka");


                let grdId = row.data("details-id");
                let bori = row.data("bori");
                if (!truckId) return;
                if (!selectedTrucks.includes(truckId)) {
                    selectedTrucks.push(truckId);
                }
                if (!selectedMarka.includes(marka)) {
                    selectedMarka.push(marka);
                }
                refreshTruckSelects();
                let label = $("#truck option[value='" + truckId + "'][data-bori='" + bori + "']").text();

                $("#truck_labels").append(`
    <span class="badge bg-success me-1" data-id="${truckId}-${bori}-${grdId}">
        ${label}
    </span>
`);

                // Add to hidden select
                $("#truck option[value='" + truckId + "']").prop("selected", true);

                // Toggle icons
                row.find(".select-truck").addClass("d-none");
                row.find(".deselect-truck").removeClass("d-none");
                $('div#truck-toggle').html('-');
            });

            // Deselect truck
            $(document).on("click", ".deselect-truck", function() {
                let row = $(this).closest("tr");
                let truckId = row.data("truck-id");
                let grdId = row.data("details-id");
                let marka = row.data("marka");
                let bori = row.data("bori");
                // Remove from hidden select
                $("#truck option[value='" + truckId + "']").prop("selected", false);
                $("#truck_labels span[data-id='" + truckId + "-" + bori + "-" + grdId + "']").remove();
                // Toggle icons

                selectedTrucks = selectedTrucks.filter(id => id !== truckId);
                selectedMarka = selectedMarka.filter(id => id !== marka);
                refreshTruckSelects();
                row.find(".deselect-truck").addClass("d-none");
                row.find(".select-truck").removeClass("d-none");

                const detailsId = row.data('details-id');
                $('div#truck-toggle').html('-');
            });

            // Update toggle text with selected trucks
            function updateToggleText() {
                let selected = $("#truck option:selected").map(function() {
                    return $(this).text();
                }).get();

                $("#truck-toggle").text(selected.length ? selected.join(", ") : "- Select -");
            }
        });
        $(document).ready(function() {
            updateSubmitButton();


            // Select truck
            $(document).on("click", ".select-truck", function() {
                let row = $(this).closest("tr");
                let truckId = row.data("truck-id");
                let detailsId = row.data("details-id");
                let bori = parseFloat(row.data("bori")) || 0;
                let weight = parseFloat(row.data("weight")) || 0;
                let mainCate = row.data("main-cate") || '';
                let parentCate = row.data("parent-cate") || '';
                let childCate = row.data("child-cate") || '';

                // Toggle icons
                row.find(".select-truck").addClass("d-none");
                row.find(".deselect-truck").removeClass("d-none");

                // MARK AS SELECTED
                row.addClass("is-selected");

                // icon toggle
                row.find(".select-truck").addClass("d-none");
                row.find(".deselect-truck").removeClass("d-none");

                updateSubmitButton();
            });

            // Deselect truck
            $(document).on("click", ".deselect-truck", function() {
                let row = $(this).closest("tr");
                let truckId = row.data("truck-id");
                let detailId = row.data("details-id");

                // Toggle icons
                row.find(".deselect-truck").addClass("d-none");
                row.find(".select-truck").removeClass("d-none");
                // REMOVE SELECT STATE
                row.removeClass("is-selected");

                // icon toggle
                row.find(".deselect-truck").addClass("d-none");
                row.find(".select-truck").removeClass("d-none");

                let selectedCount = $("tr.is-selected").length;

                if (selectedCount === 0) {
                    $(".select-truck").prop("disabled", false);
                }

                $("#truck option[value='" + truckId + "']").prop("selected", false);

                updateSubmitButton();
            });

            // Manual remove button inside item-table
            $(document).on("click", ".remove-row", function() {
                let row = $(this).closest("tr");
                let truckId = row.data("truck-id");
                let detailId = row.data("details-id");

                // Remove from hidden select
                $("#truck option[value='" + truckId + "']").prop("selected", false);

                // Reset dropdown icons
                $(".truck-details[data-details-id='" + detailId + "']")
                    .find(".deselect-truck").addClass("d-none")
                    .end().find(".select-truck").removeClass("d-none");

                row.remove();
                updateSubmitButton();
                updateTotals();
            });
        });
    </script>


    @php
        $truckDataArray = $sale->salesItemsDetails
            ->map(function ($item) {
                return [
                    'good_detail_id' => $item->good_detail_id,
                    'id' => $item->id_sid,
                    'bori' => $item->bori,
                    'weight' => $item->weight,
                    'marka' => $item->marka,
                    'rate' => $item->rate,
                    'amount' => $item->amount,
                    'mainCate' => $item->items_main_cate ?? '',
                    'parentCate' => $item->items_parent_cate ?? '',
                    'childCate' => $item->items_child_cate ?? '',
                    'mainCateName' =>
                        $item->productMainCate?->products_category_name_urdu ?? ($item->items_main_cate_name ?? ''),
                    'parentCateName' => $item->productParentCate?->name_urdu ?? ($item->items_parent_cate_name ?? ''),
                    'childCateName' => $item->productChildCate?->name_urdu ?? ($item->items_child_cate_name ?? ''),
                ];
            })
            ->values()
            ->toArray();
    @endphp

    <script>
        const truckData = @json($truckDataArray);
    </script>

    <script>
        function getTruckOptionsSelectedOnly(selectedId = '') {
            selectedId = selectedId ? String(selectedId) : '';
            let options = `<option value="">Select Truck</option>`;
            const selectedSet = (selectedTrucks || []).map(String);

            trucks.forEach(truck => {
                const id = String(truck.id_truck);
                // only include trucks that are in selectedTrucks OR the current select's value
                if (selectedSet.includes(id) || id === selectedId) {
                    const selected = id === selectedId ? 'selected' : '';
                    options += `<option value="${id}" ${selected}>${truck.truck_no}</option>`;
                }
            });

            return options;
        }

        // Ensure the select has the option for the given value/text and select it.
        // If option doesn't exist, append it.
        function ensureSelectOption($select, value, text) {
            value = value == null ? '' : String(value);
            text = text == null ? String(value) : String(text);
            if ($select.find("option[value='" + value + "']").length === 0) {
                $select.append(`<option value="${value}">${text}</option>`);
            }
            $select.val(value);
        }

        function refreshTruckSelects() {
            $('.select-truck-good').each(function() {
                const $sel = $(this);
                const currentVal = $sel.val() == null ? '' : String($sel.val());
                $sel.html(getTruckOptions(currentVal));
                if (currentVal !== '') $sel.val(currentVal);
            });
        }

        $(document).ready(function() {

            function autoFillTrucks() {
                Object.keys(truckData).forEach(goodDetailId => {
                    const detail = truckData[goodDetailId];

                    // Select the truck in the hidden select
                    $("#truck option[value='" + detail.good_detail_id + "']").prop("selected", true);
                    let $option = $("#truck option[data-grd-id='" + detail.good_detail_id + "']");

                    if (!$option.length) return;

                    $option.prop('selected', true);
                    const truckId = String($option.val() || '');
                    const bori = $option.data('bori') || detail.bori || '';
                    const label = $option.text() || truckId;

                    let badgeKey =
                        `${truckId}-${detail.mainCate}-${detail.parentCate}-${detail.childCate}-${detail.marka}`;
                    let badgeExists = $("#truck_labels span.badge[data-badge-key='" + badgeKey + "']")
                        .length > 0;

                    if (!badgeExists) {
                        $("#truck_labels").append(`
        <span class="badge bg-success me-1"
              data-id="${truckId}-${bori}-${detail.good_detail_id}"
              data-badge-key="${badgeKey}"
              data-truck-id="${truckId}"
              data-main-cate="${detail.mainCate}"
              data-parent-cate="${detail.parentCate}"
              data-child-cate="${detail.childCate}"
              data-marka="${detail.marka}">
           ${label}
        </span>
    `);
                    }

                    $("#truck-toggle").text(label);

                    const rowDropdown = $("tr.truck-details[data-details-id='" + detail.good_detail_id +
                        "']");
                    let marka = rowDropdown.data('marka');
                    if (rowDropdown.length) {
                        rowDropdown.addClass('is-selected deselect-truck');
                        rowDropdown.find(".btn-select").addClass("d-none");
                        rowDropdown.find(".btn-deselect").removeClass("d-none");
                        forceSelectTruckRow(rowDropdown);
                    } else {
                        console.warn("Row not found for", detail.good_detail_id);
                    }

                    if (truckId && !selectedTrucks.includes(truckId)) {
                        selectedTrucks.push(truckId);
                    }
                    if (!selectedMarka.includes(marka)) {
                        selectedMarka.push(marka);
                    }

                    rowDropdown.find(".btn-select").addClass("d-none");
                    rowDropdown.find(".btn-deselect").removeClass("d-none");

                    if (!selectedTrucks.includes(truckId)) {
                        selectedTrucks.push(truckId);
                    }
                    if (!selectedMarka.includes(marka)) {
                        selectedMarka.push(marka);
                    }
                    refreshTruckSelects();

                    // ✅ FIX: Append row to item-table
                    const rowHtml = `<tr data-truck-id="${truckId}" data-details-id="${detail.good_detail_id}" data-is-edit="true">
            <td>
                <select class="form-control select-truck-good" name="good_receipts_truck_ids[]">
                    ${getTruckOptions(truckId)}
                </select>
            </td>
            <td>
                <select class="form-control main-cate" name="main_category[]"></select>
            </td>
            <td>
                <select class="form-control parent-cate" name="parent_category[]"></select>
            </td>
            <td>
                <select class="form-control child-cate" name="child_category[]"></select>
            </td>
            <td>
                 <select class="form-control marka marka-select" name="marka[]"></select>
            </td>
            <td>
                <input type="hidden" id="setBori_${detail.good_detail_id}">
                <input type="text" class="form-control bori-check n-amount" name="bori[]" data-max-bori="" onkeyup="checkBoriQty(this)">
                <small class="text-muted">Available Bori: </small>
                <span class="bori-error text-danger" style="display:none;">Exceeded available Bori!</span>
            </td>
            <td>
                <input type="hidden" id="setWeight_${detail.good_detail_id}">
                <input type="text" class="form-control n-amount weight-input" name="weight[]" oninput="calculateAmount(this)">
                <span class="available-weight" style="display:none;">
                    Available Weight in stock: <span class="weight-quantity"></span>
                </span>
                <span class="outofstockWeight text-danger"></span>
            </td>
            <input type="hidden" class="good_receipt_detail_id" name="good_receipt_detail_id[]" value="${detail.good_detail_id}">
            <td><input type="text" class="form-control n-amount rate-input" name="rate[]" oninput="calculateAmount(this)"></td>
            <td><input type="text" class="form-control n-amount amount-input" name="amount[]" readonly></td>

            <td>
                <button type="button" class="btn btn-sm btn-outline-danger remove-row">
                    <i class="fa fa-trash"></i>
                </button>
            </td>
        </tr>`;

                    $('#item-table tbody').append(rowHtml);

                    const $lastRow = $('#item-table tbody tr:last');
                    const $main = $lastRow.find('.main-cate');
                    const $parent = $lastRow.find('.parent-cate');
                    const $child = $lastRow.find('.child-cate');
                    const $marka = $lastRow.find('.marka');


                    $lastRow.find('.n-amount').each(function() {
                        new AutoNumeric(this, {
                            digitGroupSeparator: ',',
                            decimalPlaces: 0,
                            decimalCharacter: '.',
                            minimumValue: '0',
                            unformatOnSubmit: true
                        });
                    });


                    $lastRow.find(".select-truck-good").trigger('change');

                    ensureSelectOption($main, detail.mainCate, detail.mainCateName || detail.mainCate);
                    ensureSelectOption($parent, detail.parentCate, detail.parentCateName || detail
                        .parentCate);
                    ensureSelectOption($child, detail.childCate, detail.childCateName || detail.childCate);


                    $main.trigger('change');
                    $parent.trigger('change');


                    $lastRow.data('original-detail', detail);
                    $child.trigger('change');

                    refreshTruckSelects();

                });
            }


            // Call it on page load
            autoFillTrucks();
            updateTotals();
            updateSubmitButton();
        });

        function forceSelectTruckRow(row) {
            if (row.hasClass('is-selected')) return;

            row.removeClass('select-truck')
                .addClass('deselect-truck is-selected');

            row.find('.btn-outline-success').addClass('d-none');
            row.find('.btn-outline-danger').removeClass('d-none');
        }

        function toggleTruckRow(row) {

            $('.dropdown-content').css('display', 'block');

            let isSelected = row.hasClass('is-selected');

            if (isSelected) {

                row.removeClass('deselect-truck is-selected')
                    .addClass('select-truck');

                row.find('.btn-outline-danger').addClass('d-none');
                row.find('.btn-outline-success').removeClass('d-none');


            } else {
                row.removeClass('select-truck')
                    .addClass('deselect-truck is-selected');

                row.find('.btn-outline-success').addClass('d-none');
                row.find('.btn-outline-danger').removeClass('d-none');
            }
        }

        $(document).on('click', '.truck-details', function(e) {
            e.stopPropagation();
            toggleTruckRow($(this));
        });

        function syncTruckRows() {

            $('.truck-details').each(function() {
                const row = $(this);

                if (row.hasClass('is-selected')) {
                    row.removeClass('select-truck')
                        .addClass('deselect-truck');
                } else {
                    row.removeClass('deselect-truck')
                        .addClass('select-truck');
                }
            });
        }
        $(document).ready(function() {

            Object.keys(truckData).forEach(goodDetailId => {
                const detail = truckData[goodDetailId];
                const rowDropdown = $("tr.truck-details[data-details-id='" + detail.good_detail_id + "']");
                let marka = rowDropdown.data('marka');


                let $option = $("#truck option[data-grd-id='" + detail.good_detail_id + "']");
                if (!$option.length) return;

                let truckId = $option.val();
                if (rowDropdown.length) {
                    rowDropdown.addClass('is-selected');
                    if (!truckId) return;
                    if (!selectedTrucks.includes(truckId)) {
                        selectedTrucks.push(truckId);
                    }

                    if (!selectedMarka.includes(marka)) {
                        selectedMarka.push(marka);
                    }

                    forceSelectTruckRow(rowDropdown);
                    refreshTruckSelects();


                }
            });

            syncTruckRows();

        });
    </script>
@endpush
