@extends('layouts.master')

@section('content')
    <style>
        @font-face {
            font-family: 'Jameel Noori Nastaleeq';
            src: url('path/to/JameelNooriNastaleeq.woff') format('woff'),
                url('path/to/JameelNooriNastaleeq.ttf') format('truetype');
        }

        .az-content-label-ur {
            font-family: 'Jameel Noori Nastaleeq', serif;
            font-size: 2.5vh;

            margin-bottom: 15px;
            line-height: 1;
        }

        .urdu-font {
            font-size: 17px;
        }
    </style>
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Goods Receipts</span>
        <span>Edit Goods Receipts</span>
    </div>
    <h2 class="az-content-title" style="display: inline">Edit Goods Receipts
        <span>
            <a href="{{ route('good_receipts.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to List
            </a>
        </span>
    </h2>
    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Edit Goods Receipts</h5>
                <form method="post" action="{{ route('good_receipts.update', $goodReceipt->id_good_rec) }}"
                    id="goodReceiptsForm">
                    @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

                    <!-- Basic Details -->
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="goods_date">Date</label>
                                <input type="date" name="goods_date" class="form-control"
                                    value="{{ $goodReceipt->date }}" required />
                            </div>
                            @error('goods_date')
                                <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" style="float: inline-end;">
                                    <span style="color:red;">*</span> ٹرک نمبر
                                </label>
                                <input type="text" id="truck_toggle" name="truck_number" class="form-control"
                                    value="{{ $goodReceipt->goodReceiptTruck->truck_no }}" required />
                            </div>
                            @error('truck_number')
                                <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" style="float: inline-end;">
                                    <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 }}"
                                            {{ $goodReceipt->supplier_id == $supplier->id_supplier ? 'selected' : '' }}>
                                            {{ $supplier->supplier_name }} - {{ $supplier->supplier_name_urdu }}
                                        </option>
                                    @endforeach
                                </select> <button type="button" style="color:#fff;"
                                    class="btn btn-sm btn-info mt-2 float-end" data-toggle="modal"
                                    data-target="#addSupplierModal">
                                    + Add Supplier
                                </button>
                            </div>
                            @error('suppliers')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                    </div>

                    <!-- Suppliers, Builty Number, Rent Received -->
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">
                                    بلٹی نمبر
                                </label>
                                <input type="text" name="builty_number" class="form-control"
                                    value="{{ $goodReceipt->builty_no }}" />
                            </div>
                            @error('builty_number')
                                <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" style="float: inline-end;">
                                    کرایہ وصول
                                </label>
                                <input type="text" name="rent_received" id="rent_received" class="form-control n-amount"
                                    value="{{ $goodReceipt->rent_recieve }}" />
                            </div>
                            @error('rent_received')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                        <div class="col-md-4">
                            <label class="az-content-label" for="goods_status">Status</label>
                            <select id="goods_status" name="goods_status" class="form-control">
                                <option value="">Select</option>
                                <option value="1" {{ $goodReceipt->status == '1' ? 'selected' : '' }}>Active
                                </option>
                                <option value="0" {{ $goodReceipt->status == '0' ? 'selected' : '' }}>In-Active
                                </option>
                            </select>
                            @error('goods_status')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                    </div>

                    <!-- Details -->
                    <div class="row row-sm mg-b-20">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="az-content-label urdu-font" style="float: inline-end;">تفصیلات</label>
                                <textarea class="form-control" name="details" id="details">{{ $goodReceipt->details }}</textarea>
                            </div>
                            @error('details')
                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                    </div>

                    <!-- Items Section -->
                    <hr class="my-5">
                    <div id="items-wrapper">
                        @foreach ($goodReceipt->goodReceiptDetails as $index => $detail)
                            <div class="row row-sm mg-b-20 shadow p-3 bg-light rounded"
                                id="item-row-{{ $index }}">
                                {{-- For Main Category --}}
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="az-content-label" for="productMainCate{{ $detail->id_grd }}">
                                            Main Category
                                        </label>
                                        <select name="productMainCate[]" id="productMainCate{{ $detail->id_grd }}"
                                            class="form-control item-select"
                                            data-parent-cate-id="{{ $detail->pro_cate_parent_id }}"
                                            data-child-cate-id="{{ $detail->pro_cate_child_id }}"
                                            onchange="checkForParentCate(this.value, {{ $detail->id_grd }})">
                                            <option value="">Select Main Category</option>
                                            @foreach ($productCateMain as $key => $main)
                                                <option value="{{ $main->id_pro_cate_main }}"
                                                    {{ $detail->pro_cate_main_id == $main->id_pro_cate_main ? 'selected' : '' }}>
                                                    {{ $main->products_category_name }} |
                                                    {{ $main->products_category_name_urdu }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    @error('productMainCate')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>

                                {{-- For Parent Category --}}
                                <?php
                                $productsSubCategoryParent = App\ProductsSubCategoryParent::where('id_pro_sub_cat_parent', $detail->pro_cate_parent_id)->get();
                                $display1 = $detail->pro_cate_parent_id != null ? 'block' : 'none';
                                ?>
                                <div class="col-md-2" id="productParentCatShow{{ $detail->id_grd }}"
                                    style="display: {{ $display1 }};">
                                    <div class="form-group">
                                        <label class="az-content-label" for="productParentCate{{ $detail->id_grd }}">
                                            Parent Category
                                        </label>
                                        <select name="productParentCate[]" id="productParentCate{{ $detail->id_grd }}"
                                            class="form-control item-select"
                                            onchange="checkForChildCate(this.value, {{ $detail->id_grd }})">
                                            <option value="">Select Parent Category</option>
                                            @foreach ($productsSubCategoryParent as $key => $parent)
                                                <option value="{{ $parent->id_pro_sub_cat_parent }}"
                                                    {{ $detail->pro_cate_parent_id == $parent->id_pro_sub_cat_parent ? 'selected' : '' }}>
                                                    {{ $parent->name }} |
                                                    {{ $parent->name_urdu }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    @error('productParentCate')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>

                                {{-- For Child Category --}}
                                <?php
                                $productsSubCategoryChild = App\ProductsSubCategoryChild::where('id_pro_sub_cat_child', $detail->pro_cate_child_id)->get();
                                $display2 = $detail->pro_cate_child_id != null ? 'block' : 'none';
                                ?>
                                <div class="col-md-2" id="productChildCatShow{{ $detail->id_grd }}"
                                    style="display: {{ $display2 }};">
                                    <div class="form-group">
                                        <label class="az-content-label" for="productChildCate{{ $detail->id_grd }}">
                                            Child Category
                                        </label>
                                        <select name="productChildCate[]" id="productChildCate{{ $detail->id_grd }}"
                                            class="form-control item-select">
                                            <option value="">Select Child Category</option>
                                            @foreach ($productsSubCategoryChild as $key => $child)
                                                <option value="{{ $child->id_pro_sub_cat_child }}"
                                                    {{ $detail->pro_cate_child_id == $child->id_pro_sub_cat_child ? 'selected' : '' }}>
                                                    {{ $child->name }} |
                                                    {{ $child->name_urdu }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    @error('productChildCate')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>


                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="az-content-label">Marka (مارکہ)</label>
                                        <input type="text" name="marka[]" class="form-control"
                                            value="{{ $detail->marka }}" />
                                    </div>
                                    @error('marka')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="az-content-label">Bori (بوری)</label>
                                        <input type="text" name="bori[]" class="form-control n-amount"
                                            value="{{ $detail->bori }}" />
                                    </div>
                                    @error('bori')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="az-content-label">Weight (وزن)</label>
                                        <input type="text" name="weight[]" oninput="calculateAmount(this)"
                                            class="form-control weight-input n-amount" value="{{ $detail->weight }}" />
                                    </div>
                                    @error('weight')
                                        <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">Remarks (ریمارکس)</label>
                                        <textarea class="form-control" name="remarks[]" cols="30" rows="10">{{ $detail->remarks }}</textarea>
                                    </div>
                                    @error('remarks')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>
                            </div>
                        @endforeach
                    </div>

                    <!-- Add More Button -->
                    <div class="row">
                        <div class="col-lg-12">
                            <button type="button" class="btn btn-az-primary btn-block mt-2" id="add-item">
                                <span class="mdi mdi-arrow-expand-up"></span> Add More
                            </button>
                        </div>
                    </div>

                    {{-- Show Total --}}
                    <div class="row row-sm mg-b-20 mt-5" style="float: right;">
                        <div class="col-12">
                            <h3 style="line-height: 2.5rem;">
                                <span>
                                    Total Bori: <span id="total-bori">0</span>
                                </span>
                                <br>
                                <span>
                                    Total Weight: <span id="total-weight">0</span>
                                </span>
                            </h3>
                        </div>
                    </div>

                    <div class="mt-5">
                        <a href="{{ route('good_receipts.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                        <button type="submit" class="btn btn-az-primary pd-x-20">Save</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="addSupplierModal" tabindex="-1" role="dialog" aria-labelledby="addCustomerModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form id="addSupplierForm" method="POST">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add New Supplier</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>Supplier Name (English)</label>
                            <input type="text" name="supplier_name" id="customer_name" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Supplier Name (Urdu)</label>
                            <input type="text" name="supplier_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')
    <script>
        function initAutoNumeric() {
            document.querySelectorAll('.n-amount').forEach(function(el) {
                if (!AutoNumeric.getAutoNumericElement(el)) { // prevent duplicate init
                    new AutoNumeric(el, {
                        digitGroupSeparator: ',',
                         decimalPlaces: 0,
                        unformatOnSubmit: true
                    });
                }
            });
        }
        $(document).ready(function() {



            // document.querySelectorAll('.n-amount').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', '#addSupplierForm', function(e) {
                e.preventDefault(); // stops page reload ✅

                let form = $(this);

                $.ajax({
                    url: "{{ route('supplier.store') }}",
                    method: "POST",
                    data: form.serialize(),
                    beforeSend: function() {
                        // optional: disable button or show loader
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#mdcancelBtn').click();
                            $('#suppliers').empty().append(
                                '<option value="">- Select -</option>');
                            // Loop through suppliers and create <option> tags
                            response.suppliers.forEach(function(supplier) {
                                const option = `<option value="${supplier.id_supplier}">
                                    ${supplier.supplier_name} | ${supplier.supplier_name_urdu}
                                </option>`;
                                $('#suppliers').append(option);
                            });
                            $('#customer_name').val('')
                            $('#customer_name_urdu').val('')
                            toastr.success('Supplier 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>
        function calculateAmount(element) {
            // Get the closest parent with class "row"
            let row = element.closest('.row');

            // Get the values for weight and rate, with default to 0 if empty
            let weight = parseFloat(row.querySelector('.weight-input').value) || 0;
            let rate = parseFloat(row.querySelector('.rate-input').value) || 0;

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

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

        $(document).ready(function() {
            $("#goods_date").datepicker({
                dateFormat: "yy-mm-dd"
            });

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

            $('.item-select').select2({
                placeholder: "Select Item",
                allowClear: true
            });

            checkAllMainCates();
        });

        function checkAllMainCates() {
            $('[id^=productMainCate]').each(function() {
                var id_grd = $(this).attr('id').replace('productMainCate', '');
                var mainCateId = $(this).val();
                if (mainCateId) {
                    // Get the corresponding parent and child category IDs from the template
                    var parentCateId = $(this).data('parent-cate-id');
                    var childCateId = $(this).data('child-cate-id');
                    checkForParentCate(mainCateId, id_grd, true, parentCateId, childCateId);
                }
            });
        }

        function checkForParentCate(productMainCateId, id_grd, initialLoad = false, parentCateId = null, childCateId =
            null) {
            $.ajax({
                url: '{{ route('check-cate-parent') }}',
                type: 'GET',
                data: {
                    productMainCateId: productMainCateId
                },
                success: function(response) {
                    if (response.productParentCate.length > 0) {
                        let options = '<option value="">Select Parent Category</option>';
                        response.productParentCate.forEach(function(subParentCategory) {
                            options +=
                                `<option value="${subParentCategory.id_pro_sub_cat_parent}">${subParentCategory.name} | ${subParentCategory.name_urdu}</option>`;
                        });
                        $('#productParentCate' + id_grd).html(
                            '<option value="">Select Parent Category</option>');
                        $('#productChildCate' + id_grd).html(
                            '<option value="">Select Child Category</option>');
                        $('#productParentCate' + id_grd).html(options);
                        $('#productParentCatShow' + id_grd).show();

                        if (initialLoad && parentCateId) {
                            $('#productParentCate' + id_grd).val(parentCateId).trigger('change');
                            checkForChildCate(parentCateId, id_grd, childCateId);
                        }
                    } else {
                        $('#productParentCatShow' + id_grd).hide();
                        $('#productChildCatShow' + id_grd).hide();
                    }
                },
                error: function() {
                    alert('Error checking Product Parent Category!');
                }
            });
        }

        function checkForChildCate(productParentCateId, id_grd, childCateId = null) {
            $('#productChildCate' + id_grd).html(
                '<option value="">Select Child Category</option>');
            $.ajax({
                url: '{{ route('check-cate-child') }}',
                type: 'GET',
                data: {
                    productParentCateId: productParentCateId
                },
                success: function(response) {
                    if (response.productChildCate.length > 0) {
                        let options = '<option value="">Select Child Category</option>';
                        response.productChildCate.forEach(function(subChildCategory) {
                            options +=
                                `<option value="${subChildCategory.id_pro_sub_cat_child}">${subChildCategory.name} | ${subChildCategory.name_urdu}</option>`;
                        });
                        $('#productChildCate' + id_grd).html(options);
                        $('#productChildCatShow' + id_grd).show();
                        if (childCateId) {
                            $('#productChildCate' + id_grd).val(childCateId).trigger('change');
                        }
                    } else {
                        $('#productChildCatShow' + id_grd).hide();
                    }
                },
                error: function() {
                    alert('Error checking Product Child Category!');
                }
            });
        }


        document.addEventListener("DOMContentLoaded", function() {
            let itemIndex = {{ $goodReceipt->goodReceiptDetails->count() }};

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

                // Loop through all bori[] inputs
                document.querySelectorAll('input[name="bori[]"]').forEach(function(input) {
                    let raw = AutoNumeric.getNumber(input) || 0; // get raw numeric value
                    totalBori += parseFloat(raw);
                });

                // Loop through weight[] inputs
                document.querySelectorAll('input[name="weight[]"]').forEach(function(input) {
                    let raw = AutoNumeric.getNumber(input) || 0;
                    totalWeight += parseFloat(raw);
                });

                // Format with commas using Intl.NumberFormat
                let formattedBori = new Intl.NumberFormat().format(totalBori);
                let formattedWeight = new Intl.NumberFormat().format(totalWeight);

                // Update innerText
                document.getElementById('total-bori').innerText = formattedBori;
                document.getElementById('total-weight').innerText = formattedWeight;
            }
            initAutoNumeric();
            document.getElementById('items-wrapper').addEventListener('input', function(event) {
                if (event.target.name === 'bori[]' || event.target.name === 'weight[]') {
                    calculateTotals();
                }
            });

            document.querySelectorAll('#items-wrapper .row').forEach(function(row) {
                let removeIcon = document.createElement('i');
                removeIcon.className = 'fa fa-trash-alt text-light remove-item bg-danger p-2 rounded-1';
                removeIcon.style.cursor = 'pointer';
                removeIcon.style.float = 'right';
                removeIcon.style.marginTop = '10px';

                removeIcon.addEventListener('click', function() {
                    if (document.querySelectorAll('#items-wrapper .row').length > 1) {
                        this.closest('.row').remove();
                        calculateTotals();
                    } else {
                        alert("You cannot delete the last remaining item.");
                    }
                });

                let actionCol = document.createElement('div');
                actionCol.className = 'col-md-12';
                actionCol.appendChild(removeIcon);
                row.appendChild(actionCol);
            });

            document.getElementById('add-item').addEventListener('click', function() {
                let newRow = `
                    <div class="row row-sm mg-b-20 shadow p-3 bg-light rounded mt-5" id="item-row-${itemIndex}">
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label" for="productMainCate">Main Category</label>
                                <select name="productMainCate[]" class="form-control item-select productMainCateSelect" onchange="checkForParentCateRow(this.value, ${itemIndex})"
                                    data-row-id="${itemIndex}">
                                    <option value="">Select Main Category</option>
                                    @foreach ($productCateMain as $key => $main)
                                        <option value="{{ $main->id_pro_cate_main }}">
                                            {{ $main->products_category_name }} |
                                            {{ $main->products_category_name_urdu }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2" id="productParentCatShow-${itemIndex}" style="display: none;">
                            <div class="form-group">
                                <label class="az-content-label" for="productParentCate">Parent Category</label>
                                <select name="productParentCate[]" class="form-control item-select productParentCateSelect" onchange="checkForChildCateRow(this.value, ${itemIndex})"
                                    data-row-id="${itemIndex}">
                                    <option value="">Select Parent Category</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2" id="productChildCatShow-${itemIndex}" style="display: none;">
                            <div class="form-group">
                                <label class="az-content-label" for="productChildCate">Child Category</label>
                                <select name="productChildCate[]" class="form-control item-select">
                                    <option value="">Select Child Category</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label">Marka (مارکہ)</label>
                                <input type="text" name="marka[]" class="form-control" />
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label">Bori (بوری)</label>
                                <input type="text" name="bori[]" class="form-control n-amount" />
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label">Weight (وزن)</label>
                                <input type="text" name="weight[]" class="form-control weight-input n-amount" oninput="calculateAmount(this)" />
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label">Remarks (ریمارکس)</label>
                                <textarea class="form-control" name="remarks[]" cols="30" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <i class="fa fa-trash-alt text-light remove-item bg-danger p-2 rounded-1" style="cursor: pointer; float: right; margin-top: 10px;"></i>
                        </div>
                    </div>
                    `;
                // Append the new row
                document.getElementById('items-wrapper').insertAdjacentHTML('beforeend', newRow);

                // Re-initialize select2 for the new item-select
                $(`#item-row-${itemIndex} .item-select`).select2({
                    placeholder: "Select Item",
                    allowClear: true
                });

                initAutoNumeric();

                // Add event listener for remove icon
                document.querySelector(`#item-row-${itemIndex} .remove-item`).addEventListener('click',
                    function() {
                        if (document.querySelectorAll('#items-wrapper .row').length > 1) {
                            this.closest('.row').remove();
                            calculateTotals();
                        } else {
                            alert("You cannot delete the last remaining item.");
                        }
                    });

                // Increment the item index for the next row
                itemIndex++;
            });

            calculateTotals();
        });

        function checkForParentCateRow(productMainCateId, rowId) {
            $.ajax({
                url: '{{ route('check-cate-parent') }}',
                type: 'GET',
                data: {
                    productMainCateId: productMainCateId
                },
                success: function(response) {
                    if (Array.isArray(response.productParentCate) && 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>`;
                        });
                        $(`#productParentCatShow-${rowId} select`).html(options);
                        $(`#productParentCatShow-${rowId}`).show();
                    } else {
                        $(`#productParentCatShow-${rowId}`).hide();
                        $(`#productChildCatShow-${rowId}`).hide();
                    }
                },
                error: function() {
                    alert('Error checking Product Parent Category!');
                }
            });
        }

        function checkForChildCateRow(productParentCateId, rowId) {
            $.ajax({
                url: '{{ route('check-cate-child') }}',
                type: 'GET',
                data: {
                    productParentCateId: productParentCateId
                },
                success: function(response) {
                    if (Array.isArray(response.productChildCate) && 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>`;
                        });
                        $(`#productChildCatShow-${rowId} select`).html(options);
                        $(`#productChildCatShow-${rowId}`).show();
                    } else {
                        $(`#productChildCatShow-${rowId}`).hide();
                    }
                },
                error: function() {
                    alert('Error checking Product Child Category!');
                }
            });
        }

        // Custom Keys Work
        document.addEventListener('DOMContentLoaded', function() {
            // Prevent form submission on Enter key
            document.getElementById('goodReceiptsForm').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('goodReceiptsForm').submit(); // Submit the form
                }
            });
        });
    </script>


    <script>
        $(function() {

            $(window).on('load', function() {
                setTimeout(function() {
                    $('#truck-toggle').trigger('focus');
                }, 600);
            });
            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
