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

    .disabled-div {
        pointer-events: none;
        opacity: 0.5;
    }
</style>

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Sales</span>
        <span>Create Sale</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Create Sale
        <span>
            <a href="{{ route('sales.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to List
            </a>
        </span>
    </h2>

    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Create Sale</h5>
                <form action="{{ route('sales.store') }}" method="POST" id="salesForm">
                    @csrf
                    <input type="hidden" name="getGoodsDetailId" id="setGoodsDetailId">
                    <input type="hidden" name="getItemsMarka" id="setItemsMarka">
                    <input type="hidden" name="getMainCateName" id="setMainCateName">
                    <input type="hidden" name="getParentCateName" id="setParentCateName">
                    <input type="hidden" name="getChildCateName" id="setChildCateName">

                    <!-- Error Display -->
                    @if (count($errors) > 0)
                        <div class="p-1">
                            @foreach ($errors->all() as $error)
                                <div class="alert alert-warning alert-danger fade show" role="alert">{{ $error }}
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    <div class="row row-sm mg-b-20">
                        <div class="col-md-4 mt-2">
                            <div class="form-group">
                                <label class="az-content-label" for="sales_date">Date</label>
                                <input type="text" name="sales_date" id="sales_date" class="form-control"
                                    placeholder="dd/mm/yyyy" readonly />
                            </div>
                        </div>

                        <div class="col-md-8">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="truck" style="float: right;">
                                    <span style="color:red;">*</span>
                                    ٹرک نمبر
                                </label>
                                <!-- Hidden native select element -->
                                <select class="form-control d-none" name="good_receipts_truck_id" id="truck" required>
                                    <option value="">- Select -</option>
                                    @foreach ($trucks as $truck)
                                        @foreach ($truck->goodReceiptDetails as $details)
                                            <option value="{{ $truck->id_truck }}" data-bori="{{ $details->bori }}"
                                                data-grd-id="{{ $details->id_grd }}">
                                                {{ $truck->truck_no }} (Bori: {{ $details->bori }})
                                            </option>
                                        @endforeach
                                    @endforeach
                                </select>
                                <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-weight="{{ $detail->weight }}"
                                                                data-marka="{{ $detail->marka }}"
                                                                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-outline-success  ">
                                                                        <i class="fa fa-check"></i>
                                                                    </button>
                                                                    <button type="button"
                                                                        class="btn btn-sm 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 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">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            <div class="form-group">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <label class="az-content-label urdu-font" for="bill_no" style="float: right;">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    بل نمبر
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                </label>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <input type="text" class="form-control" name="bill_no" id="bill_no">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            </div>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        </div>-->
                        <div class="col-md-4">
                            <label class="az-content-label urdu-font" for="sales_status" style="float: right;">
                                حیثیت
                            </label>
                            <select id="sales_status" name="sales_status" class="form-control">
                                <option value="">Select</option>
                                <option value="1" selected>Active</option>
                                <option value="0" {{ old('sales_status') == '0' ? 'selected' : '' }}>
                                    In-Active
                                </option>
                            </select>
                            @error('sales_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <div 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 class="col-md-6 mt-3">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            <div class="form-group">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <label class="az-content-label urdu-font" for="bori_details" style="float: right;">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    بوری کی تفصیلات
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                </label>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <textarea class="form-control" name="bori_details" id="bori_details" cols="5" rows="5"></textarea>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            </div>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        </div>-->
                    </div>
                    <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>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>
                                                {{-- <th
                                                    style="font-size: 2vh; color: black; font-family: 'Jameel Noori Nastaleeq', serif; ">
                                                    Action
                                                </th> --}}
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {{-- <tr>
                                                <td>
                                                    <input type="hidden" id="setBori">
                                                    <input type="text" class="form-control n-amount bori-check"
                                                        name="bori" id="validateBori" readonly
                                                        onkeyup="checkBoriQty(this.value)">
                                                    <span id="available-bori" style="display: none;">
                                                        Available Bori in stock: <span id="bori-quantity"></span>
                                                    </span>
                                                    <span id="outofstock" class="text-danger"></span>
                                                </td>


                                                <td>
                                                    <input type="hidden" id="setWeight">
                                                    <input type="text" class="form-control n-amount weight-input"
                                                        name="weight" oninput="calculateAmount(this)">
                                                    <span id="available-weight" style="display: none;">
                                                        Available Weight in stock: <span id="weight-quantity"></span>
                                                    </span>
                                                    <span id="outofstockWeight" class="text-danger"></span>
                                                </td>
                                                <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>

                                            </tr> --}}
                                        </tbody>
                                    </table>
                                    <button type="button" class="btn btn-az-primary btn-block mt-2" id="add-more-btn"
                                        onclick="addRow()">
                                        <span class="mdi mdi-arrow-expand-up"></span> Add More
                                    </button>
                                    {{-- <td>
                                                    <button type="button" class="btn rounded shadow-base"
                                                        onclick="removeRow(this)">
                                                        <i class="text-danger fa-solid fa-trash-can"></i>
                                                    </button>
                                                </td> --}}
                                </div>
                            </div>
                        </div>
                        <!-- Additional Bori Details Section -->
                        <div class="col-md-6" id="dismyDiv">
                            <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-amount2"
                                                        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">
                                            <div class="row mt-4">
                        <div class="col-md-12">
                            <h4>Totals</h4>
                            <div class="form-group row">
                                <label for="total_bori" class="col-sm-2 col-form-label">Total Bori:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="total_bori" name="total_bori" value="{{ old('total_bori') }}"
                                        readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="remaining_amount" class="col-sm-2 col-form-label">Remaining
                                    Amount:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="remaining_amount"
                                        name="remaining_amount" readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="cash_received" class="col-sm-2 col-form-label">Cash Received:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="cash_received" name="cash_received" value="{{ old('cash_received') }}">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="total_amount" class="col-sm-2 col-fo --}}
                    <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-amount2" 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-amount2" id="cash_received"
                                        name="cash_received" value="{{ 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-amount2" 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-amount2 " 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">Submit</button>
                        </div>
                </form>
            </div>
        </div>
    </div>

    <div id="errorNotification" class="alert alert-danger position-fixed top-0 end-0 m-3" style="display: none;">
        <strong>Error!</strong> <span id="errorMessage">Please select the row you want to delete.</span>
    </div>
    <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-amount2').forEach(function(el) {
                new AutoNumeric(el, {
                    digitGroupSeparator: ',',
                    decimalPlaces: 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);
            }
        }
        // For Weight
        function checkWeightQty(inputWeight) {
            var availableWeight = $('#setWeight').val();
            var outofstockSpanWeight = document.getElementById('outofstockWeight');
            var weightSpan = document.getElementById('available-weight');
            var submitBtn = document.getElementById('submitData');
            var weightInput = document.querySelector('.weight-input');

            // Convert the values to numbers to compare them properly
            inputWeight = parseFloat(inputWeight);
            availableWeight = parseFloat(availableWeight);

            if (inputWeight > availableWeight) {
                // If input is greater than available, mark input field as red
                $(weightInput).addClass('border-danger').removeClass('border-none');
                weightSpan.style.display = 'none';
                outofstockSpanWeight.textContent = 'Weight must be under! ' + availableWeight;
                submitBtn.disabled = true;
            } else {
                // If input is within available stock, reset the border and enable save
                $(weightInput).removeClass('border-danger');
                weightSpan.style.display = 'inline';
                outofstockSpanWeight.textContent = '';
                submitBtn.disabled = false;
            }
        }


        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 rate = parseFloat(AutoNumeric.getNumber(row.querySelector('.rate-input'))) || 0;
            // Calculate the amount (رقم)
            let 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 = '') {
            if (selectedTrucks.length === 0) {
                return `<option value="">Select Truck</option>`;
            }
            let options = `<option value="">Select Truck</option>`;
            trucks.forEach(truck => {
                if (selectedTrucks.includes(truck.id_truck)) {
                    let selected = truck.id_truck == selectedId ? 'selected' : '';
                    options += `<option value="${truck.id_truck}" ${selected}>${truck.truck_no}</option>`;
                }
            });

            return options;
        }
        $(document).ready(function() {
            refreshTruckSelects();
        });

        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.value)">
                <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,
                    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();

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

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

            // Populate marka and item selects in the new row

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

        function 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.selected').each(function() {
                let row = $(this);

                // agar specific truckId chahiye
                if (truckId && row.data('truck-id') != truckId) {
                    return;
                }

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

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

            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 an = AutoNumeric.getAutoNumericElement(boriInput);
                    if (!an) return;


                    // an.set(0);


                    let totalBori = Number(data.bori);



                    let usedBori = 0;
                    $('#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() == 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;


                    an.update({
                        maximumValue: remainingBori.toString()
                    });
                    // an.set(remainingBori);

                    // ✅ Update attributes & UI
                    $(boriInput).attr('data-max-bori', remainingBori).data('max-bori', remainingBori);
                    row.find('.text-muted').text('Available Bori: ' + remainingBori);
                    row.find('.good_receipt_detail_id').val(data.good_receipt_detail_id);
                },
                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').empty();
                    let parentSelect = row.find('.parent-cate').empty();
                    let childSelect = row.find('.child-cate').empty();

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



                    });
                    // Update Bori
                    // row.find('.bori-check')
                    //     .attr('data-max-bori', data.bori)
                    //     .val(1);

                    // row.find('.text-muted').text('Available Bori: ' + data.bori);

                    // // Update details_id hidden input
                    // row.find("input[name='good_receipt_detail_id[]']").val(data.details_id);
                }
            });
        });

        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,
                unformatOnSubmit: true
            });

            let bori = $('.bori-check').val();

            // Convert string to number, default 0 if empty
            bori = parseInt(bori, 10) || 0;


            // Increment
            bori++;


            $('.bori-check').val(bori);


            setTimeout(() => {
                if (newInput) newInput.focus();
            }, 50); // 50ms delay ensures AutoNumeric is fully ready

            updateBoriDetails();
            updateTotals();
        }

        function removeBoriRow(button) {

            $(button).closest('tr').remove();
            let bori = $('.bori-check').val();
            bori = parseInt(bori, 10) || 0;
            bori--;
            $('.bori-check').val(bori);
            updateBoriDetails();
            updateTotals();
        }

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

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

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


                totalBori += 1;


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

                // DO NOT overwrite the user input in boriEl
            });

            // Update item-table weight inputs and recalc amount
            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 total inputs (readonly)
            let totalBoriInput = $('#total_bori')[0];
            let totalWeightInput = $('#total_weight')[0];

            if (totalBoriInput) AutoNumeric.set(totalBoriInput, totalBori);
            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) {
                        // Populate marka select in the new row
                        // newRow.find('.marka-select').empty().append('<option value="">- Select -</option>');
                        // $.each(data.markas, function(_, marka) {
                        //     newRow.find('.marka-select').append(
                        //         `<option value="${marka}">${marka}</option>`);
                        // });

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

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

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


        // function updateTotals() {
        //     let totalBori = 0;
        //     let totalAmount = 0;


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

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

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

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


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

        //     // Update remaining amount when cash received changes
        //     $('#cash_received').on('input', function() {
        //         let cashReceived = parseFloat($(this).val()) || 0;
        //         let totalAmount = parseFloat($('#total_amount').val()) || 0;
        //         $('#remaining_amount').val(totalAmount - cashReceived);
        //     });
        // }
        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');
             if (cashReceivedEl && AutoNumeric.getAutoNumericElement(cashReceivedEl)) {
                AutoNumeric.getAutoNumericElement(cashReceivedEl).set(totalAmount);
            }
            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
            });

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

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

            // for truck custom dropdown

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

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

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

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

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

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

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

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

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

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

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

                var bori = row.cells[6].textContent;
                var weight = row.cells[7].textContent;
                var marka = row.cells[8].textContent;
                var mainCate = row.cells[1].textContent;
                var parentCate = row.cells[2].textContent;
                var childCate = row.cells[3].textContent;

                // For Bori
                var boriSpan = document.getElementById('available-bori');
                var boriQuantitySpan = document.getElementById('bori-quantity');
                var outofstockSpan = document.getElementById('outofstock');

                $('#setBori').val(bori);
                if (bori > 0) {
                    submitBtn.disabled = false;
                    boriQuantitySpan.textContent = bori;
                    boriSpan.style.display = 'inline'; // Show the span
                    document.querySelector('.bori-check').removeAttribute('readonly');
                    outofstockSpan.textContent = '';
                } else {
                    // submitBtn.disabled = true;
                    outofstockSpan.textContent = 'Out of stock!';
                    document.querySelector('.bori-check').setAttribute('readonly', true);
                    boriSpan.style.display = 'none';
                }

                // For Weight
                var weightSpan = document.getElementById('available-weight');
                var weightQuantitySpan = document.getElementById('weight-quantity');
                var outofstockSpanWeight = document.getElementById('outofstockWeight');

                $('#setWeight').val(weight);

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

        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

                        // You can add additional functionality like recalculating totals here
                        // Example: updateTotals();
                    } 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);
                    }
                }
            });


            // $(document).on('keydown', '.select2-search__field', function(e) {
            //     if (e.key === 'Enter') {
            //         e.stopPropagation();
            //     }
            // });
        });
    </script>

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

            // Function to initialize AutoNumeric on an input
            function initAutoNumeric(input) {
                new AutoNumeric(input, {
                    digitGroupSeparator: ',',
                    decimalCharacter: '.',
                    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();
                }
            });
        });

        function refreshTruckSelects() {
            $('.select-truck-good').each(function() {
                let currentId = $(this).val();
                $(this).html(getTruckOptions(currentId));
            });
        }
        $(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 detailId = row.data("details-id");
                let grdId = row.data("details-id");
                let bori = row.data("bori");
                let marka = row.data("marka");
                // alert(marka);

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

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

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


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

                updateToggleText();
                $('div#truck-toggle').html('-');
            });

            // Deselect truck
            $(document).on("click", ".deselect-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");

                selectedTrucks = selectedTrucks.filter(id => id !== truckId);
                selectedMarka = selectedMarka.filter(id => id !== marka);
                refreshTruckSelects();
                // Remove from hidden select
                $("#truck option[value='" + truckId + "']").prop("selected", false);


                $("#truck_labels span[data-id='" + truckId + "-" + bori + "-" + grdId + "']").remove();

                // $('div#truck-toggle').find(`span[data-id='${truckId}-${bori}-${grdId}']`).remove();
                // Toggle icons
                row.find(".deselect-truck").addClass("d-none");
                row.find(".select-truck").removeClass("d-none");

                updateToggleText();
                $('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();


            // function updateTruckStates() {
            //     // Get all currently selected truck IDs
            //     let selectedTruckIds = $("tr.truck-selected").map(function() {
            //         return $(this).data("truck-id");
            //     }).get();

            //     if (selectedTruckIds.length === 0) {
            //         // No truck selected → enable all trucks
            //         $(".select-truck").prop("disabled", false).removeClass("text-muted");
            //     } else {
            //         // Trucks of selected IDs remain enabled, others disabled
            //         $(".select-truck").each(function() {
            //             let row = $(this).closest("tr");
            //             if (selectedTruckIds.includes(row.data("truck-id"))) {
            //                 $(this).prop("disabled", false).removeClass("text-muted");
            //             } else {
            //                 $(this).prop("disabled", true).addClass("text-muted");
            //             }
            //         });
            //     }
            // }


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

                // disable other trucks
                // $(".select-truck").each(function() {
                //     let r = $(this).closest("tr");
                //     if (r.data("truck-id") != truckId) {
                //         $(this).prop("disabled", true);
                //     }
                // });

                // Append new row to item-table
                let newRow = `
        <tr data-truck-id="${truckId}" data-details-id="${detailsId}">
            <td><input type="text" class="form-control main-cate" name="main_category[]" readonly value="${mainCate}"></td>
            <td><input type="text" class="form-control parent-cate" name="parent_category[]" readonly value="${parentCate}"></td>
            <td><input type="text" class="form-control child-cate" name="child_category[]" readonly value="${childCate}"></td>
            <td>
                <input type="hidden" id="setBori_${detailsId}">
                <input type="text" class="form-control n-amount bori-check" value="1" name="bori[]" data-max-bori="${bori}" onkeyup="checkBoriQty(this.value)">
                <small class="text-muted">Available Bori: ${bori}</small>
                <span class="bori-error text-danger" style="display:none;">Exceeded available Bori!</span>
            </td>
                <input type="hidden" name='good_receipts_truck_ids[]' value="${truckId}">
            <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" 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(newRow);

                // Initialize AutoNumeric
                // $("#item-table tbody tr:last .n-amount").each(function() {
                //     new AutoNumeric(this, {
                //         digitGroupSeparator: ',',
                //         decimalPlaces: 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();
            });

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

                $("#item-table tbody tr[data-details-id='" + detailId + "']").remove();
                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();
            });
        });
        $(document).on('click', '.truck-details', function(e) {
            let row = $(this);
            $('.dropdown-content')
                .css('display', 'block')
            if (row.hasClass('select-truck')) {
                // Select the row
                row.removeClass('select-truck').addClass('deselect-truck selected');
                row.find('.btn-outline-success')
                    .removeClass('btn-outline-success')
                    .addClass('btn-outline-danger');
            } else if (row.hasClass('deselect-truck')) {
                // Deselect the row
                row.removeClass('deselect-truck selected').addClass('select-truck');
                row.find('.btn-outline-danger')
                    .removeClass('btn-outline-danger')
                    .addClass('btn-outline-success');
            } else {
                // If no class initially, treat as select
                row.addClass('deselect-truck selected');
                row.find('.btn-outline-success')
                    .removeClass('btn-outline-success')
                    .addClass('btn-outline-danger');
            }
        });

        addRow();
    </script>
@endpush
