@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="row">
            <div class="col-sm-12">
                <h3 class="page-title">Edit Goods Receiving Note</h3>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('goods-receivings.index') }}">Goods Receiving Notes</a></li>
                    <li class="breadcrumb-item active">Edit Goods Receiving Note</li>
                </ul>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-body">
                    <form action="{{ route('goods-receivings.update', $goodsReceiving->id) }}" method="POST"
                        class="needs-validation" novalidate>
                        @csrf
                        @method('PUT')
                        <div class="form-row row">
                            <div class="mb-3 col-md-4">
                                <label for="code">DOC NO</label>
                                <input type="text" class="form-control" name="code" id="code" readonly
                                    value="{{ $goodsReceiving->code ?? '' }}">
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="invoice_id">PO<span class="text-danger">*</span></label>
                                <select name="invoice" readonly disabled id="invoice_id"
                                    onchange="getInvoiceDetails(this.value);" class="js-example-basic-single select2"
                                    required>
                                    <option value="">Select PO</option>
                                    @isset($invoices)
                                        <option value="{{ $invoices->id }}" @selected(true)>
                                            {{ $invoices->code }}
                                        </option>
                                    @endisset
                                </select>
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="item_id">PO Item(s) <span class="text-danger">*</span></label>
                                <select name="item_id[]" multiple readonly id="item_id" disabled
                                    class="js-example-basic-single select2" required>
                                    @foreach ($goodsReceiving?->items ?? [] as $grnItem)
                                        <option value="{{ $grnItem->id }}"
                                            data-raw_material_item_id="{{ $grnItem->raw_material_item_id }}">
                                            {{ $grnItem->rawMaterialItem?->name ?? '-' }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            {{-- Supplier fields --}}
                            <div class="mb-3 col-md-6">
                                <label for="supplier">Supplier</label>
                                <input type="text" class="form-control" name="supplier_name" id="supplier_name"
                                    placeholder="Supplier Name" value="" readonly>
                                <input type="hidden" name="supplier" id="supplier_id" value="">
                            </div>

                            <div class="mb-3 col-md-6">
                                <label for="generic_name">Supplier Code</label>
                                <input type="text" class="form-control" name="supplier_code" id="supplier_code"
                                    placeholder="Supplier Code" required value="" readonly>
                            </div>

                            {{-- Items + GRN Batches --}}
                            <div class="col-md-12">
                                <div class="card border-0 mb-0" id="item-group">
                                    {{-- @foreach ($goodsReceiving->items as $grnItem)
                                        @include('admin.goods-receivings.item-details', [
                                            'isEdit' => true,
                                            'item' => $grnItem,
                                            'itemBatches' => $grnItem->grnItemBatches ?? [],
                                        ])
                                    @endforeach --}}
                                </div>
                            </div>

                            <div class="mb-3 col-md">
                                <label for="total_amount">Grand Amount</label>
                                <input type="number" class="form-control" name="total_amount" id="total_amount"
                                    value="{{ old('total_amount', $goodsReceiving->total_amount) }}" readonly>
                            </div>
                        </div>

                        <a class="btn btn-secondary" href="{{ route('goods-receivings.index') }}">Cancel</a>
                        <input type="hidden" name="is_approved" id="is_approved" value="0">

                        <button type="submit" class="btn btn-primary"
                            onclick="document.getElementById('is_approved').value = 0;">
                            Save
                        </button>

                        @if (auth()->user()->hasPermission('Document Approval Edit'))
                            <button type="submit" class="btn btn-success"
                                onclick="document.getElementById('is_approved').value = 1;">
                                Approve
                            </button>
                        @endif
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
        const grn = @json($goodsReceiving);
        const grnItems = @json($goodsReceiving->items ?? []);
        window.onload = async function() {
            await getInvoiceDetails(grn.invoice_id);
            $.each(grnItems, async function(_, el) {
                $('#item_id').val(el.id).trigger('change');
            });
        };

        let loadedItems = new Set();

        $('#item_id').on('change', async function() {
            const selectedIds = $(this).val() || []; // all selected values

            if (selectedIds.length === 0) {
                $('#item-group').empty();
                loadedItems = new Set(); // reset cache
                return;
            }

            const newIds = selectedIds.filter(id => !loadedItems.has(id)); // only fresh ids

            for (let id of newIds) {
                const rawMaterialItemId = $(this).find(`option[value="${id}"]`)
                    .attr('data-raw_material_item_id');

                const url = "{{ route('goods-receivings.ajax-items-details') }}";
                const data = {
                    id: id,
                    grnId: grn.id,
                    grnItemId: rawMaterialItemId,
                    isEdit: true,
                    _token: "{{ csrf_token() }}"
                };

                try {
                    const res = await sendPostRequest(url, data);
                    if (res.success) {
                        $("#item-group").append(res.view);
                        loadedItems.add(id); // mark as processed
                    } else {
                        toastr.error('No PO Items Found for ' + id);
                    }
                } catch (err) {
                    console.error("Fetch failed for item:", id, err);
                }
            }
        });

        document.addEventListener('click', function(e) {
            // Handle Add GRN Row
            if (e.target.closest('.add-grn-row')) {
                const btn = e.target.closest('.add-grn-row');

                // Find nearest grn-rows-container above the button
                const grnContainer = btn.closest('.item-set')?.querySelector('.grn-rows-container');
                if (!grnContainer) return;

                const rows = grnContainer.querySelectorAll('.grn-row');
                const lastIndex = rows.length;
                const index = grnContainer.dataset.index;

                const firstRow = rows[0];
                const clone = firstRow.cloneNode(true);

                // Update name attributes and reset values
                clone.querySelectorAll('input').forEach(input => {
                    const name = input.name;
                    if (!name) return;

                    const newName = name.replace(/\[grn_items]\[\d+]/, `[grn_items][${lastIndex}]`);
                    input.name = newName;

                    if (name.includes('[unit_price]') || name.includes('[unit]')) {
                        // keep value
                    } else {
                        input.value = '';
                    }
                });

                // Show trash icon
                const removeCol = clone.querySelector('.remove-grn-row')?.closest('.col-md-auto');
                if (removeCol) removeCol.classList.remove('d-none');

                grnContainer.appendChild(clone);
            }

            // Handle Remove GRN Row
            if (e.target.closest('.remove-grn-row')) {
                e.preventDefault();
                const row = e.target.closest('.grn-row');
                if (row) row.remove();
                calculateGoodsRecievingAmount();
            }
        });

        function generateItemOptions() {
            const itemSets = document.querySelectorAll('#item-group .item-set');
            let options = '';
            itemSets.forEach((itemSet, index) => {
                const description = itemSet.querySelector('textarea[name*="[description]"]')?.value ||
                    `Item ${index + 1}`;
                options +=
                    `<option value="${index}">${description.substring(0, 50)}${description.length > 50 ? '...' : ''}</option>`;
            });
            return options;
        }

        function updateVendorBillItemDetails(select) {
            const itemIndex = select.value;
            if (itemIndex === '') return;

            const itemSet = document.querySelectorAll('#item-group .item-set')[itemIndex];
            const description = itemSet.querySelector('textarea[name*="[description]"]')?.value ||
                `Item ${parseInt(itemIndex) + 1}`;

            // You can add more logic here to auto-fill other fields based on the selected item
        }

        function removeVendorBillRow(button) {
            button.closest('.vendor-bill-row').remove();
        }

        function calculateVendorBillTotal() {
            let total = 0;
            document.querySelectorAll('input[name*="[amount]"]').forEach(input => {
                total += parseFloat(input.value) || 0;
            });
            // You can update a total field here if needed
        }

        // Calculate total amount for goods receiving
        function calculateGoodsRecievingAmount() {
            let total = 0;
            document.querySelectorAll('.product_total').forEach(input => {
                total += parseFloat(input.value) || 0;
            });
            document.getElementById('total_amount').value = total.toFixed(2);
        }
    </script>
    @include('admin.goods-receivings.validation-script')
@endsection
