    @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: 2vh;

                /* margin-bottom: 15px; */
                line-height: 2;
            }

            .urdu-font {
                font-size: 17px;
            }
        </style>
        <!-- Breadcrumb and Page Title -->
        <div class="az-content-breadcrumb">
            <span> Purchase Order</span>
            <span>Add Purchase Order</span>
        </div>
        <h2 class="az-content-title" style="display: inline">Add New Purchase Order
            <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">Add Purchase Order</h5>
                    <form method="post" action="{{ route('po.store') }}" id="goodReceiptsForm">
                        @csrf
                        <!-- 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-12">
                                <div class="card shadow-sm border-0 h-100">

                                    <!-- Card Header -->
                                    <div class="card-header   py-2">
                                        <h6 class="mb-0 urdu-font">
                                            Supplier Details
                                        </h6>
                                    </div>

                                    <div class="card-body">

                                        <!-- Select Supplier -->
                                        <div class="form-group mb-3 ">
                                            <label class="az-content-label urdu-font d-block ">
                                                Select Supplier
                                            </label>

                                            <div class="d-flex gap-2">
                                                <select class="form-control select2" style="width:85%;" name="suppliers"
                                                    id="suppliers" required>
                                                    <option value="">- Select -</option>
                                                    @foreach ($suppliers as $supplier)
                                                        <option value="{{ $supplier->id_supplier }}">
                                                            {{ $supplier->supplier_name }} |
                                                            {{ $supplier->supplier_name_urdu }}
                                                        </option>
                                                    @endforeach
                                                </select>

                                                <button type="button" class="btn btn-info btn-sm" data-toggle="modal"
                                                    data-target="#addSupplierModal">
                                                    + Add
                                                </button>
                                            </div>

                                            @error('suppliers')
                                                <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                            @enderror
                                        </div>

                                        <hr class="my-3">

                                        <!-- Supplier Details -->
                                        <div id="supplierDetails" style="display:none;">
                                            <h6 class="text-dark fw-bold urdu-font mb-2">
                                                Supplier Details
                                            </h6>

                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p class="mb-1">
                                                        <strong>Name:</strong>
                                                        <span id="supName"></span>
                                                    </p>
                                                    <p class="mb-1">
                                                        <strong>Phone Number :</strong>
                                                        <span id="supPhone"></span>
                                                    </p>
                                                </div>

                                                <div class="col-md-6">
                                                    <p class="mb-1">
                                                        <strong>Address</strong>
                                                        <span id="supAddress"></span>
                                                    </p>
                                                    <p class="mb-1">
                                                        <strong>Email</strong>
                                                        <span id="supEmail"></span>
                                                    </p>
                                                </div>
                                            </div>

                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>


                        <!-- Details -->
                        <div class="row row-sm mg-b-20">

                            <div class="col-md-4">
                                <div class="form-group mb-3">
                                    <label class="az-content-label" for="order_date">Date</label>
                                    <input type="text" id="order_date" name="order_date" class="form-control"
                                        value="{{ old('order_ate') }}" placeholder="dd/mm/yyyy" readonly />
                                </div>
                                @error('order_date')
                                    <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                @enderror
                            </div>
                            <div class="col-md-8">
                                <div class="form-group">
                                    <label class="az-content-label " style="float: inline-end;">Details</label>
                                    <textarea class="form-control" name="details" id="details">{{ old('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">
                            <h3>Select Items</h3>
                            <div class="row delete_row row-sm mg-b-20 shadow p-3 bg-light rounded" id="item-row-0">
                                {{-- For Main Category --}}
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label class="az-content-label" for="productMainCate">Main Category</label>
                                        <select name="productMainCate[]" id="productMainCate" class="form-control"
                                            onchange="checkForParentCate(this.value)">
                                            <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>
                                    @error('productMainCate')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>

                                {{-- For Parent Category --}}
                                <div class="col-md-2" id="productParentCatShow" style="display: none;">
                                    <div class="form-group">
                                        <label class="az-content-label" for="productParentCate">Parent Category</label>
                                        <select name="productParentCate[]" id="productParentCate" class="form-control"
                                            onchange="checkForChildCate(this.value)">
                                            <option value="">Select Parent Category</option>
                                        </select>
                                    </div>
                                    @error('productParentCate')
                                        <span class="form-text text-danger"><strong>{{ $message }}</strong></span>
                                    @enderror
                                </div>

                                {{-- For Child Category --}}
                                <div class="col-md-2" id="productChildCatShow" style="display: none;">
                                    <div class="form-group">
                                        <label class="az-content-label" for="productChildCate">Child Category</label>
                                        <select name="productChildCate[]" id="productChildCate" class="form-control">
                                            <option value="">Select Child Category</option>
                                        </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" />
                                    </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="number" name="bori[]" required class="form-control" />
                                    </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="number" name="weight[]" oninput="calculateAmount(this)"
                                            class="form-control weight-input" />
                                    </div>
                                    @error('weight')
                                        <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">Rate (ریٹ)</label>
                                        <input type="number" name="rate[]" class="form-control rate-input"
                                            oninput="calculateAmount(this)" />
                                    </div>
                                    @error('rate')
                                        <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">Amount (رقم)</label>
                                        <input type="number" name="amount[]" class="form-control amount-input"
                                            readonly />
                                    </div>
                                </div>
                            </div>
                        </div>

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

                        <!-- Show Total -->
                        <div class="row row-sm mg-b-20 mt-5" style="float: right;">
                            <div class="col-md-6 mt-2">
                                <h3 style="line-height: 2.5rem;">

                                    <span>
                                        Total Amount: <span id="total-amount">0</span>
                                    </span>

                                </h3>
                            </div>
                            <div class="col-md-12 mt-4">
                                <div class="form-group">
                                    <label class="az-content-label">Labour Charges</label>
                                    <input type="number" name="labour_charges" id="labour_charges"
                                        class="form-control " />
                                </div>
                                <div class="form-group">
                                    <label class="az-content-label">Local Charges</label>
                                    <input type="number" name="local_charges" id="local_charges"
                                        class="form-control " />
                                </div>
                                <div class="form-group">
                                    <label class="az-content-label">Weight Charges</label>
                                    <input type="number" name="weight_charges" id="weight_charges"
                                        class="form-control " />
                                </div>
                                <div class="form-group">
                                    <label class="az-content-label">Custom Charges</label>
                                    <input type="number" name="custom_charges" id="custom_charges"
                                        class="form-control custom-chrg-input" />
                                </div>
                                <div class="form-group mt-2">
                                    <label class="az-content-label">Tax</label>
                                    <input type="number" name="tax" id="tax"
                                        class="form-control tax-input" />
                                </div>
                            </div>


                            <div class="col-md-12 mt-2">
                                <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>

                                    <br>
                                    <span>
                                        Grand Total: <span id="grand-total">0</span>
                                    </span>
                                </h3>
                            </div>
                        </div>

                        <!-- Submit and Cancel Buttons -->
                        <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')
        {{-- Instant Add Supplier Modal Script  --}}
        <script>
            $(document).ready(function() {
                $(function() {
                    $(".date").datepicker({
                        dateFormat: "yy-mm-dd"
                    });
                });
                $('#suppliers').on('change', function() {
                    let id = $(this).val();

                    if (!id) {
                        $('#supplierDetails').hide();
                        return;
                    }

                    $.ajax({
                        url: "{{ url('/get-supplier-details/') }}/" + id,
                        type: "GET",
                        success: function(data) {
                            $('#supName').text(data.supplier_name);
                            $('#supPhone').text(data.supplier_phone);
                            $('#supAddress').text(data.supplier_address);
                            $('#supEmail').text(data.supplier_email);

                            $('#supplierDetails').show();
                        }
                    });
                });
            });
        </script>
        <script>
            $(document).ready(function() {
                // 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>
            document.addEventListener('keydown', function(event) {
                if ((event.ctrlKey || event.metaKey) && event.key === 's') {
                    event.preventDefault();

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

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

            function calculateAmount(element) {
                // Get the closest row
                let row = element.closest('.row');

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

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


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


                // Recalculate totals if needed
                calculateTotals();
            }


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

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

            $(document).ready(function() {
                // $("#order_date").datepicker({
                //     dateFormat: "yy-mm-dd"
                // });
                var today = new Date();
                var formattedDate = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' +
                    today.getDate()).slice(-2);

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

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

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

                $('#productMainCate').select2({
                    // theme: 'default',
                    placeholder: "Select Main Category",
                    allowClear: true
                });

                $('#productParentCate').select2({
                    // theme: 'default',
                    placeholder: "Select Panret Category",
                    allowClear: true
                });

                $('#productChildCate').select2({
                    // theme: 'default',
                    placeholder: "Select Child Category",
                    allowClear: true
                });
            });

            document.addEventListener("DOMContentLoaded", function() {
                let itemIndex = 1;

                // Function to calculate and update total bori and weight
                function calculateTotals() {
                    let totalBori = 0;
                    let totalWeight = 0;
                    let totalAmount = 0;


                    document.querySelectorAll('input[name="bori[]"]').forEach(function(boriInput) {
                        totalBori += parseFloat(boriInput.value) || 0;
                    });

                    document.querySelectorAll('input[name="weight[]"]').forEach(function(weightInput) {
                        totalWeight += parseFloat(weightInput.value) || 0;
                    });

                    document.querySelectorAll('input[name="amount[]"]').forEach(function(amountinput) {
                        totalAmount += parseFloat(amountinput.value) || 0;
                    });


                    let customCharges = parseFloat(document.getElementById('custom_charges').value) || 0;
                    let labourCharges = parseFloat(document.getElementById('labour_charges').value) || 0;
                    let localCharges = parseFloat(document.getElementById('local_charges').value) || 0;
                    let weightCharges = parseFloat(document.getElementById('weight_charges').value) || 0;
                    let tax = parseFloat(document.getElementById('tax').value) || 0;

                    let grandTotal = totalAmount + customCharges + tax + labourCharges + localCharges + weightCharges;
                    document.getElementById('total-bori').innerText = totalBori;
                    document.getElementById('total-weight').innerText = totalWeight;
                    document.getElementById('total-amount').innerText = parseFloat(totalAmount);
                    document.getElementById('grand-total').innerText = parseFloat(grandTotal);
                }

                // Event listener to recalculate totals when bori or weight fields are changed
                document.getElementById('items-wrapper').addEventListener('input', function(event) {
                    if (event.target.name === 'bori[]' || event.target.name === 'weight[]' || event.target
                        .name === 'rate[]') {
                        calculateTotals();
                    }
                });

                document.querySelectorAll('#custom_charges, #tax ,#labour_charges, #local_charges ,#weight_charges').forEach(function(el) {
                    el.addEventListener('input', calculateTotals);
                });
            });

            let itemIndex = 1;
            document.getElementById('add-more').addEventListener('click', function() {
                // Generate the new row HTML
                let newRow = `
                    <div class="row delete_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="number" name="bori[]" required class="form-control" />
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="az-content-label">Weight (وزن)</label>
                                <input type="number" name="weight[]" class="form-control weight-input" oninput="calculateAmount(this)" />
                            </div>
                        </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="az-content-label">Rate (ریٹ)</label>
                            <input type="number" name="rate[]" class="form-control rate-input" oninput="calculateAmount(this)" />
                        </div>
                        </div>

                        <div class="col-md-2">
                        <div class="form-group">
                            <label class="az-content-label">Amount (رقم)</label>
                            <input type="number" name="amount[]" class="form-control amount-input" readonly />
                        </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 Products",
                    allowClear: true
                });

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

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

            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-more').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براہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
                        );
                    }
                }
            });

            // Function to show error notification
            function showErrorNotification(message) {
                const notification = document.getElementById('errorNotification');
                const errorMessage = document.getElementById('errorMessage');

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

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

            // Optional: Define updateBoriDetails if necessary
            function updateBoriDetails() {
                // Your logic to update details after deleting a row
            }

            // 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>
    @endpush
