@extends('layouts.master')

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

    .custom-dropdown {
        position: relative;
        display: inline-block;
        width: 100%;
    }

    .dropdown-toggle {
        background: white;
        border: 1px solid #ced4da;
        border-radius: 4px;
        padding: 5px;
        cursor: pointer;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: white;
        width: 100%;
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #ced4da;
        border-radius: 4px;
        box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.2);
        z-index: 1;
    }

    .table-hover tbody tr:hover {
        background-color: #f5f5f5;
    }

    .truck-details {
        cursor: pointer;
    }

    .urdu-text {
        font-family: 'Jameel Noori Nastaleeq', serif;
        font-weight: 700;
    }

    .form-label {
        text-align: right;
    }

    .form-control-urdu {
        text-align: right;
    }

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

    .urdu-font {
        font-size: 17px;
    }

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

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

    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Create B-Cheque</h5>
                <form action="{{ route('b_cheque.update', ['id' => Crypt::encrypt($b_cheque->id_b_cheque)]) }}"
                    method="POST">
                    @csrf
                    @method('PUT')
                    <!-- Error Display -->
                    @if (count($errors) > 0)
                        <div class="p-1">
                            @foreach ($errors->all() as $error)
                                <div class="alert alert-warning alert-danger fade show" role="alert">{{ $error }}
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    <input type="hidden" name="get_supplier_name" id="set_supplier_name"
                        value="{{ $b_cheque->supplier_name ?? '' }}">
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label" for="bCheck_date">Date</label>
                                <input type="text" class="form-control" name="bCheck_date" id="" readonly
                                    required value="{{ $b_cheque->date ?? '' }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="az-content-label" for="pb_no">PBNo</label>
                                <input type="text" class="form-control" name="pb_no" id="pb_no"
                                    value="{{ $b_cheque->pb_no ?? '' }}">
                            </div>
                        </div>

                        {{-- Truck Entries End --}}
                        <div class="col-md-12 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="truck" style="float: right;">
                                    <span style="color:red;">*</span> ٹرک نمبر
                                </label>

                                <!-- Hidden native select element -->
                                <select class="form-control d-none" name="good_receipts_truck_id" id="truck" required>
                                    <option value="">- Select -</option>
                                    @foreach ($soldTrucks as $truck)
                                        <option value="{{ $truck->id_truck }}"
                                            {{ $b_cheque->good_receipts_truck_id == $truck->id_truck ? 'selected' : '' }}>
                                            {{ $truck->truck_no }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Visible custom dropdown -->
                                <div class="custom-dropdown">
                                    {{-- <div class="selected-trucks mt-2" id="selected-trucks"></div> --}}
                                    <div class="dropdown-toggle form-control" id="truck-toggle">
                                        {{ $b_cheque->goodReceiptTruck->truck_no }}</div>
                                    <!-- Display selected truck here -->
                                    <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>Supplier</th>
                                                    <th>Main Category</th>
                                                    <th>Parent Category</th>
                                                    <th>Child Category</th>
                                                    <th>Marka</th>
                                                    <th>Bori</th>
                                                    <th>Weight</th>
                                                    <th>Price</th>
                                                    <th>Total Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody id="truck-table-body">
                                                {{-- @foreach ($sales as $sale)
                                                    @if (!is_null($sale->goodReceiptTruck))
                                                        @foreach ($sale->salesItemsDetails as $saleDetails)
                                                            <tr class="truck-details"

                                                                data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                data-truck-no="{{ $sale->goodReceiptTruck->truck_no }}"
                                                                data-salesdetails-id="{{ $saleDetails->id_sid }}"
                                                                data-supplier-id="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->id_supplier }}"
                                                                data-rent-received="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->rent_recieve }}">
                                                                <td>
                                                                    @php
                                                                        // $isSameTruck =
                                                                        //     $b_cheque->items->sales_d_id ==
                                                                        //     $saleDetails->id_sid;
                                                                        // $isSameTruck =
                                                                        //     $b_cheque->goodReceiptTruck->id_truck ==
                                                                        //     $sale->goodReceiptTruck->id_truck;
                                                                        $isSameTruck = $b_cheque->items->contains(
                                                                            'sales_d_id',
                                                                            $saleDetails->id_sid,
                                                                        );
                                                                    @endphp
                                                                    <input type="checkbox" class="truck-checkbox" hidden
                                                                        data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                        {{ $isSameTruck ? 'checked' : '' }}>
                                                                    <span class="checkbox-icons">
                                                                        <i
                                                                            class="fa-solid fa-circle-check text-success {{ $isSameTruck ? '' : 'd-none' }}"></i>
                                                                        <i
                                                                            class="fa-regular fa-circle-xmark text-dark {{ !$isSameTruck ? '' : 'd-none' }}"></i>
                                                                    </span>
                                                                </td>
                                                                <td>{{ $sale->goodReceiptTruck->truck_no }}</td>
                                                                <td>
                                                                    {{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->supplier_name ?? 'N/A' }}
                                                                </td>
                                                                <td data-mcat-id="{{ $saleDetails->items_main_cate }}">
                                                                    {{ $saleDetails->productMainCate->products_category_name }}
                                                                </td>
                                                                <td data-pcat-id="{{ $saleDetails->items_parent_cate }}">
                                                                    {{ $saleDetails->productParentCate->name }}</td>
                                                                <td data-ccat-id="{{ $saleDetails->items_child_cate }}">
                                                                    {{ $saleDetails->productChildCate->name }}</td>
                                                                <td>{{ $saleDetails->marka }}</td>
                                                                <td>{{ $saleDetails->bori }}</td>
                                                                <td>{{ $saleDetails->weight }}</td>
                                                                <td>{{ $saleDetails->rate }}</td>
                                                                <td>{{ $saleDetails->amount }}</td>
                                                            </tr>
                                                        @endforeach
                                                    @endif
                                                @endforeach --}}
                                                @foreach ($sales as $sale)
                                                    @if (!is_null($sale->goodReceiptTruck))
                                                        @foreach ($sale->salesItemsDetails as $saleDetails)
                                                            @php
                                                                // Check if this sale detail belongs to the same truck
                                                                $isSameTruck = $b_cheque->items->contains(
                                                                    'sales_d_id',
                                                                    $saleDetails->id_sid,
                                                                );
                                                                // Alternatively, if you want to compare truck IDs instead:
                                                                // $isSameTruck = $b_cheque->goodReceiptTruck->id_truck == $sale->goodReceiptTruck->id_truck;
                                                            @endphp

                                                            <tr class="truck-details {{ !$isSameTruck ? 'disabled' : '' }}"
                                                                data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                data-truck-no="{{ $sale->goodReceiptTruck->truck_no }}"
                                                                data-salesdetails-id="{{ $saleDetails->id_sid }}"
                                                                data-supplier-id="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->id_supplier }}"
                                                                data-rent-received="{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->rent_recieve }}">
                                                                <td>
                                                                    <input type="checkbox" class="truck-checkbox" hidden
                                                                        data-truck-id="{{ $sale->goodReceiptTruck->id_truck }}"
                                                                        {{ $isSameTruck ? 'checked' : '' }}>
                                                                    <span class="checkbox-icons">
                                                                        <i
                                                                            class="fa-solid fa-circle-check text-success {{ $isSameTruck ? '' : 'd-none' }}"></i>
                                                                        <i
                                                                            class="fa-regular fa-circle-xmark text-dark {{ !$isSameTruck ? '' : 'd-none' }}"></i>
                                                                    </span>
                                                                </td>
                                                                <td>{{ $sale->goodReceiptTruck->truck_no }}</td>
                                                                <td>{{ $sale->goodReceiptTruck->goodReceiptDetails->first()->goodReceipt->supplier->supplier_name ?? 'N/A' }}
                                                                </td>
                                                                <td data-mcat-id="{{ $saleDetails->items_main_cate }}">
                                                                    {{ $saleDetails->productMainCate?->products_category_name }}
                                                                </td>
                                                                <td data-pcat-id="{{ $saleDetails->items_parent_cate }}">
                                                                    {{ $saleDetails->productParentCate?->name }}</td>
                                                                <td data-ccat-id="{{ $saleDetails->items_child_cate }}">
                                                                    {{ $saleDetails->productChildCate?->name }}</td>
                                                                <td>{{ $saleDetails->marka }}</td>
                                                                <td>{{ $saleDetails->bori }}</td>
                                                                <td>{{ $saleDetails->weight }}</td>
                                                                <td>{{ $saleDetails->rate }}</td>
                                                                <td>{{ $saleDetails->amount }}</td>
                                                            </tr>
                                                        @endforeach
                                                    @endif
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Truck Entries End --}}

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="suppliers" style="float: right;">
                                    <span style="color:red;">*</span>
                                    سپلائرز
                                </label>
                                <select class="form-control select2" name="suppliers" id="suppliers" required>
                                    <option value="">- Select -</option>
                                    @foreach ($suppliers as $key => $supplier)
                                        <option value="{{ $supplier->id_supplier }}"
                                            {{ $supplier->id_supplier == $b_cheque->supplier_id ? 'selected' : '' }}>
                                            {{ $supplier->supplier_name }} - {{ $supplier->supplier_name_urdu }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            @error('suppliers')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="bilty_no" style="float: right;">
                                    بلٹی نمبر
                                </label>
                                <input type="text" class="form-control" name="bilty_no" id="bilty_no"
                                    value="{{ $b_cheque->bilty_no }}">
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" for="detail" style="float: right;">
                                    تفصیل
                                </label>
                                <input type="text" class="form-control" name="details" id="detail"
                                    value="{{ $b_cheque->detail }}">
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <label class="az-content-label" for="bCheck_status">Status</label>
                            <select id="bCheck_status" name="bCheck_status" class="form-control">
                                <option value="1" {{ $b_cheque->status == '1' ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ $b_cheque->status == '0' ? 'selected' : '' }}>In-Active</option>
                            </select>
                            @error('bCheck_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <!-- Item Details Section -->
                        <div class="col-md-12 mt-5">
                            <h4>
                                Item Details
                                {{-- <span class="hide-span">
                                    (The current values are not showing as merged, all values are showing separately!)
                                </span>
                                <span class="show-span d-none">
                                    (You have selected the same values, Now the values are merged)
                                </span> --}}
                            </h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table table-bordered" id="item-table">
                                    <thead>
                                        <tr>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Main Cate
                                            </th>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Parent Cate
                                            </th>
                                            <th style="font-size: 13px; color: black; text-align: left;">
                                                Child Cate
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                مارکہ
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                بوری
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                وزن
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                ریٹ
                                            </th>
                                            <th
                                                style="font-size: 2vh; color: black; text-align: right; font-family: 'Jameel Noori Nastaleeq', serif;">
                                                رقم
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody id="item-details">
                                        @foreach ($b_cheque->items as $key => $items)
                                            @php
                                                $uniqueId = $key + 1; // unique id for each row
                                            @endphp
                                            <tr data-truck-no="{{ $b_cheque->goodReceiptTruck->id_truck }}"
                                                data-salesdetails-id="{{ $items->sales_d_id }}">

                                                <input type="hidden" name="salesDeId[]"
                                                    value="{{ $items->sales_d_id }}">

                                                {{-- Main Category --}}
                                                <td>
                                                    <select class="form-control form-control-sm mainCateSelect"
                                                        id="mainCate_{{ $uniqueId }}" name="mainCate[]"
                                                        onchange="checkForParentCate(this.value, {{ $uniqueId }})">
                                                        <option value="">Select Main</option>
                                                        @foreach ($productCateMain as $main)
                                                            <option value="{{ $main->id_pro_cate_main }}"
                                                                {{ $items->main_cate == $main->id_pro_cate_main ? 'selected' : '' }}>
                                                                {{ $main->products_category_name }} |
                                                                {{ $main->products_category_name_urdu }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </td>

                                                {{-- Parent Category --}}
                                                <td>
                                                    <select class="form-control form-control-sm parentCateSelect"
                                                        id="parentCate_{{ $uniqueId }}" name="parentCate[]"
                                                        data-selected="{{ $items->parent_cate }}"
                                                        onchange="checkForChildCate(this.value, {{ $uniqueId }})">
                                                        <option value="">Select Parent</option>
                                                        @if ($items->parent_cate)
                                                            <option value="{{ $items->parent_cate }}" selected>
                                                                {{ $items->parent_cate_name ?? 'Selected Parent' }}
                                                            </option>
                                                        @endif
                                                    </select>
                                                </td>

                                                {{-- Child Category --}}
                                                <td>
                                                    <select class="form-control form-control-sm childCateSelect"
                                                        id="childCate_{{ $uniqueId }}" name="childCate[]"
                                                        data-selected="{{ $items->child_cate }}"
                                                        onchange="updateChildValue({{ $uniqueId }})">
                                                        <option value="">Select Child</option>
                                                        @if ($items->child_cate)
                                                            <option value="{{ $items->child_cate }}" selected>
                                                                {{ $items->child_cate_name ?? 'Selected Child' }}
                                                            </option>
                                                        @endif
                                                    </select>
                                                </td>


                                                {{-- Marka --}}
                                                <td>
                                                    <input type="text" readonly class="form-control form-control-sm"
                                                        name="marka[]" value="{{ $items->marka }}">
                                                </td>

                                                {{-- Bori --}}
                                                <td>
                                                    <input type="text" step="any"
                                                        class="form-control form-control-sm bori-field boriSet n-amount"
                                                        name="bori[]" value="{{ $items->bori }}">
                                                </td>

                                                {{-- Weight --}}
                                                <td>
                                                    <input type="text" step="any"
                                                        class="form-control form-control-sm weight-field weightSet n-amount"
                                                        name="weight[]" value="{{ $items->weight }}">
                                                </td>

                                                {{-- Rate --}}
                                                <td>
                                                    <input type="text" step="any"
                                                        class="form-control form-control-sm rate-field rate-input rateSet n-amount"
                                                        name="rate[]" value="{{ $items->rate }}">
                                                </td>

                                                {{-- Amount (auto-calculated) --}}
                                                <td>
                                                    <input type="text" step="any"
                                                        class="form-control form-control-sm amount-field amountSet n-amount"
                                                        name="amount[]" value="{{ $items->amount }}" readonly>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>


                                </table>
                            </div>
                        </div>
                    </div>
                    <br>
                    <hr>
                    <br>
                    <?php
                    $prefNames = ['Labour', 'Bazaar Fees', 'Post Expense', 'Commission'];
                    $gen_pref = app\GeneralPrefrence::whereIn('name', $prefNames)->get()->keyBy('name');
                    
                    $labour = $gen_pref->get('Labour');
                    $bazaar_fees = $gen_pref->get('Bazaar Fees');
                    $post_expense = $gen_pref->get('Post Expense');
                    $commission = $gen_pref->get('Commission');
                    ?>
                    <div class="row urdu-text">
                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="total_amount" class="form-label">:کل رقم</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="total_amount"
                                    readonly name="total_amount" placeholder="کل رقم درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="total_expanse_amount" class="form-label">:کل خرچہ</label>
                                <input type="text" class="form-control form-control-urdu n-amount"
                                    id="total_expanse_amount" readonly name="total_expanse_amount"
                                    placeholder="کل خرچہ درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="save_amount" class="form-label">:بچت</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="save_amount"
                                    name="save_amount" placeholder=" بچت درج کریں">
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="total_bori" class="form-label">:کل بوریاں</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="total_bori"
                                    readonly name="total_bori" placeholder="کل بوریاں درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="F" class="form-label">:وزن</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="total_weight"
                                    readonly name="total_weight" placeholder="وزن درج کریں">
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="commission_rate" class="form-label">
                                    <span style="float: left; font-size: 1.9vh; font-weight: 100 !important;">Put The value
                                        of total in percentage <span style="color: red;">(%)</span></span>
                                    <span>:کمیشن ریٹ</span>
                                </label>
                                <input type="number" class="form-control form-control-urdu " id="commission_rate"
                                    name="commission_rate" placeholder="کمیشن ریٹ درج کریں" max="100"
                                    value="{{ $b_cheque->details->commission_rate ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="commission" class="form-label">:کمیشن</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="commission"
                                    readonly name="commission" placeholder="کمیشن درج کریں">
                            </div>
                            <div class="form-group mb-3">
                                <label for="more" class="form-label">:مزید</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="more"
                                    name="extra_pay" placeholder="اضافی رقم درج کریں"
                                    value="{{ $b_cheque->details->else_more_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="payment_details" class="form-label">:تفصیلات</label>
                                <textarea class="form-control form-control-urdu" name="payment_details" id="payment_details" rows="5"
                                    placeholder="تفصیلات درج کریں">{{ $b_cheque->details->payment_details ?? '' }}</textarea>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group mb-3">
                                <label for="rent_received" class="form-label">:کرایہ وصول</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="rent_received"
                                    name="rent_received" placeholder="کرایہ وصول کریں"
                                    value="{{ $b_cheque->details->rent_recieve_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> : کل مزدوری بوری </label>
                                <input type="text" class="form-control form-control-urdu n-amount"
                                    id="total_bori_mazdori" name="total_bori_mazdori" placeholder="مزدوری درج کریں"
                                    value="{{ $b_cheque->details->total_bori_mazdori ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> <span
                                        style="font-weight:bold;padding-right:5px;" id="mazdoori_total">-</span>
                                    :مزدوری</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="labour"
                                    name="labour" placeholder="مزدوری درج کریں"
                                    value="{{ $b_cheque->details->labour_amount ?? '' }}">
                            </div>

                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> :کل کَٹا</label>
                                <input value="{{ $b_cheque->details->total_katta ?? '' }}" type="text"
                                    class=" n-amount form-control form-control-urdu" id="total_katta" name="total_katta"
                                    placeholder=" کَٹا درج کریں کل" value="{{ $b_cheque->details->total_katta ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="labour" class="form-label"> :مزدوری کَٹا</label>
                                <input value="{{ $b_cheque->details->labour_katta_amount }}" type="text"
                                    class=" n-amount form-control form-control-urdu" id="labour_katta"
                                    name="labour_katta" placeholder="مزدوری کَٹا درج کریں"
                                    value="{{ $b_cheque->details->labour_katta_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="market_fees" class="form-label">:بازار کی فیس</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="market_fees"
                                    name="market_fees" placeholder="بازار کی فیس درج کریں"
                                    value="{{ $b_cheque->details->market_fees_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="post_expense" class="form-label">:پوسٹ خرچ</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="post_expense"
                                    name="post_expense" placeholder="پوسٹ خرچ درج کریں"
                                    value="{{ $b_cheque->details->post_expense_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="miscellaneous_expense" class="form-label">:متفرق خرچ</label>
                                <input type="text" class="form-control form-control-urdu n-amount"
                                    id="miscellaneous_expense" name="miscellaneous_expense"
                                    placeholder="متفرق خرچ درج کریں"
                                    value="{{ $b_cheque->details->miscellaneous_expense_amount ?? '' }}">
                            </div>
                            <div class="form-group mb-3">
                                <label for="cash" class="form-label">:نقد</label>
                                <input type="text" class="form-control form-control-urdu n-amount" id="cash"
                                    name="cash" placeholder="نقد رقم درج کریں"
                                    value="{{ $b_cheque->details->cash_amount ?? '' }}">
                            </div>
                        </div>
                        <div class="mt-5">
                            <a href="{{ route('b_cheque.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                            <button type="submit" class="btn btn-az-primary pd-x-20">Update</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        // $(document).ready(function() {
        //     $('.mainCateSelect').trigger('change');
        // });
        // const checkParentUrl = "{{ route('check-cate-parent') }}";
        // const checkChildUrl = "{{ route('check-cate-child') }}";

        // function checkForParentCate(productMainCateId, uniqId) {

        //     let productMainCateIdNew = $('#mainCate_' + uniqId).val();
        //     let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);
        //     $.ajax({
        //         url: checkParentUrl,
        //         type: 'GET',
        //         data: {
        //             productMainCateId: productMainCateIdNew
        //         },
        //         success: function(response) {
        //             if (response.productParentCate.length > 0) {
        //                 let options = '<option value="">Select Item</option>';
        //                 response.productParentCate.forEach(function(subParentCategory) {
        //                     options +=
        //                         `<option value="${subParentCategory.id_pro_sub_cat_parent}">${subParentCategory.name} | ${subParentCategory.name_urdu}</option>`;
        //                 });
        //                 $('#parentCate_' + uniqId).html(options).trigger('change');
        //                 // Update hidden row's mainCate and reset parent/child
        //                 if (hiddenRow.length) {
        //                     hiddenRow.find('input[name="mainCate[]"]').val(productMainCateIdNew);
        //                     hiddenRow.find('input[name="parentCate[]"]').val('');
        //                     hiddenRow.find('input[name="childCate[]"]').val('');
        //                 }

        //             }
        //         },
        //         error: function() {
        //             alert('Error checking Product Parent Category!');
        //         }
        //     });
        // }

        // function checkForChildCate(productParentCateId, uniqId) {
        //     let productParentCateIdNew = $('#parentCate_' + uniqId).val();
        //     let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);
        //     $.ajax({
        //         url: checkChildUrl,
        //         type: 'GET',
        //         data: {
        //             productParentCateId: productParentCateIdNew
        //         },
        //         success: function(response) {
        //             if (response.productChildCate.length > 0) {
        //                 let options = '<option value="">Select Item</option>';
        //                 response.productChildCate.forEach(function(subChildCategory) {
        //                     options +=
        //                         `<option value="${subChildCategory.id_pro_sub_cat_child}">${subChildCategory.name} | ${subChildCategory.name_urdu}</option>`;
        //                 });
        //                 $('#childCate_' + uniqId).html(options);
        //                 if (hiddenRow.length) {
        //                     hiddenRow.find('input[name="parentCate[]"]').val(productParentCateIdNew);
        //                     hiddenRow.find('input[name="childCate[]"]').val('');
        //                 }


        //             }
        //         },
        //         error: function() {
        //             alert('Error checking Product Child Category!');
        //         }
        //     });
        // }
        function initAutoNumeric() {
            document.querySelectorAll('.n-amount').forEach(el => {
                if (!AutoNumeric.getAutoNumericElement(el)) {
                    new AutoNumeric(el, {
                        digitGroupSeparator: ',',
                        decimalPlaces: 2,
                        unformatOnSubmit: true
                    });
                }
            });
        }
        initAutoNumeric(); // on page load

        $(document).on('input', '.boriSet, .weightSet, .rateSet', function() {

            const row = $(this).closest('tr');
            const salesDeId = row.data('salesdetails-id');

            // ----------------------------
            // AutoNumeric SAFE get function
            // ----------------------------
            const getAN = (el) => {
                const dom = el.get(0);
                const an = AutoNumeric.getAutoNumericElement(dom);
                if (an) {
                    return Number(an.getNumericString()); // "12,000" -> 12000
                }
                return Number(el.val().replace(/,/g, "")) || 0;
            };

            // ----------------------------
            // Get values from row
            // ----------------------------
            const bori = getAN(row.find('.boriSet'));
            const weight = getAN(row.find('.weightSet'));
            const rate = getAN(row.find('.rateSet'));

            // ----------------------------
            // Calculate amount
            // ----------------------------
            let newAmount = 0;
            if (weight > 0 && rate > 0) {
                newAmount = (weight * rate) / 40;
            }

            // ----------------------------
            // Set amount formatted
            // ----------------------------
            const amountEl = row.find('.amountSet').get(0);
            const amountAN = AutoNumeric.getAutoNumericElement(amountEl);

            if (amountAN) {
                amountAN.set(newAmount);
            } else {
                row.find('.amountSet').val(newAmount.toFixed(2));
            }

            // ----------------------------
            // Update Hidden Row (Backend Sync)
            // ----------------------------
            const hiddenRow = $(`#item-details tr.hiddenRow[data-salesdetails-id="${salesDeId}"]`);

            hiddenRow.find('input[name="bori[]"]').val(bori);
            hiddenRow.find('input[name="weight[]"]').val(weight);
            hiddenRow.find('input[name="rate[]"]').val(rate);
            hiddenRow.find('input[name="amount[]"]').val(newAmount);

            // ----------------------------
            // Update totals
            // ----------------------------
            updateTotals();
        });

        $(document).ready(function() {
            $('.mainCateSelect').each(function() {
                let uniqId = $(this).attr('id').split('_')[1]; // extract uniqueId
                $(this).trigger('change'); // trigger change to load parent and child
            });
        });

        const checkParentUrl = "{{ route('check-cate-parent') }}";
        const checkChildUrl = "{{ route('check-cate-child') }}";

        function checkForParentCate(productMainCateId, uniqId) {

            let productMainCateIdNew = $('#mainCate_' + uniqId).val();
            let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);

            // Get pre-selected parent ID from data attribute
            let preSelectedParent = $('#parentCate_' + uniqId).data('selected') || '';

            $.ajax({
                url: checkParentUrl,
                type: 'GET',
                data: {
                    productMainCateId: productMainCateIdNew
                },
                success: function(response) {
                    if (response.productParentCate.length > 0) {
                        let options = '<option value="">Select Item</option>';
                        response.productParentCate.forEach(function(subParentCategory) {
                            let isSelected = (subParentCategory.id_pro_sub_cat_parent ==
                                preSelectedParent) ? 'selected' : '';
                            options +=
                                `<option value="${subParentCategory.id_pro_sub_cat_parent}" ${isSelected}>${subParentCategory.name} | ${subParentCategory.name_urdu}</option>`;
                        });

                        $('#parentCate_' + uniqId).html(options);

                        // Trigger child load if parent is preselected
                        if (preSelectedParent) {
                            $('#parentCate_' + uniqId).trigger('change');
                        }

                        if (hiddenRow.length) {
                            hiddenRow.find('input[name="mainCate[]"]').val(productMainCateIdNew);
                            hiddenRow.find('input[name="parentCate[]"]').val(preSelectedParent);
                            hiddenRow.find('input[name="childCate[]"]').val('');
                        }
                    }
                },
                error: function() {
                    alert('Error checking Product Parent Category!');
                }
            });
        }

        function checkForChildCate(productParentCateId, uniqId) {
            let productParentCateIdNew = $('#parentCate_' + uniqId).val();
            let hiddenRow = $(`#item-details tr.hiddenRow[data-uniq-id="${uniqId}"]`);

            // Get pre-selected child ID from data attribute
            let preSelectedChild = $('#childCate_' + uniqId).data('selected') || '';

            $.ajax({
                url: checkChildUrl,
                type: 'GET',
                data: {
                    productParentCateId: productParentCateIdNew
                },
                success: function(response) {
                    if (response.productChildCate.length > 0) {
                        let options = '<option value="">Select Item</option>';
                        response.productChildCate.forEach(function(subChildCategory) {
                            let isSelected = (subChildCategory.id_pro_sub_cat_child ==
                                preSelectedChild) ? 'selected' : '';
                            options +=
                                `<option value="${subChildCategory.id_pro_sub_cat_child}" ${isSelected}>${subChildCategory.name} | ${subChildCategory.name_urdu}</option>`;
                        });

                        $('#childCate_' + uniqId).html(options);

                        if (hiddenRow.length) {
                            hiddenRow.find('input[name="parentCate[]"]').val(productParentCateIdNew);
                            hiddenRow.find('input[name="childCate[]"]').val(preSelectedChild);
                        }
                    }
                },
                error: function() {
                    alert('Error checking Product Child Category!');
                }
            });
        }

        function calculateAmount(input) {
            // Find the row where the input is located
            let row = input.closest('tr');

            // Get the weight and rate inputs
            let weight = row.querySelector('.weight-input').value;
            let rate = row.querySelector('.rate-input').value;

            // If both weight and rate are filled, calculate the amount
            if (weight && rate) {
                let amount = (parseFloat(rate) * parseFloat(weight)) / 40;
                // Set the calculated amount in the amount field
                row.querySelector('.amount-input').value = amount.toFixed(2); // Rounds to 2 decimal places
                updateTotals();
            }
        }

        $(document).ready(function() {
            // Initialize Select2 and Datepicker
            $('#suppliers').select2({
                theme: 'default'
            });

            var today = new Date();
            var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' +
                today.getDate()).slice(-2);

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

            // Initialize datepicker with custom format

            $("#bCheck_date").datepicker({
                dateFormat: "yy-mm-dd"
            });

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

            // // Update totals on page load
            // updateTotals();
        });

        function validateCommissionRate() {
            let commissionRateInput = $('#commission_rate');
            let commissionRateValue = parseFloat(commissionRateInput.val()) || 0;
            let maxCommissionRate = 100;
            if (commissionRateValue > maxCommissionRate) {
                commissionRateInput.val(maxCommissionRate);
            }
        }

        $('#commission_rate').on('input', validateCommissionRate);

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

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

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

        //     // Get values for expenses and other inputs
        //     let labour = parseFloat($('input[name="labour"]').val()) || 0;
        //     let marketfee = parseFloat($('input[name="market_fees"]').val()) || 0;
        //     let postexp = parseFloat($('input[name="post_expense"]').val()) || 0;
        //     let miscellaneousExp = parseFloat($('input[name="miscellaneous_expense"]').val()) || 0;
        //     let commissionp = parseFloat($('input[name="commission_rate"]').val()) || 0;
        //     let rent_received = parseFloat($('input[name="rent_received"]').val()) || 0;
        //     let cash = parseFloat($('input[name="cash"]').val()) || 0;
        //     let more = parseFloat($('input[name="extra_pay"]').val()) || 0;

        //     // Calculate commission value based on total amount and commission rate
        //     let commissionVal = (totalAmount * commissionp) / 100;
        //     $('#commission').val(commissionVal.toFixed(2));
        //     let finalLabor = labour * totalBori;

        //     // Calculate the total expanses (cash received) including commission and other expenses
        //     let cashReceived = initialCashReceived + finalLabor + marketfee + postexp + miscellaneousExp + commissionVal +
        //         more + rent_received + cash;

        //     // Update the total fields
        //     $('#total_bori').val(totalBori);
        //     $('#mazdoori_total').html(finalLabor);
        //     $('#total_weight').val(totalWeight);
        //     $('#total_amount').val(totalAmount);
        //     $('#total_expanse_amount').val(cashReceived.toFixed(2));
        //     $('#save_amount').val((totalAmount - cashReceived).toFixed(2));
        // }


        function updateTotals() {

            let totalBori = 0;
            let totalWeight = 0;
            let totalAmount = 0;

            // Function to get value from autonumeric OR normal input
            const getVal = (el) => {
                if (!el) return 0;

                if (AutoNumeric.isManagedByAutoNumeric(el)) {
                    return parseFloat(AutoNumeric.getAutoNumericElement(el).getNumericString()) || 0;
                }

                return parseFloat(el.value.replace(/,/g, '')) || 0;
            };

            // Loop table rows
            $('#item-table tbody tr').each(function() {
                totalBori += getVal($(this).find('input[name="bori[]"]')[0]);
                totalWeight += getVal($(this).find('input[name="weight[]"]')[0]);
                totalAmount += getVal($(this).find('input[name="amount[]"]')[0]);
            });

            // Other values
            let labour = getVal(document.querySelector('input[name="labour"]'));
            let total_katta = getVal(document.querySelector('input[name="total_katta"]'));
            let total_bori_mazdori = getVal(document.querySelector('input[name="total_bori_mazdori"]'));
            let labour_katta = getVal(document.querySelector('input[name="labour_katta"]'));

            let total_katta_charges = total_katta * labour_katta;

            let marketfee = getVal(document.querySelector('input[name="market_fees"]'));
            let postexp = getVal(document.querySelector('input[name="post_expense"]'));
            let misc = getVal(document.querySelector('input[name="miscellaneous_expense"]'));
            let commissionP = getVal(document.querySelector('input[name="commission_rate"]'));
            let rentReceived = getVal(document.querySelector('input[name="rent_received"]'));
            let cash = getVal(document.querySelector('input[name="cash"]'));
            let extra = getVal(document.querySelector('input[name="extra_pay"]'));

            // Calculations
            let commissionVal = (totalAmount * commissionP) / 100;
            let finalLabor = labour * total_bori_mazdori;

            let totalExpense =
                finalLabor + marketfee + postexp + misc + commissionVal +
                extra + rentReceived + cash + total_katta_charges;

            // ===============================
            // SET FORMATTED OUTPUTS
            // ===============================

            AutoNumeric.getAutoNumericElement('#total_bori').set(totalBori);
            AutoNumeric.getAutoNumericElement('#total_weight').set(totalWeight);
            AutoNumeric.getAutoNumericElement('#total_amount').set(totalAmount);
            AutoNumeric.getAutoNumericElement('#commission').set(commissionVal);
            AutoNumeric.getAutoNumericElement('#total_expanse_amount').set(totalExpense);
            AutoNumeric.getAutoNumericElement('#save_amount').set(totalAmount - totalExpense);
        }
        // Recalculate totals when input values change
        function handleInputChange() {
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"], input[name="weight[]"]',
                updateTotals);
            $('input[name="extra_pay"], input[name="commission_rate"], input[name="miscellaneous_expense"], input[name="post_expense"], input[name="market_fees"], input[name="labour"],input[name="total_katta"],input[name="total_bori_mazdori"],input[name="labour_katta"] ,input[name="rent_received"], input[name="rent_received"], input[name="cash"]')
                .on('input', updateTotals);
        }

        // Initialize event listeners
        $(document).ready(function() {
            handleInputChange();
            updateTotals();
        });

        // For truck drop-down
        $(document).ready(function() {
            let selectedTruckNumbers = [];
            let selectedTruckIds = [];
            let selectedSuppliers = new Set();

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

            $('#truck-search').on('input', function() {
                showOnlyThisTruckDetails(this.value);
            });

            // Handle checkbox selection and icon toggle
            $('.truck-checkbox').on('change', function() {
                const truckId = $(this).data('truck-id');
                const truckNo = $(this).closest('tr').data('truck-no');
                const salesDetailsId = $(this).closest('tr').data('salesdetails-id');
                const supplierName = $(this).closest('tr').find('td:nth-child(3)').text().trim();
                const supplierId = $(this).closest('tr').data('supplier-id');
                const icons = $(this).siblings('.checkbox-icons');
                const rentReceived = $(this).closest('tr').data('rent-received');
                AutoNumeric.set('#rent_received', rentReceived || 0);
                // $('.hide-span').addClass('d-none');

                if (this.checked) {
                    selectedTruckNumbers.push(truckNo);
                    selectedTruckIds.push(truckId);
                    selectedSuppliers.add(supplierName);

                    // Show the checked icon, hide the unchecked icon
                    icons.find('.fa-circle-check').removeClass('d-none');
                    icons.find('.fa-circle-xmark').addClass('d-none');

                    // Reflect the selected truck's details in the Item Details table
                    appendSelectedTruckDetails($(this).closest('tr'));
                } else {
                    const index = selectedTruckNumbers.indexOf(truckNo);
                    if (index > -1) {
                        selectedTruckNumbers.splice(index, 1);
                        selectedTruckIds.splice(index, 1);
                    }

                    // Hide the checked icon, show the unchecked icon
                    icons.find('.fa-circle-check').addClass('d-none');
                    icons.find('.fa-circle-xmark').removeClass('d-none');

                    // Remove the unselected truck's details from the Item Details table
                    removeTruckDetails(salesDetailsId, $(this).closest('tr'));

                    // Update suppliers dropdown and check if supplier still exists
                    let supplierStillExists = false;
                    $('.truck-details').each(function() {
                        const otherSupplier = $(this).find('td:nth-child(3)').text().trim();
                        const otherTruckNo = $(this).data('truck-no');
                        if (selectedTruckNumbers.includes(otherTruckNo) && otherSupplier ===
                            supplierName) {
                            supplierStillExists = true;
                        }
                    });
                    if (!supplierStillExists) {
                        selectedSuppliers.delete(supplierName);
                    }
                }

                updateSelectedTrucks(truckNo);
                updateSuppliersDropdown(supplierId);
                filterTruckDetails();
            });

            // Function to append the selected truck's data in the Item Details table
            const productCateMainJson = @json($productCateMain);

            function appendSelectedTruckDetails(truckRow) {
                const truckNo = truckRow.data('truck-no');
                const salesDeId = truckRow.data('salesdetails-id');

                const mainCate = truckRow.find('td:nth-child(4)').attr('data-mcat-id');
                const parentCate = truckRow.find('td:nth-child(5)').attr('data-pcat-id');
                const childCate = truckRow.find('td:nth-child(6)').attr('data-ccat-id');
                const marka = truckRow.find('td:nth-child(7)').text();
                const bori = parseFloat(truckRow.find('td:nth-child(8)').text());
                const weight = parseFloat(truckRow.find('td:nth-child(9)').text());
                const rate = parseFloat(truckRow.find('td:nth-child(10)').text());
                const amount = parseFloat(truckRow.find('td:nth-child(11)').text());

                // Check if the row with salesDeId already exists in the Item Details table
                let existingRow = $('#item-details tr').filter(function() {
                    return $(this).data('salesdetails-id') == salesDeId;
                });

                if (existingRow.length > 0) {
                    // If exists, merge data by adding values to the existing row
                    const existingBori = parseFloat(existingRow.find('input[name="bori[]"]').val()) || 0;
                    const existingWeight = parseFloat(existingRow.find('input[name="weight[]"]').val()) || 0;
                    const existingAmount = parseFloat(existingRow.find('input[name="amount[]"]').val()) || 0;

                    existingRow.find('input[name="bori[]"]').val(existingBori + bori);
                    existingRow.find('input[name="weight[]"]').val(existingWeight + weight);
                    existingRow.find('input[name="amount[]"]').val(existingAmount + amount);

                    existingRow.find('.boriSet').text((existingBori + bori).toFixed(2));
                    existingRow.find('.weightSet').text((existingWeight + weight).toFixed(2));
                    existingRow.find('.amountSet').text((existingAmount + amount).toFixed(2));
                } else {
                    let mainOptions = `<option value="">Select Main Cate</option>`;

                    productCateMainJson.forEach(function(main) {
                        const selected = mainCate == main.id_pro_cate_main ? 'selected' : '';
                        mainOptions +=
                            `<option data-mcat-id='${main.id_pro_cate_main}' value="${main.id_pro_cate_main}" ${selected}>${main.products_category_name} | ${main.products_category_name_urdu}</option>`;
                    });
                    // If it doesn't exist, add a new row with this truck's details
                    $('#item-details').append(`
    <tr data-truck-no="${truckNo}" data-salesdetails-id="${salesDeId}">
        <input type="hidden" name="salesDeId[]" value="${salesDeId}">
        <td>
            <select class="form-control form-control-sm mainCateSelect"
                name="mainCate[]"
              id="mainCate_${salesDeId}"
                onchange="checkForParentCate(this.value, ${salesDeId})">
                <option value="">Select Main</option>
                 ${mainOptions}
            </select>

        </td>
        <td>
            <select class="form-control form-control-sm parentCateSelect"
                name="parentCate[]"
                 id="parentCate_${salesDeId}"
                onchange="checkForChildCate(this.value, ${salesDeId})">
                <option value="">Select Parent</option>
            </select>

        </td>
        <td>
            <select class="form-control form-control-sm childCateSelect"
                name="childCate[]"
                 id="childCate_${salesDeId}"
                onchange="updateChildValue(${salesDeId})">
                <option value="">Select Child</option>
            </select>

        </td>
        <td>
            <input type="text" readonly class="form-control form-control-sm"
                name="marka[]" value="${marka}">

        </td>
        <td>
            <input type="number" step="any" class="form-control form-control-sm bori-field boriSet n-amount"
                name="bori[]" value="${bori}">


        </td>
        <td>
            <input type="number" step="any" class="form-control form-control-sm weight-field weightSet n-amount"
                name="weight[]" value="${weight}">


        </td>
        <td>
            <input type="number" step="any" class="form-control form-control-sm rate-field rate-input rateSet n-amount"
                name="rate[]" value="${rate}">


        </td>
        <td>
            <input type="number"  step="any" class="form-control form-control-sm amount-field amountSet n-amount"
                name="amount[]" value="${amount}" readonly>

        </td>
    </tr>
`);


                    $(`#mainCate_${salesDeId}`).val(mainCate).trigger('change');
                    setTimeout(() => {
                        $(`#parentCate_${salesDeId}`).val(parentCate).trigger('change');
                        setTimeout(() => {
                            $(`#childCate_${salesDeId}`).val(childCate);
                        }, 400);
                    }, 400);

                }
                updateTotals();
                initAutoNumeric();
            }

            // Function to remove a truck's details from the Item Details table when unchecked
            function removeTruckDetails(salesDetailsId, truckRow) {
                let existingRow = $(`#item-details tr[data-salesdetails-id="${salesDetailsId}"]`);

                if (existingRow.length > 0) {
                    const bori = parseFloat(existingRow.find('input[name="bori[]"]').val());
                    const weight = parseFloat(existingRow.find('input[name="weight[]"]').val());
                    const amount = parseFloat(existingRow.find('input[name="amount[]"]').val());

                    const mainCate = truckRow.find('td:nth-child(4)').text();
                    const parentCate = truckRow.find('td:nth-child(5)').text();
                    const childCate = truckRow.find('td:nth-child(6)').text();
                    const marka = truckRow.find('td:nth-child(7)').text();
                    const rate = parseFloat(truckRow.find('td:nth-child(10)').text());

                    // Update the quantities if the selected truck details were merged
                    const existingBori = parseFloat(existingRow.find('.boriSet').text()) - bori;
                    const existingWeight = parseFloat(existingRow.find('.weightSet').text()) - weight;
                    const existingAmount = parseFloat(existingRow.find('.amountSet').text()) - amount;

                    if (existingBori > 0 || existingWeight > 0 || existingAmount > 0) {
                        existingRow.find('.boriSet').text(existingBori.toFixed(2));
                        existingRow.find('.weightSet').text(existingWeight.toFixed(2));
                        existingRow.find('.amountSet').text(existingAmount.toFixed(2));
                    } else {
                        existingRow.remove();
                    }
                }

                updateTotals();
            }

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

            function updateSelectedTrucks(truckNo) {
                // $('#selected-trucks').text('Selected Truck: ' + truckNo);
                selectedTruckIds.forEach(function(truckId) {
                    $('#truck').append('<option value="' + truckId + '" selected>' + truckNo + '</option>');
                });
                $('#truck-toggle').html(truckNo);
            }

            function updateSuppliersDropdown(supplierId) {
                const $supplierDropdown = $('#suppliers');
                $supplierDropdown.html('');

                if (selectedSuppliers.size > 0) {
                    selectedSuppliers.forEach(function(supplier) {
                        $supplierDropdown.append('<option value="' + supplierId + '" selected>' + supplier +
                            '</option>');
                        $('#set_supplier_name').val(supplier);
                    });
                } else {
                    $('#set_supplier_name').val('{{ $b_cheque->supplier_name }}');
                    $supplierDropdown.append('<option value="">- Select -</option>');
                    @foreach ($suppliers as $key => $supplier)
                        $supplierDropdown.append(
                            '<option value="{{ $supplier->id_supplier }}" {{ $supplier->id_supplier == $b_cheque->supplier_id ? 'selected' : '' }}>{{ $supplier->supplier_name }} - {{ $supplier->supplier_name_urdu }}</option>'
                        );
                    @endforeach
                }
            }

            $('#truck-table-body').on('click', '.truck-details', function() {
                const checkbox = $(this).find('.truck-checkbox')[0];
                checkbox.checked = !checkbox.checked;
                $(checkbox).trigger('change');
            });

            function filterTruckDetails() {
                const allTrucks = {};

                $('.truck-details').each(function() {
                    const truckNo = $(this).data('truck-no');
                    const truckId = $(this).data('truck-id');
                    const isSelected = selectedTruckNumbers.includes(truckNo);

                    // Track all trucks with their selection status
                    if (!allTrucks[truckNo]) {
                        allTrucks[truckNo] = {
                            count: 0,
                            checked: 0
                        };
                    }
                    allTrucks[truckNo].count++;
                    if (isSelected) {
                        allTrucks[truckNo].checked++;
                    }
                });

                // Enable or disable rows based on the selection count for each truck number
                $('.truck-details').each(function() {
                    const truckNo = $(this).data('truck-no');
                    const allSelected = allTrucks[truckNo].checked === allTrucks[truckNo].count;

                    if (allSelected) {
                        $(this).find('.truck-checkbox').prop('disabled', false); // Enable checkbox
                        $(this).removeClass('disabled');
                    } else {
                        if (selectedTruckNumbers.length > 0 && !selectedTruckNumbers.includes(truckNo)) {
                            $(this).find('.truck-checkbox').prop('disabled', true); // Disable checkbox
                            $(this).addClass('disabled');
                        } else if ($('.truck-checkbox:checked').length == 0) {
                            // $('#selected-trucks').text('Selected Truck: ' + '');
                            $('#truck').html('');
                            if ('{{ $b_cheque->goodReceiptTruck->truck_no }}' != null) {
                                $('#truck-toggle').html('{{ $b_cheque->goodReceiptTruck->truck_no }}');
                            } else {
                                $('#truck-toggle').html('');
                            }
                            $('#set_supplier_name').val('{{ $b_cheque->supplier_name }}');
                            // $('#rent_received').val('{{ $b_cheque->details->rent_recieve_amount }}');
                            $('#rent_received').val('');
                            $(this).find('.truck-checkbox').prop('disabled', false); // Enable checkbox
                            $(this).removeClass('disabled');
                        }
                    }
                });
            }

            function showOnlyThisTruckDetails(searchValue) {
                searchValue = searchValue.toLowerCase();
                document.querySelectorAll('#truck-table-body .truck-details').forEach(function(row) {
                    const cells = row.querySelectorAll('td');
                    let matchFound = false;

                    cells.forEach(function(cell) {
                        if (cell.textContent.toLowerCase().includes(searchValue)) {
                            matchFound = true;
                        }
                    });

                    row.style.display = matchFound ? '' : 'none';
                });
            }
        });
    </script>

    <script>
        $(window).on('load', function() {
            setTimeout(function() {

                $('.dropdown-content').css('display', 'block');
                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>
@endpush
